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