Update copyright year
[openssl.git] / crypto / bio / bss_conn.c
1 /*
2  * Copyright 1995-2022 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
13 #include "bio_local.h"
14 #include "internal/bio_tfo.h"
15 #include "internal/ktls.h"
16
17 #ifndef OPENSSL_NO_SOCK
18
19 typedef struct bio_connect_st {
20     int state;
21     int connect_family;
22     char *param_hostname;
23     char *param_service;
24     int connect_mode;
25 # ifndef OPENSSL_NO_KTLS
26     unsigned char record_type;
27 # endif
28     int tfo_first;
29
30     BIO_ADDRINFO *addr_first;
31     const BIO_ADDRINFO *addr_iter;
32     /*
33      * int socket; this will be kept in bio->num so that it is compatible
34      * with the bss_sock bio
35      */
36     /*
37      * called when the connection is initially made callback(BIO,state,ret);
38      * The callback should return 'ret'.  state is for compatibility with the
39      * ssl info_callback
40      */
41     BIO_info_cb *info_callback;
42 } BIO_CONNECT;
43
44 static int conn_write(BIO *h, const char *buf, int num);
45 static int conn_read(BIO *h, char *buf, int size);
46 static int conn_puts(BIO *h, const char *str);
47 static int conn_gets(BIO *h, char *buf, int size);
48 static long conn_ctrl(BIO *h, int cmd, long arg1, void *arg2);
49 static int conn_new(BIO *h);
50 static int conn_free(BIO *data);
51 static long conn_callback_ctrl(BIO *h, int cmd, BIO_info_cb *);
52
53 static int conn_state(BIO *b, BIO_CONNECT *c);
54 static void conn_close_socket(BIO *data);
55 BIO_CONNECT *BIO_CONNECT_new(void);
56 void BIO_CONNECT_free(BIO_CONNECT *a);
57
58 #define BIO_CONN_S_BEFORE                1
59 #define BIO_CONN_S_GET_ADDR              2
60 #define BIO_CONN_S_CREATE_SOCKET         3
61 #define BIO_CONN_S_CONNECT               4
62 #define BIO_CONN_S_OK                    5
63 #define BIO_CONN_S_BLOCKED_CONNECT       6
64 #define BIO_CONN_S_CONNECT_ERROR         7
65
66 static const BIO_METHOD methods_connectp = {
67     BIO_TYPE_CONNECT,
68     "socket connect",
69     bwrite_conv,
70     conn_write,
71     bread_conv,
72     conn_read,
73     conn_puts,
74     conn_gets,
75     conn_ctrl,
76     conn_new,
77     conn_free,
78     conn_callback_ctrl,
79 };
80
81 static int conn_state(BIO *b, BIO_CONNECT *c)
82 {
83     int ret = -1, i;
84     BIO_info_cb *cb = NULL;
85
86     if (c->info_callback != NULL)
87         cb = c->info_callback;
88
89     for (;;) {
90         switch (c->state) {
91         case BIO_CONN_S_BEFORE:
92             if (c->param_hostname == NULL && c->param_service == NULL) {
93                 ERR_raise_data(ERR_LIB_BIO,
94                                BIO_R_NO_HOSTNAME_OR_SERVICE_SPECIFIED,
95                                "hostname=%s service=%s",
96                                c->param_hostname, c->param_service);
97                 goto exit_loop;
98             }
99             c->state = BIO_CONN_S_GET_ADDR;
100             break;
101
102         case BIO_CONN_S_GET_ADDR:
103             {
104                 int family = AF_UNSPEC;
105                 switch (c->connect_family) {
106                 case BIO_FAMILY_IPV6:
107                     if (1) { /* This is a trick we use to avoid bit rot.
108                               * at least the "else" part will always be
109                               * compiled.
110                               */
111 #ifdef AF_INET6
112                         family = AF_INET6;
113                     } else {
114 #endif
115                         ERR_raise(ERR_LIB_BIO, BIO_R_UNAVAILABLE_IP_FAMILY);
116                         goto exit_loop;
117                     }
118                     break;
119                 case BIO_FAMILY_IPV4:
120                     family = AF_INET;
121                     break;
122                 case BIO_FAMILY_IPANY:
123                     family = AF_UNSPEC;
124                     break;
125                 default:
126                     ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_IP_FAMILY);
127                     goto exit_loop;
128                 }
129                 if (BIO_lookup(c->param_hostname, c->param_service,
130                                BIO_LOOKUP_CLIENT,
131                                family, SOCK_STREAM, &c->addr_first) == 0)
132                     goto exit_loop;
133             }
134             if (c->addr_first == NULL) {
135                 ERR_raise(ERR_LIB_BIO, BIO_R_LOOKUP_RETURNED_NOTHING);
136                 goto exit_loop;
137             }
138             c->addr_iter = c->addr_first;
139             c->state = BIO_CONN_S_CREATE_SOCKET;
140             break;
141
142         case BIO_CONN_S_CREATE_SOCKET:
143             ret = BIO_socket(BIO_ADDRINFO_family(c->addr_iter),
144                              BIO_ADDRINFO_socktype(c->addr_iter),
145                              BIO_ADDRINFO_protocol(c->addr_iter), 0);
146             if (ret == (int)INVALID_SOCKET) {
147                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
148                                "calling socket(%s, %s)",
149                                c->param_hostname, c->param_service);
150                 ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_CREATE_SOCKET);
151                 goto exit_loop;
152             }
153             b->num = ret;
154             c->state = BIO_CONN_S_CONNECT;
155             break;
156
157         case BIO_CONN_S_CONNECT:
158             BIO_clear_retry_flags(b);
159             ERR_set_mark();
160             ret = BIO_connect(b->num, BIO_ADDRINFO_address(c->addr_iter),
161                               BIO_SOCK_KEEPALIVE | c->connect_mode);
162             b->retry_reason = 0;
163             if (ret == 0) {
164                 if (BIO_sock_should_retry(ret)) {
165                     BIO_set_retry_special(b);
166                     c->state = BIO_CONN_S_BLOCKED_CONNECT;
167                     b->retry_reason = BIO_RR_CONNECT;
168                     ERR_pop_to_mark();
169                 } else if ((c->addr_iter = BIO_ADDRINFO_next(c->addr_iter))
170                            != NULL) {
171                     /*
172                      * if there are more addresses to try, do that first
173                      */
174                     BIO_closesocket(b->num);
175                     c->state = BIO_CONN_S_CREATE_SOCKET;
176                     ERR_pop_to_mark();
177                     break;
178                 } else {
179                     ERR_clear_last_mark();
180                     ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
181                                    "calling connect(%s, %s)",
182                                     c->param_hostname, c->param_service);
183                     c->state = BIO_CONN_S_CONNECT_ERROR;
184                     break;
185                 }
186                 goto exit_loop;
187             } else {
188                 ERR_clear_last_mark();
189                 c->state = BIO_CONN_S_OK;
190             }
191             break;
192
193         case BIO_CONN_S_BLOCKED_CONNECT:
194             i = BIO_sock_error(b->num);
195             if (i != 0) {
196                 BIO_clear_retry_flags(b);
197                 if ((c->addr_iter = BIO_ADDRINFO_next(c->addr_iter)) != NULL) {
198                     /*
199                      * if there are more addresses to try, do that first
200                      */
201                     BIO_closesocket(b->num);
202                     c->state = BIO_CONN_S_CREATE_SOCKET;
203                     break;
204                 }
205                 ERR_raise_data(ERR_LIB_SYS, i,
206                                "calling connect(%s, %s)",
207                                 c->param_hostname, c->param_service);
208                 ERR_raise(ERR_LIB_BIO, BIO_R_NBIO_CONNECT_ERROR);
209                 ret = 0;
210                 goto exit_loop;
211             } else
212                 c->state = BIO_CONN_S_OK;
213             break;
214
215         case BIO_CONN_S_CONNECT_ERROR:
216             ERR_raise(ERR_LIB_BIO, BIO_R_CONNECT_ERROR);
217             ret = 0;
218             goto exit_loop;
219
220         case BIO_CONN_S_OK:
221             ret = 1;
222             goto exit_loop;
223         default:
224             /* abort(); */
225             goto exit_loop;
226         }
227
228         if (cb != NULL) {
229             if ((ret = cb((BIO *)b, c->state, ret)) == 0)
230                 goto end;
231         }
232     }
233
234     /* Loop does not exit */
235  exit_loop:
236     if (cb != NULL)
237         ret = cb((BIO *)b, c->state, ret);
238  end:
239     return ret;
240 }
241
242 BIO_CONNECT *BIO_CONNECT_new(void)
243 {
244     BIO_CONNECT *ret;
245
246     if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) {
247         ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
248         return NULL;
249     }
250     ret->state = BIO_CONN_S_BEFORE;
251     ret->connect_family = BIO_FAMILY_IPANY;
252     return ret;
253 }
254
255 void BIO_CONNECT_free(BIO_CONNECT *a)
256 {
257     if (a == NULL)
258         return;
259     OPENSSL_free(a->param_hostname);
260     OPENSSL_free(a->param_service);
261     BIO_ADDRINFO_free(a->addr_first);
262     OPENSSL_free(a);
263 }
264
265 const BIO_METHOD *BIO_s_connect(void)
266 {
267     return &methods_connectp;
268 }
269
270 static int conn_new(BIO *bi)
271 {
272     bi->init = 0;
273     bi->num = (int)INVALID_SOCKET;
274     bi->flags = 0;
275     if ((bi->ptr = (char *)BIO_CONNECT_new()) == NULL)
276         return 0;
277     else
278         return 1;
279 }
280
281 static void conn_close_socket(BIO *bio)
282 {
283     BIO_CONNECT *c;
284
285     c = (BIO_CONNECT *)bio->ptr;
286     if (bio->num != (int)INVALID_SOCKET) {
287         /* Only do a shutdown if things were established */
288         if (c->state == BIO_CONN_S_OK)
289             shutdown(bio->num, 2);
290         BIO_closesocket(bio->num);
291         bio->num = (int)INVALID_SOCKET;
292     }
293 }
294
295 static int conn_free(BIO *a)
296 {
297     BIO_CONNECT *data;
298
299     if (a == NULL)
300         return 0;
301     data = (BIO_CONNECT *)a->ptr;
302
303     if (a->shutdown) {
304         conn_close_socket(a);
305         BIO_CONNECT_free(data);
306         a->ptr = NULL;
307         a->flags = 0;
308         a->init = 0;
309     }
310     return 1;
311 }
312
313 static int conn_read(BIO *b, char *out, int outl)
314 {
315     int ret = 0;
316     BIO_CONNECT *data;
317
318     data = (BIO_CONNECT *)b->ptr;
319     if (data->state != BIO_CONN_S_OK) {
320         ret = conn_state(b, data);
321         if (ret <= 0)
322             return ret;
323     }
324
325     if (out != NULL) {
326         clear_socket_error();
327 # ifndef OPENSSL_NO_KTLS
328         if (BIO_get_ktls_recv(b))
329             ret = ktls_read_record(b->num, out, outl);
330         else
331 # endif
332             ret = readsocket(b->num, out, outl);
333         BIO_clear_retry_flags(b);
334         if (ret <= 0) {
335             if (BIO_sock_should_retry(ret))
336                 BIO_set_retry_read(b);
337             else if (ret == 0)
338                 b->flags |= BIO_FLAGS_IN_EOF;
339         }
340     }
341     return ret;
342 }
343
344 static int conn_write(BIO *b, const char *in, int inl)
345 {
346     int ret;
347     BIO_CONNECT *data;
348
349     data = (BIO_CONNECT *)b->ptr;
350     if (data->state != BIO_CONN_S_OK) {
351         ret = conn_state(b, data);
352         if (ret <= 0)
353             return ret;
354     }
355
356     clear_socket_error();
357 # ifndef OPENSSL_NO_KTLS
358     if (BIO_should_ktls_ctrl_msg_flag(b)) {
359         ret = ktls_send_ctrl_message(b->num, data->record_type, in, inl);
360         if (ret >= 0) {
361             ret = inl;
362             BIO_clear_ktls_ctrl_msg_flag(b);
363         }
364     } else
365 # endif
366 # if defined(OSSL_TFO_SENDTO)
367     if (data->tfo_first) {
368         int peerlen = BIO_ADDRINFO_sockaddr_size(data->addr_iter);
369
370         ret = sendto(b->num, in, inl, OSSL_TFO_SENDTO,
371                      BIO_ADDRINFO_sockaddr(data->addr_iter), peerlen);
372         data->tfo_first = 0;
373     } else
374 # endif
375         ret = writesocket(b->num, in, inl);
376     BIO_clear_retry_flags(b);
377     if (ret <= 0) {
378         if (BIO_sock_should_retry(ret))
379             BIO_set_retry_write(b);
380     }
381     return ret;
382 }
383
384 static long conn_ctrl(BIO *b, int cmd, long num, void *ptr)
385 {
386     BIO *dbio;
387     int *ip;
388     const char **pptr = NULL;
389     long ret = 1;
390     BIO_CONNECT *data;
391 # ifndef OPENSSL_NO_KTLS
392     ktls_crypto_info_t *crypto_info;
393 # endif
394
395     data = (BIO_CONNECT *)b->ptr;
396
397     switch (cmd) {
398     case BIO_CTRL_RESET:
399         ret = 0;
400         data->state = BIO_CONN_S_BEFORE;
401         conn_close_socket(b);
402         BIO_ADDRINFO_free(data->addr_first);
403         data->addr_first = NULL;
404         b->flags = 0;
405         break;
406     case BIO_C_DO_STATE_MACHINE:
407         /* use this one to start the connection */
408         if (data->state != BIO_CONN_S_OK)
409             ret = (long)conn_state(b, data);
410         else
411             ret = 1;
412         break;
413     case BIO_C_GET_CONNECT:
414         if (ptr != NULL) {
415             pptr = (const char **)ptr;
416             if (num == 0) {
417                 *pptr = data->param_hostname;
418             } else if (num == 1) {
419                 *pptr = data->param_service;
420             } else if (num == 2) {
421                 *pptr = (const char *)BIO_ADDRINFO_address(data->addr_iter);
422             } else if (num == 3) {
423                 switch (BIO_ADDRINFO_family(data->addr_iter)) {
424 # ifdef AF_INET6
425                 case AF_INET6:
426                     ret = BIO_FAMILY_IPV6;
427                     break;
428 # endif
429                 case AF_INET:
430                     ret = BIO_FAMILY_IPV4;
431                     break;
432                 case 0:
433                     ret = data->connect_family;
434                     break;
435                 default:
436                     ret = -1;
437                     break;
438                 }
439             } else if (num == 4) {
440                 ret = data->connect_mode;
441             } else {
442                 ret = 0;
443             }
444         } else {
445             ret = 0;
446         }
447         break;
448     case BIO_C_SET_CONNECT:
449         if (ptr != NULL) {
450             b->init = 1;
451             if (num == 0) { /* BIO_set_conn_hostname */
452                 char *hold_service = data->param_service;
453                 /* We affect the hostname regardless.  However, the input
454                  * string might contain a host:service spec, so we must
455                  * parse it, which might or might not affect the service
456                  */
457
458                 OPENSSL_free(data->param_hostname);
459                 data->param_hostname = NULL;
460                 ret = BIO_parse_hostserv(ptr,
461                                          &data->param_hostname,
462                                          &data->param_service,
463                                          BIO_PARSE_PRIO_HOST);
464                 if (hold_service != data->param_service)
465                     OPENSSL_free(hold_service);
466             } else if (num == 1) { /* BIO_set_conn_port */
467                 OPENSSL_free(data->param_service);
468                 if ((data->param_service = OPENSSL_strdup(ptr)) == NULL)
469                     ret = 0;
470             } else if (num == 2) { /* BIO_set_conn_address */
471                 const BIO_ADDR *addr = (const BIO_ADDR *)ptr;
472                 char *host = BIO_ADDR_hostname_string(addr, 1);
473                 char *service = BIO_ADDR_service_string(addr, 1);
474
475                 ret = host != NULL && service != NULL;
476                 if (ret) {
477                     OPENSSL_free(data->param_hostname);
478                     data->param_hostname = host;
479                     OPENSSL_free(data->param_service);
480                     data->param_service = service;
481                     BIO_ADDRINFO_free(data->addr_first);
482                     data->addr_first = NULL;
483                     data->addr_iter = NULL;
484                 } else {
485                     OPENSSL_free(host);
486                     OPENSSL_free(service);
487                 }
488             } else if (num == 3) { /* BIO_set_conn_ip_family */
489                 data->connect_family = *(int *)ptr;
490             } else {
491                 ret = 0;
492             }
493         }
494         break;
495     case BIO_C_SET_NBIO:
496         if (num != 0)
497             data->connect_mode |= BIO_SOCK_NONBLOCK;
498         else
499             data->connect_mode &= ~BIO_SOCK_NONBLOCK;
500         break;
501 #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO)
502     case BIO_C_SET_TFO:
503         if (num != 0) {
504             data->connect_mode |= BIO_SOCK_TFO;
505             data->tfo_first = 1;
506         } else {
507             data->connect_mode &= ~BIO_SOCK_TFO;
508             data->tfo_first = 0;
509         }
510         break;
511 #endif
512     case BIO_C_SET_CONNECT_MODE:
513         data->connect_mode = (int)num;
514         if (num & BIO_SOCK_TFO)
515             data->tfo_first = 1;
516         else
517             data->tfo_first = 0;
518         break;
519     case BIO_C_GET_FD:
520         if (b->init) {
521             ip = (int *)ptr;
522             if (ip != NULL)
523                 *ip = b->num;
524             ret = b->num;
525         } else
526             ret = -1;
527         break;
528     case BIO_CTRL_GET_CLOSE:
529         ret = b->shutdown;
530         break;
531     case BIO_CTRL_SET_CLOSE:
532         b->shutdown = (int)num;
533         break;
534     case BIO_CTRL_PENDING:
535     case BIO_CTRL_WPENDING:
536         ret = 0;
537         break;
538     case BIO_CTRL_FLUSH:
539         break;
540     case BIO_CTRL_DUP:
541         {
542             dbio = (BIO *)ptr;
543             if (data->param_hostname)
544                 BIO_set_conn_hostname(dbio, data->param_hostname);
545             if (data->param_service)
546                 BIO_set_conn_port(dbio, data->param_service);
547             BIO_set_conn_ip_family(dbio, data->connect_family);
548             BIO_set_conn_mode(dbio, data->connect_mode);
549             /*
550              * FIXME: the cast of the function seems unlikely to be a good
551              * idea
552              */
553             (void)BIO_set_info_callback(dbio, data->info_callback);
554         }
555         break;
556     case BIO_CTRL_SET_CALLBACK:
557         ret = 0; /* use callback ctrl */
558         break;
559     case BIO_CTRL_GET_CALLBACK:
560         {
561             BIO_info_cb **fptr;
562
563             fptr = (BIO_info_cb **)ptr;
564             *fptr = data->info_callback;
565         }
566         break;
567     case BIO_CTRL_EOF:
568         ret = (b->flags & BIO_FLAGS_IN_EOF) != 0;
569         break;
570 # ifndef OPENSSL_NO_KTLS
571     case BIO_CTRL_SET_KTLS:
572         crypto_info = (ktls_crypto_info_t *)ptr;
573         ret = ktls_start(b->num, crypto_info, num);
574         if (ret)
575             BIO_set_ktls_flag(b, num);
576         break;
577     case BIO_CTRL_GET_KTLS_SEND:
578         return BIO_should_ktls_flag(b, 1) != 0;
579     case BIO_CTRL_GET_KTLS_RECV:
580         return BIO_should_ktls_flag(b, 0) != 0;
581     case BIO_CTRL_SET_KTLS_TX_SEND_CTRL_MSG:
582         BIO_set_ktls_ctrl_msg_flag(b);
583         data->record_type = num;
584         ret = 0;
585         break;
586     case BIO_CTRL_CLEAR_KTLS_TX_CTRL_MSG:
587         BIO_clear_ktls_ctrl_msg_flag(b);
588         ret = 0;
589         break;
590 # endif
591     default:
592         ret = 0;
593         break;
594     }
595     return ret;
596 }
597
598 static long conn_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp)
599 {
600     long ret = 1;
601     BIO_CONNECT *data;
602
603     data = (BIO_CONNECT *)b->ptr;
604
605     switch (cmd) {
606     case BIO_CTRL_SET_CALLBACK:
607         {
608             data->info_callback = fp;
609         }
610         break;
611     default:
612         ret = 0;
613         break;
614     }
615     return ret;
616 }
617
618 static int conn_puts(BIO *bp, const char *str)
619 {
620     int n, ret;
621
622     n = strlen(str);
623     ret = conn_write(bp, str, n);
624     return ret;
625 }
626
627 int conn_gets(BIO *bio, char *buf, int size)
628 {
629     BIO_CONNECT *data;
630     char *ptr = buf;
631     int ret = 0;
632
633     if (buf == NULL) {
634         ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
635         return -1;
636     }
637     if (size <= 0) {
638         ERR_raise(ERR_LIB_BIO, BIO_R_INVALID_ARGUMENT);
639         return -1;
640     }
641     *buf = '\0';
642
643     if (bio == NULL || bio->ptr == NULL) {
644         ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
645         return -1;
646     }
647     data = (BIO_CONNECT *)bio->ptr;
648     if (data->state != BIO_CONN_S_OK) {
649         ret = conn_state(bio, data);
650         if (ret <= 0)
651             return ret;
652     }
653
654     clear_socket_error();
655     while (size-- > 1) {
656 # ifndef OPENSSL_NO_KTLS
657         if (BIO_get_ktls_recv(bio))
658             ret = ktls_read_record(bio->num, ptr, 1);
659         else
660 # endif
661             ret = readsocket(bio->num, ptr, 1);
662         BIO_clear_retry_flags(bio);
663         if (ret <= 0) {
664             if (BIO_sock_should_retry(ret))
665                 BIO_set_retry_read(bio);
666             else if (ret == 0)
667                 bio->flags |= BIO_FLAGS_IN_EOF;
668             break;
669         }
670         if (*ptr++ == '\n')
671             break;
672     }
673     *ptr = '\0';
674     return ret > 0 || (bio->flags & BIO_FLAGS_IN_EOF) != 0 ? ptr - buf : ret;
675 }
676
677 BIO *BIO_new_connect(const char *str)
678 {
679     BIO *ret;
680
681     ret = BIO_new(BIO_s_connect());
682     if (ret == NULL)
683         return NULL;
684     if (BIO_set_conn_hostname(ret, str))
685         return ret;
686     BIO_free(ret);
687     return NULL;
688 }
689
690 #endif