Fix KTLS with BIO_new_connect
[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 #if OPENSSL_USE_IPV6
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             /* wait for socket being writable, before querying BIO_sock_error */
195             if (BIO_socket_wait(b->num, 0, time(NULL)) == 0)
196                 break;
197             i = BIO_sock_error(b->num);
198             if (i != 0) {
199                 BIO_clear_retry_flags(b);
200                 if ((c->addr_iter = BIO_ADDRINFO_next(c->addr_iter)) != NULL) {
201                     /*
202                      * if there are more addresses to try, do that first
203                      */
204                     BIO_closesocket(b->num);
205                     c->state = BIO_CONN_S_CREATE_SOCKET;
206                     break;
207                 }
208                 ERR_raise_data(ERR_LIB_SYS, i,
209                                "calling connect(%s, %s)",
210                                 c->param_hostname, c->param_service);
211                 ERR_raise(ERR_LIB_BIO, BIO_R_NBIO_CONNECT_ERROR);
212                 ret = 0;
213                 goto exit_loop;
214             } else {
215                 c->state = BIO_CONN_S_OK;
216 # ifndef OPENSSL_NO_KTLS
217                 /*
218                  * The new socket is created successfully regardless of ktls_enable.
219                  * ktls_enable doesn't change any functionality of the socket, except
220                  * changing the setsockopt to enable the processing of ktls_start.
221                  * Thus, it is not a problem to call it for non-TLS sockets.
222                  */
223                 ktls_enable(b->num);
224 # endif
225             }
226             break;
227
228         case BIO_CONN_S_CONNECT_ERROR:
229             ERR_raise(ERR_LIB_BIO, BIO_R_CONNECT_ERROR);
230             ret = 0;
231             goto exit_loop;
232
233         case BIO_CONN_S_OK:
234             ret = 1;
235             goto exit_loop;
236         default:
237             /* abort(); */
238             goto exit_loop;
239         }
240
241         if (cb != NULL) {
242             if ((ret = cb((BIO *)b, c->state, ret)) == 0)
243                 goto end;
244         }
245     }
246
247     /* Loop does not exit */
248  exit_loop:
249     if (cb != NULL)
250         ret = cb((BIO *)b, c->state, ret);
251  end:
252     return ret;
253 }
254
255 BIO_CONNECT *BIO_CONNECT_new(void)
256 {
257     BIO_CONNECT *ret;
258
259     if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) {
260         ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
261         return NULL;
262     }
263     ret->state = BIO_CONN_S_BEFORE;
264     ret->connect_family = BIO_FAMILY_IPANY;
265     return ret;
266 }
267
268 void BIO_CONNECT_free(BIO_CONNECT *a)
269 {
270     if (a == NULL)
271         return;
272     OPENSSL_free(a->param_hostname);
273     OPENSSL_free(a->param_service);
274     BIO_ADDRINFO_free(a->addr_first);
275     OPENSSL_free(a);
276 }
277
278 const BIO_METHOD *BIO_s_connect(void)
279 {
280     return &methods_connectp;
281 }
282
283 static int conn_new(BIO *bi)
284 {
285     bi->init = 0;
286     bi->num = (int)INVALID_SOCKET;
287     bi->flags = 0;
288     if ((bi->ptr = (char *)BIO_CONNECT_new()) == NULL)
289         return 0;
290     else
291         return 1;
292 }
293
294 static void conn_close_socket(BIO *bio)
295 {
296     BIO_CONNECT *c;
297
298     c = (BIO_CONNECT *)bio->ptr;
299     if (bio->num != (int)INVALID_SOCKET) {
300         /* Only do a shutdown if things were established */
301         if (c->state == BIO_CONN_S_OK)
302             shutdown(bio->num, 2);
303         BIO_closesocket(bio->num);
304         bio->num = (int)INVALID_SOCKET;
305     }
306 }
307
308 static int conn_free(BIO *a)
309 {
310     BIO_CONNECT *data;
311
312     if (a == NULL)
313         return 0;
314     data = (BIO_CONNECT *)a->ptr;
315
316     if (a->shutdown) {
317         conn_close_socket(a);
318         BIO_CONNECT_free(data);
319         a->ptr = NULL;
320         a->flags = 0;
321         a->init = 0;
322     }
323     return 1;
324 }
325
326 static int conn_read(BIO *b, char *out, int outl)
327 {
328     int ret = 0;
329     BIO_CONNECT *data;
330
331     data = (BIO_CONNECT *)b->ptr;
332     if (data->state != BIO_CONN_S_OK) {
333         ret = conn_state(b, data);
334         if (ret <= 0)
335             return ret;
336     }
337
338     if (out != NULL) {
339         clear_socket_error();
340 # ifndef OPENSSL_NO_KTLS
341         if (BIO_get_ktls_recv(b))
342             ret = ktls_read_record(b->num, out, outl);
343         else
344 # endif
345             ret = readsocket(b->num, out, outl);
346         BIO_clear_retry_flags(b);
347         if (ret <= 0) {
348             if (BIO_sock_should_retry(ret))
349                 BIO_set_retry_read(b);
350             else if (ret == 0)
351                 b->flags |= BIO_FLAGS_IN_EOF;
352         }
353     }
354     return ret;
355 }
356
357 static int conn_write(BIO *b, const char *in, int inl)
358 {
359     int ret;
360     BIO_CONNECT *data;
361
362     data = (BIO_CONNECT *)b->ptr;
363     if (data->state != BIO_CONN_S_OK) {
364         ret = conn_state(b, data);
365         if (ret <= 0)
366             return ret;
367     }
368
369     clear_socket_error();
370 # ifndef OPENSSL_NO_KTLS
371     if (BIO_should_ktls_ctrl_msg_flag(b)) {
372         ret = ktls_send_ctrl_message(b->num, data->record_type, in, inl);
373         if (ret >= 0) {
374             ret = inl;
375             BIO_clear_ktls_ctrl_msg_flag(b);
376         }
377     } else
378 # endif
379 # if defined(OSSL_TFO_SENDTO)
380     if (data->tfo_first) {
381         int peerlen = BIO_ADDRINFO_sockaddr_size(data->addr_iter);
382
383         ret = sendto(b->num, in, inl, OSSL_TFO_SENDTO,
384                      BIO_ADDRINFO_sockaddr(data->addr_iter), peerlen);
385         data->tfo_first = 0;
386     } else
387 # endif
388         ret = writesocket(b->num, in, inl);
389     BIO_clear_retry_flags(b);
390     if (ret <= 0) {
391         if (BIO_sock_should_retry(ret))
392             BIO_set_retry_write(b);
393     }
394     return ret;
395 }
396
397 static long conn_ctrl(BIO *b, int cmd, long num, void *ptr)
398 {
399     BIO *dbio;
400     int *ip;
401     const char **pptr = NULL;
402     long ret = 1;
403     BIO_CONNECT *data;
404 # ifndef OPENSSL_NO_KTLS
405     ktls_crypto_info_t *crypto_info;
406 # endif
407
408     data = (BIO_CONNECT *)b->ptr;
409
410     switch (cmd) {
411     case BIO_CTRL_RESET:
412         ret = 0;
413         data->state = BIO_CONN_S_BEFORE;
414         conn_close_socket(b);
415         BIO_ADDRINFO_free(data->addr_first);
416         data->addr_first = NULL;
417         b->flags = 0;
418         break;
419     case BIO_C_DO_STATE_MACHINE:
420         /* use this one to start the connection */
421         if (data->state != BIO_CONN_S_OK)
422             ret = (long)conn_state(b, data);
423         else
424             ret = 1;
425         break;
426     case BIO_C_GET_CONNECT:
427         if (ptr != NULL) {
428             pptr = (const char **)ptr;
429             if (num == 0) {
430                 *pptr = data->param_hostname;
431             } else if (num == 1) {
432                 *pptr = data->param_service;
433             } else if (num == 2) {
434                 *pptr = (const char *)BIO_ADDRINFO_address(data->addr_iter);
435             } else if (num == 3) {
436                 switch (BIO_ADDRINFO_family(data->addr_iter)) {
437 # if OPENSSL_USE_IPV6
438                 case AF_INET6:
439                     ret = BIO_FAMILY_IPV6;
440                     break;
441 # endif
442                 case AF_INET:
443                     ret = BIO_FAMILY_IPV4;
444                     break;
445                 case 0:
446                     ret = data->connect_family;
447                     break;
448                 default:
449                     ret = -1;
450                     break;
451                 }
452             } else if (num == 4) {
453                 ret = data->connect_mode;
454             } else {
455                 ret = 0;
456             }
457         } else {
458             ret = 0;
459         }
460         break;
461     case BIO_C_SET_CONNECT:
462         if (ptr != NULL) {
463             b->init = 1;
464             if (num == 0) { /* BIO_set_conn_hostname */
465                 char *hold_service = data->param_service;
466                 /* We affect the hostname regardless.  However, the input
467                  * string might contain a host:service spec, so we must
468                  * parse it, which might or might not affect the service
469                  */
470
471                 OPENSSL_free(data->param_hostname);
472                 data->param_hostname = NULL;
473                 ret = BIO_parse_hostserv(ptr,
474                                          &data->param_hostname,
475                                          &data->param_service,
476                                          BIO_PARSE_PRIO_HOST);
477                 if (hold_service != data->param_service)
478                     OPENSSL_free(hold_service);
479             } else if (num == 1) { /* BIO_set_conn_port */
480                 OPENSSL_free(data->param_service);
481                 if ((data->param_service = OPENSSL_strdup(ptr)) == NULL)
482                     ret = 0;
483             } else if (num == 2) { /* BIO_set_conn_address */
484                 const BIO_ADDR *addr = (const BIO_ADDR *)ptr;
485                 char *host = BIO_ADDR_hostname_string(addr, 1);
486                 char *service = BIO_ADDR_service_string(addr, 1);
487
488                 ret = host != NULL && service != NULL;
489                 if (ret) {
490                     OPENSSL_free(data->param_hostname);
491                     data->param_hostname = host;
492                     OPENSSL_free(data->param_service);
493                     data->param_service = service;
494                     BIO_ADDRINFO_free(data->addr_first);
495                     data->addr_first = NULL;
496                     data->addr_iter = NULL;
497                 } else {
498                     OPENSSL_free(host);
499                     OPENSSL_free(service);
500                 }
501             } else if (num == 3) { /* BIO_set_conn_ip_family */
502                 data->connect_family = *(int *)ptr;
503             } else {
504                 ret = 0;
505             }
506         }
507         break;
508     case BIO_C_SET_NBIO:
509         if (num != 0)
510             data->connect_mode |= BIO_SOCK_NONBLOCK;
511         else
512             data->connect_mode &= ~BIO_SOCK_NONBLOCK;
513         break;
514 #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO)
515     case BIO_C_SET_TFO:
516         if (num != 0) {
517             data->connect_mode |= BIO_SOCK_TFO;
518             data->tfo_first = 1;
519         } else {
520             data->connect_mode &= ~BIO_SOCK_TFO;
521             data->tfo_first = 0;
522         }
523         break;
524 #endif
525     case BIO_C_SET_CONNECT_MODE:
526         data->connect_mode = (int)num;
527         if (num & BIO_SOCK_TFO)
528             data->tfo_first = 1;
529         else
530             data->tfo_first = 0;
531         break;
532     case BIO_C_GET_FD:
533         if (b->init) {
534             ip = (int *)ptr;
535             if (ip != NULL)
536                 *ip = b->num;
537             ret = b->num;
538         } else
539             ret = -1;
540         break;
541     case BIO_CTRL_GET_CLOSE:
542         ret = b->shutdown;
543         break;
544     case BIO_CTRL_SET_CLOSE:
545         b->shutdown = (int)num;
546         break;
547     case BIO_CTRL_PENDING:
548     case BIO_CTRL_WPENDING:
549         ret = 0;
550         break;
551     case BIO_CTRL_FLUSH:
552         break;
553     case BIO_CTRL_DUP:
554         {
555             dbio = (BIO *)ptr;
556             if (data->param_hostname)
557                 BIO_set_conn_hostname(dbio, data->param_hostname);
558             if (data->param_service)
559                 BIO_set_conn_port(dbio, data->param_service);
560             BIO_set_conn_ip_family(dbio, data->connect_family);
561             BIO_set_conn_mode(dbio, data->connect_mode);
562             /*
563              * FIXME: the cast of the function seems unlikely to be a good
564              * idea
565              */
566             (void)BIO_set_info_callback(dbio, data->info_callback);
567         }
568         break;
569     case BIO_CTRL_SET_CALLBACK:
570         ret = 0; /* use callback ctrl */
571         break;
572     case BIO_CTRL_GET_CALLBACK:
573         {
574             BIO_info_cb **fptr;
575
576             fptr = (BIO_info_cb **)ptr;
577             *fptr = data->info_callback;
578         }
579         break;
580     case BIO_CTRL_EOF:
581         ret = (b->flags & BIO_FLAGS_IN_EOF) != 0;
582         break;
583 # ifndef OPENSSL_NO_KTLS
584     case BIO_CTRL_SET_KTLS:
585         crypto_info = (ktls_crypto_info_t *)ptr;
586         ret = ktls_start(b->num, crypto_info, num);
587         if (ret)
588             BIO_set_ktls_flag(b, num);
589         break;
590     case BIO_CTRL_GET_KTLS_SEND:
591         return BIO_should_ktls_flag(b, 1) != 0;
592     case BIO_CTRL_GET_KTLS_RECV:
593         return BIO_should_ktls_flag(b, 0) != 0;
594     case BIO_CTRL_SET_KTLS_TX_SEND_CTRL_MSG:
595         BIO_set_ktls_ctrl_msg_flag(b);
596         data->record_type = num;
597         ret = 0;
598         break;
599     case BIO_CTRL_CLEAR_KTLS_TX_CTRL_MSG:
600         BIO_clear_ktls_ctrl_msg_flag(b);
601         ret = 0;
602         break;
603 # endif
604     default:
605         ret = 0;
606         break;
607     }
608     return ret;
609 }
610
611 static long conn_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp)
612 {
613     long ret = 1;
614     BIO_CONNECT *data;
615
616     data = (BIO_CONNECT *)b->ptr;
617
618     switch (cmd) {
619     case BIO_CTRL_SET_CALLBACK:
620         {
621             data->info_callback = fp;
622         }
623         break;
624     default:
625         ret = 0;
626         break;
627     }
628     return ret;
629 }
630
631 static int conn_puts(BIO *bp, const char *str)
632 {
633     int n, ret;
634
635     n = strlen(str);
636     ret = conn_write(bp, str, n);
637     return ret;
638 }
639
640 int conn_gets(BIO *bio, char *buf, int size)
641 {
642     BIO_CONNECT *data;
643     char *ptr = buf;
644     int ret = 0;
645
646     if (buf == NULL) {
647         ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
648         return -1;
649     }
650     if (size <= 0) {
651         ERR_raise(ERR_LIB_BIO, BIO_R_INVALID_ARGUMENT);
652         return -1;
653     }
654     *buf = '\0';
655
656     if (bio == NULL || bio->ptr == NULL) {
657         ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER);
658         return -1;
659     }
660     data = (BIO_CONNECT *)bio->ptr;
661     if (data->state != BIO_CONN_S_OK) {
662         ret = conn_state(bio, data);
663         if (ret <= 0)
664             return ret;
665     }
666
667     clear_socket_error();
668     while (size-- > 1) {
669 # ifndef OPENSSL_NO_KTLS
670         if (BIO_get_ktls_recv(bio))
671             ret = ktls_read_record(bio->num, ptr, 1);
672         else
673 # endif
674             ret = readsocket(bio->num, ptr, 1);
675         BIO_clear_retry_flags(bio);
676         if (ret <= 0) {
677             if (BIO_sock_should_retry(ret))
678                 BIO_set_retry_read(bio);
679             else if (ret == 0)
680                 bio->flags |= BIO_FLAGS_IN_EOF;
681             break;
682         }
683         if (*ptr++ == '\n')
684             break;
685     }
686     *ptr = '\0';
687     return ret > 0 || (bio->flags & BIO_FLAGS_IN_EOF) != 0 ? ptr - buf : ret;
688 }
689
690 BIO *BIO_new_connect(const char *str)
691 {
692     BIO *ret;
693
694     ret = BIO_new(BIO_s_connect());
695     if (ret == NULL)
696         return NULL;
697     if (BIO_set_conn_hostname(ret, str))
698         return ret;
699     BIO_free(ret);
700     return NULL;
701 }
702
703 #endif