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