Move ossl_sleep() to e_os.h and use it in apps
[openssl.git] / crypto / bio / bio_lib.c
1 /*
2  * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <errno.h>
12 #include <openssl/crypto.h>
13 #include "bio_local.h"
14
15 /*
16  * Helper macro for the callback to determine whether an operator expects a
17  * len parameter or not
18  */
19 #define HAS_LEN_OPER(o) ((o) == BIO_CB_READ || (o) == BIO_CB_WRITE \
20                          || (o) == BIO_CB_GETS)
21
22 /*
23  * Helper function to work out whether to call the new style callback or the old
24  * one, and translate between the two.
25  *
26  * This has a long return type for consistency with the old callback. Similarly
27  * for the "long" used for "inret"
28  */
29 static long bio_call_callback(BIO *b, int oper, const char *argp, size_t len,
30                               int argi, long argl, long inret,
31                               size_t *processed)
32 {
33     long ret;
34     int bareoper;
35
36     if (b->callback_ex != NULL)
37         return b->callback_ex(b, oper, argp, len, argi, argl, inret, processed);
38
39     /* Strip off any BIO_CB_RETURN flag */
40     bareoper = oper & ~BIO_CB_RETURN;
41
42     /*
43      * We have an old style callback, so we will have to do nasty casts and
44      * check for overflows.
45      */
46     if (HAS_LEN_OPER(bareoper)) {
47         /* In this case |len| is set, and should be used instead of |argi| */
48         if (len > INT_MAX)
49             return -1;
50
51         argi = (int)len;
52     }
53
54     if (inret > 0 && (oper & BIO_CB_RETURN) && bareoper != BIO_CB_CTRL) {
55         if (*processed > INT_MAX)
56             return -1;
57         inret = *processed;
58     }
59
60     ret = b->callback(b, oper, argp, argi, argl, inret);
61
62     if (ret > 0 && (oper & BIO_CB_RETURN) && bareoper != BIO_CB_CTRL) {
63         *processed = (size_t)ret;
64         ret = 1;
65     }
66
67     return ret;
68 }
69
70 BIO *BIO_new_ex(OSSL_LIB_CTX *libctx, const BIO_METHOD *method)
71 {
72     BIO *bio = OPENSSL_zalloc(sizeof(*bio));
73
74     if (bio == NULL) {
75         ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
76         return NULL;
77     }
78
79     bio->libctx = libctx;
80     bio->method = method;
81     bio->shutdown = 1;
82     bio->references = 1;
83
84     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_BIO, bio, &bio->ex_data))
85         goto err;
86
87     bio->lock = CRYPTO_THREAD_lock_new();
88     if (bio->lock == NULL) {
89         ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
90         CRYPTO_free_ex_data(CRYPTO_EX_INDEX_BIO, bio, &bio->ex_data);
91         goto err;
92     }
93
94     if (method->create != NULL && !method->create(bio)) {
95         ERR_raise(ERR_LIB_BIO, ERR_R_INIT_FAIL);
96         CRYPTO_free_ex_data(CRYPTO_EX_INDEX_BIO, bio, &bio->ex_data);
97         CRYPTO_THREAD_lock_free(bio->lock);
98         goto err;
99     }
100     if (method->create == NULL)
101         bio->init = 1;
102
103     return bio;
104
105 err:
106     OPENSSL_free(bio);
107     return NULL;
108 }
109
110 BIO *BIO_new(const BIO_METHOD *method)
111 {
112     return BIO_new_ex(NULL, method);
113 }
114
115 int BIO_free(BIO *a)
116 {
117     int ret;
118
119     if (a == NULL)
120         return 0;
121
122     if (CRYPTO_DOWN_REF(&a->references, &ret, a->lock) <= 0)
123         return 0;
124
125     REF_PRINT_COUNT("BIO", a);
126     if (ret > 0)
127         return 1;
128     REF_ASSERT_ISNT(ret < 0);
129
130     if (a->callback != NULL || a->callback_ex != NULL) {
131         ret = (int)bio_call_callback(a, BIO_CB_FREE, NULL, 0, 0, 0L, 1L, NULL);
132         if (ret <= 0)
133             return ret;
134     }
135
136     if ((a->method != NULL) && (a->method->destroy != NULL))
137         a->method->destroy(a);
138
139     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_BIO, a, &a->ex_data);
140
141     CRYPTO_THREAD_lock_free(a->lock);
142
143     OPENSSL_free(a);
144
145     return 1;
146 }
147
148 void BIO_set_data(BIO *a, void *ptr)
149 {
150     a->ptr = ptr;
151 }
152
153 void *BIO_get_data(BIO *a)
154 {
155     return a->ptr;
156 }
157
158 void BIO_set_init(BIO *a, int init)
159 {
160     a->init = init;
161 }
162
163 int BIO_get_init(BIO *a)
164 {
165     return a->init;
166 }
167
168 void BIO_set_shutdown(BIO *a, int shut)
169 {
170     a->shutdown = shut;
171 }
172
173 int BIO_get_shutdown(BIO *a)
174 {
175     return a->shutdown;
176 }
177
178 void BIO_vfree(BIO *a)
179 {
180     BIO_free(a);
181 }
182
183 int BIO_up_ref(BIO *a)
184 {
185     int i;
186
187     if (CRYPTO_UP_REF(&a->references, &i, a->lock) <= 0)
188         return 0;
189
190     REF_PRINT_COUNT("BIO", a);
191     REF_ASSERT_ISNT(i < 2);
192     return i > 1;
193 }
194
195 void BIO_clear_flags(BIO *b, int flags)
196 {
197     b->flags &= ~flags;
198 }
199
200 int BIO_test_flags(const BIO *b, int flags)
201 {
202     return (b->flags & flags);
203 }
204
205 void BIO_set_flags(BIO *b, int flags)
206 {
207     b->flags |= flags;
208 }
209
210 BIO_callback_fn BIO_get_callback(const BIO *b)
211 {
212     return b->callback;
213 }
214
215 void BIO_set_callback(BIO *b, BIO_callback_fn cb)
216 {
217     b->callback = cb;
218 }
219
220 BIO_callback_fn_ex BIO_get_callback_ex(const BIO *b)
221 {
222     return b->callback_ex;
223 }
224
225 void BIO_set_callback_ex(BIO *b, BIO_callback_fn_ex cb)
226 {
227     b->callback_ex = cb;
228 }
229
230 void BIO_set_callback_arg(BIO *b, char *arg)
231 {
232     b->cb_arg = arg;
233 }
234
235 char *BIO_get_callback_arg(const BIO *b)
236 {
237     return b->cb_arg;
238 }
239
240 const char *BIO_method_name(const BIO *b)
241 {
242     return b->method->name;
243 }
244
245 int BIO_method_type(const BIO *b)
246 {
247     return b->method->type;
248 }
249
250 /*
251  * This is essentially the same as BIO_read_ex() except that it allows
252  * 0 or a negative value to indicate failure (retryable or not) in the return.
253  * This is for compatibility with the old style BIO_read(), where existing code
254  * may make assumptions about the return value that it might get.
255  */
256 static int bio_read_intern(BIO *b, void *data, size_t dlen, size_t *readbytes)
257 {
258     int ret;
259
260     if (b == NULL) {
261         ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
262         return -1;
263     }
264     if (b->method == NULL || b->method->bread == NULL) {
265         ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_METHOD);
266         return -2;
267     }
268
269     if ((b->callback != NULL || b->callback_ex != NULL) &&
270         ((ret = (int)bio_call_callback(b, BIO_CB_READ, data, dlen, 0, 0L, 1L,
271                                        NULL)) <= 0))
272         return ret;
273
274     if (!b->init) {
275         ERR_raise(ERR_LIB_BIO, BIO_R_UNINITIALIZED);
276         return -1;
277     }
278
279     ret = b->method->bread(b, data, dlen, readbytes);
280
281     if (ret > 0)
282         b->num_read += (uint64_t)*readbytes;
283
284     if (b->callback != NULL || b->callback_ex != NULL)
285         ret = (int)bio_call_callback(b, BIO_CB_READ | BIO_CB_RETURN, data,
286                                      dlen, 0, 0L, ret, readbytes);
287
288     /* Shouldn't happen */
289     if (ret > 0 && *readbytes > dlen) {
290         ERR_raise(ERR_LIB_BIO, ERR_R_INTERNAL_ERROR);
291         return -1;
292     }
293
294     return ret;
295 }
296
297 int BIO_read(BIO *b, void *data, int dlen)
298 {
299     size_t readbytes;
300     int ret;
301
302     if (dlen < 0)
303         return 0;
304
305     ret = bio_read_intern(b, data, (size_t)dlen, &readbytes);
306
307     if (ret > 0) {
308         /* *readbytes should always be <= dlen */
309         ret = (int)readbytes;
310     }
311
312     return ret;
313 }
314
315 int BIO_read_ex(BIO *b, void *data, size_t dlen, size_t *readbytes)
316 {
317     return bio_read_intern(b, data, dlen, readbytes) > 0;
318 }
319
320 static int bio_write_intern(BIO *b, const void *data, size_t dlen,
321                             size_t *written)
322 {
323     int ret;
324
325     if (b == NULL) {
326         ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
327         return -1;
328     }
329     if (b->method == NULL || b->method->bwrite == NULL) {
330         ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_METHOD);
331         return -2;
332     }
333
334     if ((b->callback != NULL || b->callback_ex != NULL) &&
335         ((ret = (int)bio_call_callback(b, BIO_CB_WRITE, data, dlen, 0, 0L, 1L,
336                                        NULL)) <= 0))
337         return ret;
338
339     if (!b->init) {
340         ERR_raise(ERR_LIB_BIO, BIO_R_UNINITIALIZED);
341         return -1;
342     }
343
344     ret = b->method->bwrite(b, data, dlen, written);
345
346     if (ret > 0)
347         b->num_write += (uint64_t)*written;
348
349     if (b->callback != NULL || b->callback_ex != NULL)
350         ret = (int)bio_call_callback(b, BIO_CB_WRITE | BIO_CB_RETURN, data,
351                                      dlen, 0, 0L, ret, written);
352
353     return ret;
354 }
355
356 int BIO_write(BIO *b, const void *data, int dlen)
357 {
358     size_t written;
359     int ret;
360
361     if (dlen < 0)
362         return 0;
363
364     ret = bio_write_intern(b, data, (size_t)dlen, &written);
365
366     if (ret > 0) {
367         /* *written should always be <= dlen */
368         ret = (int)written;
369     }
370
371     return ret;
372 }
373
374 int BIO_write_ex(BIO *b, const void *data, size_t dlen, size_t *written)
375 {
376     return bio_write_intern(b, data, dlen, written) > 0;
377 }
378
379 int BIO_puts(BIO *b, const char *buf)
380 {
381     int ret;
382     size_t written = 0;
383
384     if (b == NULL) {
385         ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
386         return -1;
387     }
388     if (b->method == NULL || b->method->bputs == NULL) {
389         ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_METHOD);
390         return -2;
391     }
392
393     if (b->callback != NULL || b->callback_ex != NULL) {
394         ret = (int)bio_call_callback(b, BIO_CB_PUTS, buf, 0, 0, 0L, 1L, NULL);
395         if (ret <= 0)
396             return ret;
397     }
398
399     if (!b->init) {
400         ERR_raise(ERR_LIB_BIO, BIO_R_UNINITIALIZED);
401         return -1;
402     }
403
404     ret = b->method->bputs(b, buf);
405
406     if (ret > 0) {
407         b->num_write += (uint64_t)ret;
408         written = ret;
409         ret = 1;
410     }
411
412     if (b->callback != NULL || b->callback_ex != NULL)
413         ret = (int)bio_call_callback(b, BIO_CB_PUTS | BIO_CB_RETURN, buf, 0, 0,
414                                      0L, ret, &written);
415
416     if (ret > 0) {
417         if (written > INT_MAX) {
418             ERR_raise(ERR_LIB_BIO, BIO_R_LENGTH_TOO_LONG);
419             ret = -1;
420         } else {
421             ret = (int)written;
422         }
423     }
424
425     return ret;
426 }
427
428 int BIO_gets(BIO *b, char *buf, int size)
429 {
430     int ret;
431     size_t readbytes = 0;
432
433     if (b == NULL) {
434         ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
435         return -1;
436     }
437     if (b->method == NULL || b->method->bgets == NULL) {
438         ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_METHOD);
439         return -2;
440     }
441
442     if (size < 0) {
443         ERR_raise(ERR_LIB_BIO, BIO_R_INVALID_ARGUMENT);
444         return -1;
445     }
446
447     if (b->callback != NULL || b->callback_ex != NULL) {
448         ret = (int)bio_call_callback(b, BIO_CB_GETS, buf, size, 0, 0L, 1, NULL);
449         if (ret <= 0)
450             return ret;
451     }
452
453     if (!b->init) {
454         ERR_raise(ERR_LIB_BIO, BIO_R_UNINITIALIZED);
455         return -1;
456     }
457
458     ret = b->method->bgets(b, buf, size);
459
460     if (ret > 0) {
461         readbytes = ret;
462         ret = 1;
463     }
464
465     if (b->callback != NULL || b->callback_ex != NULL)
466         ret = (int)bio_call_callback(b, BIO_CB_GETS | BIO_CB_RETURN, buf, size,
467                                      0, 0L, ret, &readbytes);
468
469     if (ret > 0) {
470         /* Shouldn't happen */
471         if (readbytes > (size_t)size)
472             ret = -1;
473         else
474             ret = (int)readbytes;
475     }
476
477     return ret;
478 }
479
480 int BIO_indent(BIO *b, int indent, int max)
481 {
482     if (indent < 0)
483         indent = 0;
484     if (indent > max)
485         indent = max;
486     while (indent--)
487         if (BIO_puts(b, " ") != 1)
488             return 0;
489     return 1;
490 }
491
492 long BIO_int_ctrl(BIO *b, int cmd, long larg, int iarg)
493 {
494     int i;
495
496     i = iarg;
497     return BIO_ctrl(b, cmd, larg, (char *)&i);
498 }
499
500 void *BIO_ptr_ctrl(BIO *b, int cmd, long larg)
501 {
502     void *p = NULL;
503
504     if (BIO_ctrl(b, cmd, larg, (char *)&p) <= 0)
505         return NULL;
506     else
507         return p;
508 }
509
510 long BIO_ctrl(BIO *b, int cmd, long larg, void *parg)
511 {
512     long ret;
513
514     if (b == NULL) {
515         ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
516         return -1;
517     }
518     if (b->method == NULL || b->method->ctrl == NULL) {
519         ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_METHOD);
520         return -2;
521     }
522
523     if (b->callback != NULL || b->callback_ex != NULL) {
524         ret = bio_call_callback(b, BIO_CB_CTRL, parg, 0, cmd, larg, 1L, NULL);
525         if (ret <= 0)
526             return ret;
527     }
528
529     ret = b->method->ctrl(b, cmd, larg, parg);
530
531     if (b->callback != NULL || b->callback_ex != NULL)
532         ret = bio_call_callback(b, BIO_CB_CTRL | BIO_CB_RETURN, parg, 0, cmd,
533                                 larg, ret, NULL);
534
535     return ret;
536 }
537
538 long BIO_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp)
539 {
540     long ret;
541
542     if (b == NULL) {
543         ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
544         return -2;
545     }
546     if (b->method == NULL || b->method->callback_ctrl == NULL
547             || cmd != BIO_CTRL_SET_CALLBACK) {
548         ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_METHOD);
549         return -2;
550     }
551
552     if (b->callback != NULL || b->callback_ex != NULL) {
553         ret = bio_call_callback(b, BIO_CB_CTRL, (void *)&fp, 0, cmd, 0, 1L,
554                                 NULL);
555         if (ret <= 0)
556             return ret;
557     }
558
559     ret = b->method->callback_ctrl(b, cmd, fp);
560
561     if (b->callback != NULL || b->callback_ex != NULL)
562         ret = bio_call_callback(b, BIO_CB_CTRL | BIO_CB_RETURN, (void *)&fp, 0,
563                                 cmd, 0, ret, NULL);
564
565     return ret;
566 }
567
568 /*
569  * It is unfortunate to duplicate in functions what the BIO_(w)pending macros
570  * do; but those macros have inappropriate return type, and for interfacing
571  * from other programming languages, C macros aren't much of a help anyway.
572  */
573 size_t BIO_ctrl_pending(BIO *bio)
574 {
575     return BIO_ctrl(bio, BIO_CTRL_PENDING, 0, NULL);
576 }
577
578 size_t BIO_ctrl_wpending(BIO *bio)
579 {
580     return BIO_ctrl(bio, BIO_CTRL_WPENDING, 0, NULL);
581 }
582
583 /* put the 'bio' on the end of b's list of operators */
584 BIO *BIO_push(BIO *b, BIO *bio)
585 {
586     BIO *lb;
587
588     if (b == NULL)
589         return bio;
590     lb = b;
591     while (lb->next_bio != NULL)
592         lb = lb->next_bio;
593     lb->next_bio = bio;
594     if (bio != NULL)
595         bio->prev_bio = lb;
596     /* called to do internal processing */
597     BIO_ctrl(b, BIO_CTRL_PUSH, 0, lb);
598     return b;
599 }
600
601 /* Remove the first and return the rest */
602 BIO *BIO_pop(BIO *b)
603 {
604     BIO *ret;
605
606     if (b == NULL) {
607         ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
608         return NULL;
609     }
610     ret = b->next_bio;
611
612     BIO_ctrl(b, BIO_CTRL_POP, 0, b);
613
614     if (b->prev_bio != NULL)
615         b->prev_bio->next_bio = b->next_bio;
616     if (b->next_bio != NULL)
617         b->next_bio->prev_bio = b->prev_bio;
618
619     b->next_bio = NULL;
620     b->prev_bio = NULL;
621     return ret;
622 }
623
624 BIO *BIO_get_retry_BIO(BIO *bio, int *reason)
625 {
626     BIO *b, *last;
627
628     b = last = bio;
629     for (;;) {
630         if (!BIO_should_retry(b))
631             break;
632         last = b;
633         b = b->next_bio;
634         if (b == NULL)
635             break;
636     }
637     if (reason != NULL)
638         *reason = last->retry_reason;
639     return last;
640 }
641
642 int BIO_get_retry_reason(BIO *bio)
643 {
644     return bio->retry_reason;
645 }
646
647 void BIO_set_retry_reason(BIO *bio, int reason)
648 {
649     bio->retry_reason = reason;
650 }
651
652 BIO *BIO_find_type(BIO *bio, int type)
653 {
654     int mt, mask;
655
656     if (bio == NULL) {
657         ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
658         return NULL;
659     }
660     mask = type & 0xff;
661     do {
662         if (bio->method != NULL) {
663             mt = bio->method->type;
664
665             if (!mask) {
666                 if (mt & type)
667                     return bio;
668             } else if (mt == type) {
669                 return bio;
670             }
671         }
672         bio = bio->next_bio;
673     } while (bio != NULL);
674     return NULL;
675 }
676
677 BIO *BIO_next(BIO *b)
678 {
679     if (b == NULL) {
680         ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
681         return NULL;
682     }
683     return b->next_bio;
684 }
685
686 void BIO_set_next(BIO *b, BIO *next)
687 {
688     b->next_bio = next;
689 }
690
691 void BIO_free_all(BIO *bio)
692 {
693     BIO *b;
694     int ref;
695
696     while (bio != NULL) {
697         b = bio;
698         ref = b->references;
699         bio = bio->next_bio;
700         BIO_free(b);
701         /* Since ref count > 1, don't free anyone else. */
702         if (ref > 1)
703             break;
704     }
705 }
706
707 BIO *BIO_dup_chain(BIO *in)
708 {
709     BIO *ret = NULL, *eoc = NULL, *bio, *new_bio;
710
711     for (bio = in; bio != NULL; bio = bio->next_bio) {
712         if ((new_bio = BIO_new(bio->method)) == NULL)
713             goto err;
714         new_bio->callback = bio->callback;
715         new_bio->callback_ex = bio->callback_ex;
716         new_bio->cb_arg = bio->cb_arg;
717         new_bio->init = bio->init;
718         new_bio->shutdown = bio->shutdown;
719         new_bio->flags = bio->flags;
720
721         /* This will let SSL_s_sock() work with stdin/stdout */
722         new_bio->num = bio->num;
723
724         if (!BIO_dup_state(bio, (char *)new_bio)) {
725             BIO_free(new_bio);
726             goto err;
727         }
728
729         /* copy app data */
730         if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_BIO, &new_bio->ex_data,
731                                 &bio->ex_data)) {
732             BIO_free(new_bio);
733             goto err;
734         }
735
736         if (ret == NULL) {
737             eoc = new_bio;
738             ret = eoc;
739         } else {
740             BIO_push(eoc, new_bio);
741             eoc = new_bio;
742         }
743     }
744     return ret;
745  err:
746     BIO_free_all(ret);
747
748     return NULL;
749 }
750
751 void BIO_copy_next_retry(BIO *b)
752 {
753     BIO_set_flags(b, BIO_get_retry_flags(b->next_bio));
754     b->retry_reason = b->next_bio->retry_reason;
755 }
756
757 int BIO_set_ex_data(BIO *bio, int idx, void *data)
758 {
759     return CRYPTO_set_ex_data(&(bio->ex_data), idx, data);
760 }
761
762 void *BIO_get_ex_data(const BIO *bio, int idx)
763 {
764     return CRYPTO_get_ex_data(&(bio->ex_data), idx);
765 }
766
767 uint64_t BIO_number_read(BIO *bio)
768 {
769     if (bio)
770         return bio->num_read;
771     return 0;
772 }
773
774 uint64_t BIO_number_written(BIO *bio)
775 {
776     if (bio)
777         return bio->num_write;
778     return 0;
779 }
780
781 void bio_free_ex_data(BIO *bio)
782 {
783     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_BIO, bio, &bio->ex_data);
784 }
785
786 void bio_cleanup(void)
787 {
788 #ifndef OPENSSL_NO_SOCK
789     bio_sock_cleanup_int();
790     CRYPTO_THREAD_lock_free(bio_lookup_lock);
791     bio_lookup_lock = NULL;
792 #endif
793     CRYPTO_THREAD_lock_free(bio_type_lock);
794     bio_type_lock = NULL;
795 }
796
797 /* Internal variant of the below BIO_wait() not calling BIOerr() */
798 static int bio_wait(BIO *bio, time_t max_time, unsigned int nap_milliseconds)
799 {
800 #ifndef OPENSSL_NO_SOCK
801     int fd;
802 #endif
803     long sec_diff;
804
805     if (max_time == 0) /* no timeout */
806         return 1;
807
808 #ifndef OPENSSL_NO_SOCK
809     if (BIO_get_fd(bio, &fd) > 0 && fd < FD_SETSIZE)
810         return BIO_socket_wait(fd, BIO_should_read(bio), max_time);
811 #endif
812     /* fall back to polling since no sockets are available */
813
814     sec_diff = (long)(max_time - time(NULL)); /* might overflow */
815     if (sec_diff < 0)
816         return 0; /* clearly timeout */
817
818     /* now take a nap at most the given number of milliseconds */
819     if (sec_diff == 0) { /* we are below the 1 seconds resolution of max_time */
820         if (nap_milliseconds > 1000)
821             nap_milliseconds = 1000;
822     } else { /* for sec_diff > 0, take min(sec_diff * 1000, nap_milliseconds) */
823         if ((unsigned long)sec_diff * 1000 < nap_milliseconds)
824             nap_milliseconds = (unsigned int)sec_diff * 1000;
825     }
826     ossl_sleep(nap_milliseconds);
827     return 1;
828 }
829
830 /*-
831  * Wait on (typically socket-based) BIO at most until max_time.
832  * Succeed immediately if max_time == 0.
833  * If sockets are not available support polling: succeed after waiting at most
834  * the number of nap_milliseconds in order to avoid a tight busy loop.
835  * Call BIOerr(...) on timeout or error.
836  * Returns -1 on error, 0 on timeout, and 1 on success.
837  */
838 int BIO_wait(BIO *bio, time_t max_time, unsigned int nap_milliseconds)
839 {
840     int rv = bio_wait(bio, max_time, nap_milliseconds);
841
842     if (rv <= 0)
843         ERR_raise(ERR_LIB_BIO,
844                   rv == 0 ? BIO_R_TRANSFER_TIMEOUT : BIO_R_TRANSFER_ERROR);
845     return rv;
846 }
847
848 /*
849  * Connect via given BIO using BIO_do_connect() until success/timeout/error.
850  * Parameter timeout == 0 means no timeout, < 0 means exactly one try.
851  * For non-blocking and potentially even non-socket BIOs perform polling with
852  * the given density: between polls sleep nap_milliseconds using BIO_wait()
853  * in order to avoid a tight busy loop.
854  * Returns -1 on error, 0 on timeout, and 1 on success.
855  */
856 int BIO_do_connect_retry(BIO *bio, int timeout, int nap_milliseconds)
857 {
858     int blocking = timeout <= 0;
859     time_t max_time = timeout > 0 ? time(NULL) + timeout : 0;
860     int rv;
861
862     if (bio == NULL) {
863         ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
864         return -1;
865     }
866
867     if (nap_milliseconds < 0)
868         nap_milliseconds = 100;
869     BIO_set_nbio(bio, !blocking);
870
871  retry:
872     ERR_set_mark();
873     rv = BIO_do_connect(bio);
874
875     if (rv <= 0) { /* could be timeout or retryable error or fatal error */
876         int err = ERR_peek_last_error();
877         int reason = ERR_GET_REASON(err);
878         int do_retry = BIO_should_retry(bio); /* may be 1 only if !blocking */
879
880         if (ERR_GET_LIB(err) == ERR_LIB_BIO) {
881             switch (reason) {
882             case ERR_R_SYS_LIB:
883                 /*
884                  * likely retryable system error occurred, which may be
885                  * EAGAIN (resource temporarily unavailable) some 40 secs after
886                  * calling getaddrinfo(): Temporary failure in name resolution
887                  * or a premature ETIMEDOUT, some 30 seconds after connect()
888                  */
889             case BIO_R_CONNECT_ERROR:
890             case BIO_R_NBIO_CONNECT_ERROR:
891                 /* some likely retryable connection error occurred */
892                 (void)BIO_reset(bio); /* often needed to avoid retry failure */
893                 do_retry = 1;
894                 break;
895             default:
896                 break;
897             }
898         }
899         if (timeout >= 0 && do_retry) {
900             ERR_pop_to_mark();
901             /* will not actually wait if timeout == 0 (i.e., blocking BIO): */
902             rv = bio_wait(bio, max_time, nap_milliseconds);
903             if (rv > 0)
904                 goto retry;
905             ERR_raise(ERR_LIB_BIO,
906                       rv == 0 ? BIO_R_CONNECT_TIMEOUT : BIO_R_CONNECT_ERROR);
907         } else {
908             ERR_clear_last_mark();
909             rv = -1;
910             if (err == 0) /* missing error queue entry */
911                 /* workaround: general error */
912                 ERR_raise(ERR_LIB_BIO, BIO_R_CONNECT_ERROR);
913         }
914     } else {
915         ERR_clear_last_mark();
916     }
917
918     return rv;
919 }