xref: /freebsd/crypto/openssl/crypto/bio/bss_dgram.c (revision 88b8b7f0c4e9948667a2279e78e975a784049cba)
1 /*
2  * Copyright 2005-2025 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 #ifndef _GNU_SOURCE
11 # define _GNU_SOURCE
12 #endif
13 
14 #include <stdio.h>
15 #include <errno.h>
16 
17 #include "internal/time.h"
18 #include "bio_local.h"
19 #ifndef OPENSSL_NO_DGRAM
20 
21 # ifndef OPENSSL_NO_SCTP
22 #  include <netinet/sctp.h>
23 #  include <fcntl.h>
24 #  define OPENSSL_SCTP_DATA_CHUNK_TYPE            0x00
25 #  define OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE 0xc0
26 # endif
27 
28 # if defined(OPENSSL_SYS_LINUX) && !defined(IP_MTU)
29 #  define IP_MTU      14        /* linux is lame */
30 # endif
31 
32 # if OPENSSL_USE_IPV6 && !defined(IPPROTO_IPV6)
33 #  define IPPROTO_IPV6 41       /* windows is lame */
34 # endif
35 
36 # if defined(__FreeBSD__) && defined(IN6_IS_ADDR_V4MAPPED)
37 /* Standard definition causes type-punning problems. */
38 #  undef IN6_IS_ADDR_V4MAPPED
39 #  define s6_addr32 __u6_addr.__u6_addr32
40 #  define IN6_IS_ADDR_V4MAPPED(a)               \
41         (((a)->s6_addr32[0] == 0) &&          \
42          ((a)->s6_addr32[1] == 0) &&          \
43          ((a)->s6_addr32[2] == htonl(0x0000ffff)))
44 # endif
45 
46 /* Determine what method to use for BIO_sendmmsg and BIO_recvmmsg. */
47 # define M_METHOD_NONE       0
48 # define M_METHOD_RECVMMSG   1
49 # define M_METHOD_RECVMSG    2
50 # define M_METHOD_RECVFROM   3
51 # define M_METHOD_WSARECVMSG 4
52 
53 # if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
54 #  if !(__GLIBC_PREREQ(2, 14))
55 #   undef NO_RECVMMSG
56     /*
57      * Some old glibc versions may have recvmmsg and MSG_WAITFORONE flag, but
58      * not sendmmsg. We need both so force this to be disabled on these old
59      * versions
60      */
61 #   define NO_RECVMMSG
62 #  endif
63 # endif
64 # if defined(__GNU__)
65    /* GNU/Hurd does not have IP_PKTINFO yet */
66    #undef NO_RECVMSG
67    #define NO_RECVMSG
68 # endif
69 # if (defined(__ANDROID_API__) && __ANDROID_API__ < 21) || defined(_AIX)
70 #  undef NO_RECVMMSG
71 #  define NO_RECVMMSG
72 # endif
73 # if !defined(M_METHOD)
74 #  if defined(OPENSSL_SYS_WINDOWS) && defined(BIO_HAVE_WSAMSG) && !defined(NO_WSARECVMSG)
75 #   define M_METHOD  M_METHOD_WSARECVMSG
76 #  elif !defined(OPENSSL_SYS_WINDOWS) && defined(MSG_WAITFORONE) && !defined(NO_RECVMMSG)
77 #   define M_METHOD  M_METHOD_RECVMMSG
78 #  elif !defined(OPENSSL_SYS_WINDOWS) && defined(CMSG_LEN) && !defined(NO_RECVMSG)
79 #   define M_METHOD  M_METHOD_RECVMSG
80 #  elif !defined(NO_RECVFROM)
81 #   define M_METHOD  M_METHOD_RECVFROM
82 #  else
83 #   define M_METHOD  M_METHOD_NONE
84 #  endif
85 # endif
86 
87 # if defined(OPENSSL_SYS_WINDOWS)
88 #  define BIO_CMSG_SPACE(x) WSA_CMSG_SPACE(x)
89 #  define BIO_CMSG_FIRSTHDR(x) WSA_CMSG_FIRSTHDR(x)
90 #  define BIO_CMSG_NXTHDR(x, y) WSA_CMSG_NXTHDR(x, y)
91 #  define BIO_CMSG_DATA(x) WSA_CMSG_DATA(x)
92 #  define BIO_CMSG_LEN(x) WSA_CMSG_LEN(x)
93 #  define MSGHDR_TYPE WSAMSG
94 #  define CMSGHDR_TYPE WSACMSGHDR
95 # else
96 #  define MSGHDR_TYPE struct msghdr
97 #  define CMSGHDR_TYPE struct cmsghdr
98 #  define BIO_CMSG_SPACE(x) CMSG_SPACE(x)
99 #  define BIO_CMSG_FIRSTHDR(x) CMSG_FIRSTHDR(x)
100 #  define BIO_CMSG_NXTHDR(x, y) CMSG_NXTHDR(x, y)
101 #  define BIO_CMSG_DATA(x) CMSG_DATA(x)
102 #  define BIO_CMSG_LEN(x) CMSG_LEN(x)
103 # endif
104 
105 # if   M_METHOD == M_METHOD_RECVMMSG   \
106     || M_METHOD == M_METHOD_RECVMSG    \
107     || M_METHOD == M_METHOD_WSARECVMSG
108 #  if defined(__APPLE__)
109     /*
110      * CMSG_SPACE is not a constant expression on OSX even though POSIX
111      * says it's supposed to be. This should be adequate.
112      */
113 #   define BIO_CMSG_ALLOC_LEN   64
114 #  else
115 #   if defined(IPV6_PKTINFO)
116 #     define BIO_CMSG_ALLOC_LEN_1   BIO_CMSG_SPACE(sizeof(struct in6_pktinfo))
117 #   else
118 #     define BIO_CMSG_ALLOC_LEN_1   0
119 #   endif
120 #   if defined(IP_PKTINFO)
121 #     define BIO_CMSG_ALLOC_LEN_2   BIO_CMSG_SPACE(sizeof(struct in_pktinfo))
122 #   else
123 #     define BIO_CMSG_ALLOC_LEN_2   0
124 #   endif
125 #   if defined(IP_RECVDSTADDR)
126 #     define BIO_CMSG_ALLOC_LEN_3   BIO_CMSG_SPACE(sizeof(struct in_addr))
127 #   else
128 #     define BIO_CMSG_ALLOC_LEN_3   0
129 #   endif
130 #   define BIO_MAX(X,Y) ((X) > (Y) ? (X) : (Y))
131 #   define BIO_CMSG_ALLOC_LEN                                        \
132         BIO_MAX(BIO_CMSG_ALLOC_LEN_1,                                \
133                 BIO_MAX(BIO_CMSG_ALLOC_LEN_2, BIO_CMSG_ALLOC_LEN_3))
134 #  endif
135 #  if (defined(IP_PKTINFO) || defined(IP_RECVDSTADDR)) && defined(IPV6_RECVPKTINFO)
136 #   define SUPPORT_LOCAL_ADDR
137 #  endif
138 # endif
139 
140 # define BIO_MSG_N(array, stride, n) (*(BIO_MSG *)((char *)(array) + (n)*(stride)))
141 
142 static int dgram_write(BIO *h, const char *buf, int num);
143 static int dgram_read(BIO *h, char *buf, int size);
144 static int dgram_puts(BIO *h, const char *str);
145 static long dgram_ctrl(BIO *h, int cmd, long arg1, void *arg2);
146 static int dgram_new(BIO *h);
147 static int dgram_free(BIO *data);
148 static int dgram_clear(BIO *bio);
149 static int dgram_sendmmsg(BIO *b, BIO_MSG *msg,
150                           size_t stride, size_t num_msg,
151                           uint64_t flags, size_t *num_processed);
152 static int dgram_recvmmsg(BIO *b, BIO_MSG *msg,
153                           size_t stride, size_t num_msg,
154                           uint64_t flags, size_t *num_processed);
155 
156 # ifndef OPENSSL_NO_SCTP
157 static int dgram_sctp_write(BIO *h, const char *buf, int num);
158 static int dgram_sctp_read(BIO *h, char *buf, int size);
159 static int dgram_sctp_puts(BIO *h, const char *str);
160 static long dgram_sctp_ctrl(BIO *h, int cmd, long arg1, void *arg2);
161 static int dgram_sctp_new(BIO *h);
162 static int dgram_sctp_free(BIO *data);
163 static int dgram_sctp_wait_for_dry(BIO *b);
164 static int dgram_sctp_msg_waiting(BIO *b);
165 #  ifdef SCTP_AUTHENTICATION_EVENT
166 static void dgram_sctp_handle_auth_free_key_event(BIO *b, union sctp_notification
167                                                   *snp);
168 #  endif
169 # endif
170 
171 static int BIO_dgram_should_retry(int s);
172 
173 static const BIO_METHOD methods_dgramp = {
174     BIO_TYPE_DGRAM,
175     "datagram socket",
176     bwrite_conv,
177     dgram_write,
178     bread_conv,
179     dgram_read,
180     dgram_puts,
181     NULL,                       /* dgram_gets,         */
182     dgram_ctrl,
183     dgram_new,
184     dgram_free,
185     NULL,                       /* dgram_callback_ctrl */
186     dgram_sendmmsg,
187     dgram_recvmmsg,
188 };
189 
190 # ifndef OPENSSL_NO_SCTP
191 static const BIO_METHOD methods_dgramp_sctp = {
192     BIO_TYPE_DGRAM_SCTP,
193     "datagram sctp socket",
194     bwrite_conv,
195     dgram_sctp_write,
196     bread_conv,
197     dgram_sctp_read,
198     dgram_sctp_puts,
199     NULL,                       /* dgram_gets,         */
200     dgram_sctp_ctrl,
201     dgram_sctp_new,
202     dgram_sctp_free,
203     NULL,                       /* dgram_callback_ctrl */
204     NULL,                       /* sendmmsg */
205     NULL,                       /* recvmmsg */
206 };
207 # endif
208 
209 typedef struct bio_dgram_data_st {
210     BIO_ADDR peer;
211     BIO_ADDR local_addr;
212     unsigned int connected;
213     unsigned int _errno;
214     unsigned int mtu;
215     OSSL_TIME next_timeout;
216     OSSL_TIME socket_timeout;
217     unsigned int peekmode;
218     char local_addr_enabled;
219 } bio_dgram_data;
220 
221 # ifndef OPENSSL_NO_SCTP
222 typedef struct bio_dgram_sctp_save_message_st {
223     BIO *bio;
224     char *data;
225     int length;
226 } bio_dgram_sctp_save_message;
227 
228 /*
229  * Note: bio_dgram_data must be first here
230  * as we use dgram_ctrl for underlying dgram operations
231  * which will cast this struct to a bio_dgram_data
232  */
233 typedef struct bio_dgram_sctp_data_st {
234     bio_dgram_data dgram;
235     struct bio_dgram_sctp_sndinfo sndinfo;
236     struct bio_dgram_sctp_rcvinfo rcvinfo;
237     struct bio_dgram_sctp_prinfo prinfo;
238     BIO_dgram_sctp_notification_handler_fn handle_notifications;
239     void *notification_context;
240     int in_handshake;
241     int ccs_rcvd;
242     int ccs_sent;
243     int save_shutdown;
244     int peer_auth_tested;
245 } bio_dgram_sctp_data;
246 # endif
247 
BIO_s_datagram(void)248 const BIO_METHOD *BIO_s_datagram(void)
249 {
250     return &methods_dgramp;
251 }
252 
BIO_new_dgram(int fd,int close_flag)253 BIO *BIO_new_dgram(int fd, int close_flag)
254 {
255     BIO *ret;
256 
257     ret = BIO_new(BIO_s_datagram());
258     if (ret == NULL)
259         return NULL;
260     BIO_set_fd(ret, fd, close_flag);
261     return ret;
262 }
263 
dgram_new(BIO * bi)264 static int dgram_new(BIO *bi)
265 {
266     bio_dgram_data *data = OPENSSL_zalloc(sizeof(*data));
267 
268     if (data == NULL)
269         return 0;
270     bi->ptr = data;
271     return 1;
272 }
273 
dgram_free(BIO * a)274 static int dgram_free(BIO *a)
275 {
276     bio_dgram_data *data;
277 
278     if (a == NULL)
279         return 0;
280     if (!dgram_clear(a))
281         return 0;
282 
283     data = (bio_dgram_data *)a->ptr;
284     OPENSSL_free(data);
285 
286     return 1;
287 }
288 
dgram_clear(BIO * a)289 static int dgram_clear(BIO *a)
290 {
291     if (a == NULL)
292         return 0;
293     if (a->shutdown) {
294         if (a->init) {
295             BIO_closesocket(a->num);
296         }
297         a->init = 0;
298         a->flags = 0;
299     }
300     return 1;
301 }
302 
dgram_adjust_rcv_timeout(BIO * b)303 static void dgram_adjust_rcv_timeout(BIO *b)
304 {
305 # if defined(SO_RCVTIMEO)
306     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
307     OSSL_TIME timeleft;
308 
309     /* Is a timer active? */
310     if (!ossl_time_is_zero(data->next_timeout)) {
311         /* Read current socket timeout */
312 #  ifdef OPENSSL_SYS_WINDOWS
313         int timeout;
314         int sz = sizeof(timeout);
315 
316         if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
317                        (void *)&timeout, &sz) < 0)
318             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
319                            "calling getsockopt()");
320         else
321             data->socket_timeout = ossl_ms2time(timeout);
322 #  else
323         struct timeval tv;
324         socklen_t sz = sizeof(tv);
325 
326         if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, &tv, &sz) < 0)
327             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
328                            "calling getsockopt()");
329         else
330             data->socket_timeout = ossl_time_from_timeval(tv);
331 #  endif
332 
333         /* Calculate time left until timer expires */
334         timeleft = ossl_time_subtract(data->next_timeout, ossl_time_now());
335         if (ossl_time_compare(timeleft, ossl_ticks2time(OSSL_TIME_US)) < 0)
336             timeleft = ossl_ticks2time(OSSL_TIME_US);
337 
338         /*
339          * Adjust socket timeout if next handshake message timer will expire
340          * earlier.
341          */
342         if (ossl_time_is_zero(data->socket_timeout)
343             || ossl_time_compare(data->socket_timeout, timeleft) >= 0) {
344 #  ifdef OPENSSL_SYS_WINDOWS
345             timeout = (int)ossl_time2ms(timeleft);
346             if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
347                            (void *)&timeout, sizeof(timeout)) < 0)
348                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
349                                "calling setsockopt()");
350 #  else
351             tv = ossl_time_to_timeval(timeleft);
352             if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, &tv,
353                            sizeof(tv)) < 0)
354                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
355                                "calling setsockopt()");
356 #  endif
357         }
358     }
359 # endif
360 }
361 
dgram_update_local_addr(BIO * b)362 static void dgram_update_local_addr(BIO *b)
363 {
364     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
365     socklen_t addr_len = sizeof(data->local_addr);
366 
367     if (getsockname(b->num, &data->local_addr.sa, &addr_len) < 0)
368         /*
369          * This should not be possible, but zero-initialize and return
370          * anyway.
371          */
372         BIO_ADDR_clear(&data->local_addr);
373 }
374 
375 # if M_METHOD == M_METHOD_RECVMMSG || M_METHOD == M_METHOD_RECVMSG || M_METHOD == M_METHOD_WSARECVMSG
dgram_get_sock_family(BIO * b)376 static int dgram_get_sock_family(BIO *b)
377 {
378     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
379     return data->local_addr.sa.sa_family;
380 }
381 # endif
382 
dgram_reset_rcv_timeout(BIO * b)383 static void dgram_reset_rcv_timeout(BIO *b)
384 {
385 # if defined(SO_RCVTIMEO)
386     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
387 
388     /* Is a timer active? */
389     if (!ossl_time_is_zero(data->next_timeout)) {
390 #  ifdef OPENSSL_SYS_WINDOWS
391         int timeout = (int)ossl_time2ms(data->socket_timeout);
392 
393         if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
394                        (void *)&timeout, sizeof(timeout)) < 0)
395             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
396                            "calling setsockopt()");
397 #  else
398         struct timeval tv = ossl_time_to_timeval(data->socket_timeout);
399 
400         if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0)
401             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
402                            "calling setsockopt()");
403 #  endif
404     }
405 # endif
406 }
407 
dgram_read(BIO * b,char * out,int outl)408 static int dgram_read(BIO *b, char *out, int outl)
409 {
410     int ret = 0;
411     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
412     int flags = 0;
413 
414     BIO_ADDR peer;
415     socklen_t len = sizeof(peer);
416 
417     if (out != NULL) {
418         clear_socket_error();
419         BIO_ADDR_clear(&peer);
420         dgram_adjust_rcv_timeout(b);
421         if (data->peekmode)
422             flags = MSG_PEEK;
423         ret = recvfrom(b->num, out, outl, flags,
424                        BIO_ADDR_sockaddr_noconst(&peer), &len);
425 
426         if (!data->connected && ret >= 0)
427             BIO_ctrl(b, BIO_CTRL_DGRAM_SET_PEER, 0, &peer);
428 
429         BIO_clear_retry_flags(b);
430         if (ret < 0) {
431             if (BIO_dgram_should_retry(ret)) {
432                 BIO_set_retry_read(b);
433                 data->_errno = get_last_socket_error();
434             }
435         }
436 
437         dgram_reset_rcv_timeout(b);
438     }
439     return ret;
440 }
441 
dgram_write(BIO * b,const char * in,int inl)442 static int dgram_write(BIO *b, const char *in, int inl)
443 {
444     int ret;
445     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
446     clear_socket_error();
447 
448     if (data->connected)
449         ret = writesocket(b->num, in, inl);
450     else {
451         int peerlen = BIO_ADDR_sockaddr_size(&data->peer);
452 
453         ret = sendto(b->num, in, inl, 0,
454                      BIO_ADDR_sockaddr(&data->peer), peerlen);
455     }
456 
457     BIO_clear_retry_flags(b);
458     if (ret <= 0) {
459         if (BIO_dgram_should_retry(ret)) {
460             BIO_set_retry_write(b);
461             data->_errno = get_last_socket_error();
462         }
463     }
464     return ret;
465 }
466 
dgram_get_mtu_overhead(BIO_ADDR * addr)467 static long dgram_get_mtu_overhead(BIO_ADDR *addr)
468 {
469     long ret;
470 
471     switch (BIO_ADDR_family(addr)) {
472     case AF_INET:
473         /*
474          * Assume this is UDP - 20 bytes for IP, 8 bytes for UDP
475          */
476         ret = 28;
477         break;
478 # if OPENSSL_USE_IPV6
479     case AF_INET6:
480         {
481 #  ifdef IN6_IS_ADDR_V4MAPPED
482             struct in6_addr tmp_addr;
483 
484             if (BIO_ADDR_rawaddress(addr, &tmp_addr, NULL)
485                 && IN6_IS_ADDR_V4MAPPED(&tmp_addr))
486                 /*
487                  * Assume this is UDP - 20 bytes for IP, 8 bytes for UDP
488                  */
489                 ret = 28;
490             else
491 #  endif
492             /*
493              * Assume this is UDP - 40 bytes for IP, 8 bytes for UDP
494              */
495             ret = 48;
496         }
497         break;
498 # endif
499     default:
500         /* We don't know. Go with the historical default */
501         ret = 28;
502         break;
503     }
504     return ret;
505 }
506 
507 /* Enables appropriate destination address reception option on the socket. */
508 # if defined(SUPPORT_LOCAL_ADDR)
enable_local_addr(BIO * b,int enable)509 static int enable_local_addr(BIO *b, int enable) {
510     int af = dgram_get_sock_family(b);
511 
512     if (af == AF_INET) {
513 #  if defined(IP_PKTINFO)
514         /* IP_PKTINFO is preferred */
515         if (setsockopt(b->num, IPPROTO_IP, IP_PKTINFO,
516                        (void *)&enable, sizeof(enable)) < 0)
517             return 0;
518 
519         return 1;
520 
521 #  elif defined(IP_RECVDSTADDR)
522         /* Fall back to IP_RECVDSTADDR */
523 
524         if (setsockopt(b->num, IPPROTO_IP, IP_RECVDSTADDR,
525                        &enable, sizeof(enable)) < 0)
526             return 0;
527 
528         return 1;
529 #  endif
530     }
531 
532 #  if OPENSSL_USE_IPV6
533     if (af == AF_INET6) {
534 #   if defined(IPV6_RECVPKTINFO)
535         if (setsockopt(b->num, IPPROTO_IPV6, IPV6_RECVPKTINFO,
536                        &enable, sizeof(enable)) < 0)
537             return 0;
538 
539         return 1;
540 #   endif
541     }
542 #  endif
543 
544     return 0;
545 }
546 # endif
547 
dgram_ctrl(BIO * b,int cmd,long num,void * ptr)548 static long dgram_ctrl(BIO *b, int cmd, long num, void *ptr)
549 {
550     long ret = 1;
551     int *ip;
552     bio_dgram_data *data = NULL;
553 # ifndef __DJGPP__
554     /* There are currently no cases where this is used on djgpp/watt32. */
555     int sockopt_val = 0;
556 # endif
557     int d_errno;
558 # if defined(OPENSSL_SYS_LINUX) && (defined(IP_MTU_DISCOVER) || defined(IP_MTU))
559     socklen_t sockopt_len;      /* assume that system supporting IP_MTU is
560                                  * modern enough to define socklen_t */
561     socklen_t addr_len;
562     BIO_ADDR addr;
563 # endif
564     struct sockaddr_storage ss;
565     socklen_t ss_len = sizeof(ss);
566 
567     data = (bio_dgram_data *)b->ptr;
568 
569     switch (cmd) {
570     case BIO_CTRL_RESET:
571         num = 0;
572         ret = 0;
573         break;
574     case BIO_CTRL_INFO:
575         ret = 0;
576         break;
577     case BIO_C_SET_FD:
578         dgram_clear(b);
579         b->num = *((int *)ptr);
580         b->shutdown = (int)num;
581         b->init = 1;
582         dgram_update_local_addr(b);
583         if (getpeername(b->num, (struct sockaddr *)&ss, &ss_len) == 0) {
584             BIO_ADDR_make(&data->peer, BIO_ADDR_sockaddr((BIO_ADDR *)&ss));
585             data->connected = 1;
586         }
587 # if defined(SUPPORT_LOCAL_ADDR)
588         if (data->local_addr_enabled) {
589             if (enable_local_addr(b, 1) < 1)
590                 data->local_addr_enabled = 0;
591         }
592 # endif
593         break;
594     case BIO_C_GET_FD:
595         if (b->init) {
596             ip = (int *)ptr;
597             if (ip != NULL)
598                 *ip = b->num;
599             ret = b->num;
600         } else
601             ret = -1;
602         break;
603     case BIO_CTRL_GET_CLOSE:
604         ret = b->shutdown;
605         break;
606     case BIO_CTRL_SET_CLOSE:
607         b->shutdown = (int)num;
608         break;
609     case BIO_CTRL_PENDING:
610     case BIO_CTRL_WPENDING:
611         ret = 0;
612         break;
613     case BIO_CTRL_DUP:
614     case BIO_CTRL_FLUSH:
615         ret = 1;
616         break;
617     case BIO_CTRL_DGRAM_CONNECT:
618         BIO_ADDR_make(&data->peer, BIO_ADDR_sockaddr((BIO_ADDR *)ptr));
619         break;
620         /* (Linux)kernel sets DF bit on outgoing IP packets */
621     case BIO_CTRL_DGRAM_MTU_DISCOVER:
622 # if defined(OPENSSL_SYS_LINUX) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
623         addr_len = (socklen_t) sizeof(addr);
624         BIO_ADDR_clear(&addr);
625         if (getsockname(b->num, &addr.sa, &addr_len) < 0) {
626             ret = 0;
627             break;
628         }
629         switch (addr.sa.sa_family) {
630         case AF_INET:
631             sockopt_val = IP_PMTUDISC_DO;
632             if ((ret = setsockopt(b->num, IPPROTO_IP, IP_MTU_DISCOVER,
633                                   &sockopt_val, sizeof(sockopt_val))) < 0)
634                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
635                                "calling setsockopt()");
636             break;
637 #  if OPENSSL_USE_IPV6 && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
638         case AF_INET6:
639             sockopt_val = IPV6_PMTUDISC_DO;
640             if ((ret = setsockopt(b->num, IPPROTO_IPV6, IPV6_MTU_DISCOVER,
641                                   &sockopt_val, sizeof(sockopt_val))) < 0)
642                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
643                                "calling setsockopt()");
644             break;
645 #  endif
646         default:
647             ret = -1;
648             break;
649         }
650 # else
651         ret = -1;
652 # endif
653         break;
654     case BIO_CTRL_DGRAM_QUERY_MTU:
655 # if defined(OPENSSL_SYS_LINUX) && defined(IP_MTU)
656         addr_len = (socklen_t) sizeof(addr);
657         BIO_ADDR_clear(&addr);
658         if (getsockname(b->num, &addr.sa, &addr_len) < 0) {
659             ret = 0;
660             break;
661         }
662         sockopt_len = sizeof(sockopt_val);
663         switch (addr.sa.sa_family) {
664         case AF_INET:
665             if ((ret =
666                  getsockopt(b->num, IPPROTO_IP, IP_MTU, (void *)&sockopt_val,
667                             &sockopt_len)) < 0 || sockopt_val < 0) {
668                 ret = 0;
669             } else {
670                 data->mtu = sockopt_val - dgram_get_mtu_overhead(&addr);
671                 ret = data->mtu;
672             }
673             break;
674 #  if OPENSSL_USE_IPV6 && defined(IPV6_MTU)
675         case AF_INET6:
676             if ((ret =
677                  getsockopt(b->num, IPPROTO_IPV6, IPV6_MTU,
678                             (void *)&sockopt_val, &sockopt_len)) < 0
679                 || sockopt_val < 0) {
680                 ret = 0;
681             } else {
682                 data->mtu = sockopt_val - dgram_get_mtu_overhead(&addr);
683                 ret = data->mtu;
684             }
685             break;
686 #  endif
687         default:
688             ret = 0;
689             break;
690         }
691 # else
692         ret = 0;
693 # endif
694         break;
695     case BIO_CTRL_DGRAM_GET_FALLBACK_MTU:
696         ret = -dgram_get_mtu_overhead(&data->peer);
697         switch (BIO_ADDR_family(&data->peer)) {
698         case AF_INET:
699             ret += 576;
700             break;
701 # if OPENSSL_USE_IPV6
702         case AF_INET6:
703             {
704 #  ifdef IN6_IS_ADDR_V4MAPPED
705                 struct in6_addr tmp_addr;
706                 if (BIO_ADDR_rawaddress(&data->peer, &tmp_addr, NULL)
707                     && IN6_IS_ADDR_V4MAPPED(&tmp_addr))
708                     ret += 576;
709                 else
710 #  endif
711                     ret += 1280;
712             }
713             break;
714 # endif
715         default:
716             ret += 576;
717             break;
718         }
719         break;
720     case BIO_CTRL_DGRAM_GET_MTU:
721         return data->mtu;
722     case BIO_CTRL_DGRAM_SET_MTU:
723         data->mtu = num;
724         ret = num;
725         break;
726     case BIO_CTRL_DGRAM_SET_CONNECTED:
727         if (ptr != NULL) {
728             data->connected = 1;
729             BIO_ADDR_make(&data->peer, BIO_ADDR_sockaddr((BIO_ADDR *)ptr));
730         } else {
731             data->connected = 0;
732             BIO_ADDR_clear(&data->peer);
733         }
734         break;
735     case BIO_CTRL_DGRAM_GET_PEER:
736         ret = BIO_ADDR_sockaddr_size(&data->peer);
737         /* FIXME: if num < ret, we will only return part of an address.
738            That should bee an error, no? */
739         if (num == 0 || num > ret)
740             num = ret;
741         memcpy(ptr, &data->peer, (ret = num));
742         break;
743     case BIO_CTRL_DGRAM_SET_PEER:
744         BIO_ADDR_make(&data->peer, BIO_ADDR_sockaddr((BIO_ADDR *)ptr));
745         break;
746     case BIO_CTRL_DGRAM_DETECT_PEER_ADDR:
747         {
748             BIO_ADDR xaddr, *p = &data->peer;
749             socklen_t xaddr_len = sizeof(xaddr.sa);
750 
751             if (BIO_ADDR_family(p) == AF_UNSPEC) {
752                 if (getpeername(b->num, (void *)&xaddr.sa, &xaddr_len) == 0
753                     && BIO_ADDR_family(&xaddr) != AF_UNSPEC) {
754                     p = &xaddr;
755                 } else {
756                     ret = 0;
757                     break;
758                 }
759             }
760 
761             ret = BIO_ADDR_sockaddr_size(p);
762             if (num == 0 || num > ret)
763                 num = ret;
764 
765             memcpy(ptr, p, (ret = num));
766         }
767         break;
768     case BIO_C_SET_NBIO:
769         if (!BIO_socket_nbio(b->num, num != 0))
770             ret = 0;
771         break;
772     case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
773         data->next_timeout = ossl_time_from_timeval(*(struct timeval *)ptr);
774         break;
775 # if defined(SO_RCVTIMEO)
776     case BIO_CTRL_DGRAM_SET_RECV_TIMEOUT:
777 #  ifdef OPENSSL_SYS_WINDOWS
778         {
779             struct timeval *tv = (struct timeval *)ptr;
780             int timeout = tv->tv_sec * 1000 + tv->tv_usec / 1000;
781 
782             if ((ret = setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
783                                   (void *)&timeout, sizeof(timeout))) < 0)
784                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
785                                "calling setsockopt()");
786         }
787 #  else
788         if ((ret = setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, ptr,
789                               sizeof(struct timeval))) < 0)
790             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
791                            "calling setsockopt()");
792 #  endif
793         break;
794     case BIO_CTRL_DGRAM_GET_RECV_TIMEOUT:
795         {
796 #  ifdef OPENSSL_SYS_WINDOWS
797             int sz = 0;
798             int timeout;
799             struct timeval *tv = (struct timeval *)ptr;
800 
801             sz = sizeof(timeout);
802             if ((ret = getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
803                                   (void *)&timeout, &sz)) < 0) {
804                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
805                                "calling getsockopt()");
806             } else {
807                 tv->tv_sec = timeout / 1000;
808                 tv->tv_usec = (timeout % 1000) * 1000;
809                 ret = sizeof(*tv);
810             }
811 #  else
812             socklen_t sz = sizeof(struct timeval);
813             if ((ret = getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
814                                   ptr, &sz)) < 0) {
815                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
816                                "calling getsockopt()");
817             } else {
818                 OPENSSL_assert((size_t)sz <= sizeof(struct timeval));
819                 ret = (int)sz;
820             }
821 #  endif
822         }
823         break;
824 # endif
825 # if defined(SO_SNDTIMEO)
826     case BIO_CTRL_DGRAM_SET_SEND_TIMEOUT:
827 #  ifdef OPENSSL_SYS_WINDOWS
828         {
829             struct timeval *tv = (struct timeval *)ptr;
830             int timeout = tv->tv_sec * 1000 + tv->tv_usec / 1000;
831 
832             if ((ret = setsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
833                                   (void *)&timeout, sizeof(timeout))) < 0)
834                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
835                                "calling setsockopt()");
836         }
837 #  else
838         if ((ret = setsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO, ptr,
839                               sizeof(struct timeval))) < 0)
840             ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
841                            "calling setsockopt()");
842 #  endif
843         break;
844     case BIO_CTRL_DGRAM_GET_SEND_TIMEOUT:
845         {
846 #  ifdef OPENSSL_SYS_WINDOWS
847             int sz = 0;
848             int timeout;
849             struct timeval *tv = (struct timeval *)ptr;
850 
851             sz = sizeof(timeout);
852             if ((ret = getsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
853                                   (void *)&timeout, &sz)) < 0) {
854                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
855                                "calling getsockopt()");
856             } else {
857                 tv->tv_sec = timeout / 1000;
858                 tv->tv_usec = (timeout % 1000) * 1000;
859                 ret = sizeof(*tv);
860             }
861 #  else
862             socklen_t sz = sizeof(struct timeval);
863 
864             if ((ret = getsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
865                                   ptr, &sz)) < 0) {
866                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
867                                "calling getsockopt()");
868             } else {
869                 OPENSSL_assert((size_t)sz <= sizeof(struct timeval));
870                 ret = (int)sz;
871             }
872 #  endif
873         }
874         break;
875 # endif
876     case BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP:
877         /* fall-through */
878     case BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP:
879 # ifdef OPENSSL_SYS_WINDOWS
880         d_errno = (data->_errno == WSAETIMEDOUT);
881 # else
882         d_errno = (data->_errno == EAGAIN);
883 # endif
884         if (d_errno) {
885             ret = 1;
886             data->_errno = 0;
887         } else
888             ret = 0;
889         break;
890 # ifdef EMSGSIZE
891     case BIO_CTRL_DGRAM_MTU_EXCEEDED:
892         if (data->_errno == EMSGSIZE) {
893             ret = 1;
894             data->_errno = 0;
895         } else
896             ret = 0;
897         break;
898 # endif
899     case BIO_CTRL_DGRAM_SET_DONT_FRAG:
900         switch (data->peer.sa.sa_family) {
901         case AF_INET:
902 # if defined(IP_DONTFRAG)
903             sockopt_val = num ? 1 : 0;
904             if ((ret = setsockopt(b->num, IPPROTO_IP, IP_DONTFRAG,
905                                   &sockopt_val, sizeof(sockopt_val))) < 0)
906                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
907                                "calling setsockopt()");
908 # elif defined(OPENSSL_SYS_LINUX) && defined(IP_MTU_DISCOVER) && defined (IP_PMTUDISC_PROBE)
909             sockopt_val = num ? IP_PMTUDISC_PROBE : IP_PMTUDISC_DONT;
910             if ((ret = setsockopt(b->num, IPPROTO_IP, IP_MTU_DISCOVER,
911                                   &sockopt_val, sizeof(sockopt_val))) < 0)
912                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
913                                "calling setsockopt()");
914 # elif defined(OPENSSL_SYS_WINDOWS) && defined(IP_DONTFRAGMENT)
915             sockopt_val = num ? 1 : 0;
916             if ((ret = setsockopt(b->num, IPPROTO_IP, IP_DONTFRAGMENT,
917                                   (const char *)&sockopt_val,
918                                   sizeof(sockopt_val))) < 0)
919                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
920                                "calling setsockopt()");
921 # else
922             ret = -1;
923 # endif
924             break;
925 # if OPENSSL_USE_IPV6
926         case AF_INET6:
927 #  if defined(IPV6_DONTFRAG)
928             sockopt_val = num ? 1 : 0;
929             if ((ret = setsockopt(b->num, IPPROTO_IPV6, IPV6_DONTFRAG,
930                                   (const void *)&sockopt_val,
931                                   sizeof(sockopt_val))) < 0)
932                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
933                                "calling setsockopt()");
934 
935 #  elif defined(OPENSSL_SYS_LINUX) && defined(IPV6_MTUDISCOVER)
936             sockopt_val = num ? IP_PMTUDISC_PROBE : IP_PMTUDISC_DONT;
937             if ((ret = setsockopt(b->num, IPPROTO_IPV6, IPV6_MTU_DISCOVER,
938                                   &sockopt_val, sizeof(sockopt_val))) < 0)
939                 ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(),
940                                "calling setsockopt()");
941 #  else
942             ret = -1;
943 #  endif
944             break;
945 # endif
946         default:
947             ret = -1;
948             break;
949         }
950         break;
951     case BIO_CTRL_DGRAM_GET_MTU_OVERHEAD:
952         ret = dgram_get_mtu_overhead(&data->peer);
953         break;
954 
955     /*
956      * BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE is used here for compatibility
957      * reasons. When BIO_CTRL_DGRAM_SET_PEEK_MODE was first defined its value
958      * was incorrectly clashing with BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE. The
959      * value has been updated to a non-clashing value. However to preserve
960      * binary compatibility we now respond to both the old value and the new one
961      */
962     case BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE:
963     case BIO_CTRL_DGRAM_SET_PEEK_MODE:
964         data->peekmode = (unsigned int)num;
965         break;
966 
967     case BIO_CTRL_DGRAM_GET_LOCAL_ADDR_CAP:
968 # if defined(SUPPORT_LOCAL_ADDR)
969         ret = 1;
970 # else
971         ret = 0;
972 # endif
973         break;
974 
975     case BIO_CTRL_DGRAM_SET_LOCAL_ADDR_ENABLE:
976 # if defined(SUPPORT_LOCAL_ADDR)
977         num = num > 0;
978         if (num != data->local_addr_enabled) {
979             if (enable_local_addr(b, num) < 1) {
980                 ret = 0;
981                 break;
982             }
983 
984             data->local_addr_enabled = (char)num;
985         }
986 # else
987         ret = 0;
988 # endif
989         break;
990 
991     case BIO_CTRL_DGRAM_GET_LOCAL_ADDR_ENABLE:
992         *(int *)ptr = data->local_addr_enabled;
993         break;
994 
995     case BIO_CTRL_DGRAM_GET_EFFECTIVE_CAPS:
996         ret = (long)(BIO_DGRAM_CAP_HANDLES_DST_ADDR
997                      | BIO_DGRAM_CAP_HANDLES_SRC_ADDR
998                      | BIO_DGRAM_CAP_PROVIDES_DST_ADDR
999                      | BIO_DGRAM_CAP_PROVIDES_SRC_ADDR);
1000         break;
1001 
1002     case BIO_CTRL_GET_RPOLL_DESCRIPTOR:
1003     case BIO_CTRL_GET_WPOLL_DESCRIPTOR:
1004         {
1005             BIO_POLL_DESCRIPTOR *pd = ptr;
1006 
1007             pd->type        = BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD;
1008             pd->value.fd    = b->num;
1009         }
1010         break;
1011 
1012     default:
1013         ret = 0;
1014         break;
1015     }
1016     /* Normalize if error */
1017     if (ret < 0)
1018         ret = -1;
1019     return ret;
1020 }
1021 
dgram_puts(BIO * bp,const char * str)1022 static int dgram_puts(BIO *bp, const char *str)
1023 {
1024     int n, ret;
1025 
1026     n = strlen(str);
1027     ret = dgram_write(bp, str, n);
1028     return ret;
1029 }
1030 
1031 # if M_METHOD == M_METHOD_WSARECVMSG
translate_msg_win(BIO * b,WSAMSG * mh,WSABUF * iov,unsigned char * control,BIO_MSG * msg)1032 static void translate_msg_win(BIO *b, WSAMSG *mh, WSABUF *iov,
1033                               unsigned char *control, BIO_MSG *msg)
1034 {
1035     iov->len = msg->data_len;
1036     iov->buf = msg->data;
1037 
1038     /* Windows requires namelen to be set exactly */
1039     mh->name = msg->peer != NULL ? &msg->peer->sa : NULL;
1040     if (msg->peer != NULL && dgram_get_sock_family(b) == AF_INET)
1041         mh->namelen = sizeof(struct sockaddr_in);
1042 #  if OPENSSL_USE_IPV6
1043     else if (msg->peer != NULL && dgram_get_sock_family(b) == AF_INET6)
1044         mh->namelen = sizeof(struct sockaddr_in6);
1045 #  endif
1046     else
1047         mh->namelen = 0;
1048 
1049     /*
1050      * When local address reception (IP_PKTINFO, etc.) is enabled, on Windows
1051      * this causes WSARecvMsg to fail if the control buffer is too small to hold
1052      * the structure, or if no control buffer is passed. So we need to give it
1053      * the control buffer even if we aren't actually going to examine the
1054      * result.
1055      */
1056     mh->lpBuffers       = iov;
1057     mh->dwBufferCount   = 1;
1058     mh->Control.len     = BIO_CMSG_ALLOC_LEN;
1059     mh->Control.buf     = control;
1060     mh->dwFlags         = 0;
1061 }
1062 # endif
1063 
1064 # if M_METHOD == M_METHOD_RECVMMSG || M_METHOD == M_METHOD_RECVMSG
1065 /* Translates a BIO_MSG to a msghdr and iovec. */
translate_msg(BIO * b,struct msghdr * mh,struct iovec * iov,unsigned char * control,BIO_MSG * msg)1066 static void translate_msg(BIO *b, struct msghdr *mh, struct iovec *iov,
1067                           unsigned char *control, BIO_MSG *msg)
1068 {
1069     bio_dgram_data *data;
1070 
1071     iov->iov_base = msg->data;
1072     iov->iov_len  = msg->data_len;
1073 
1074     data = (bio_dgram_data *)b->ptr;
1075     if (data->connected == 0) {
1076         /* macOS requires msg_namelen be 0 if msg_name is NULL */
1077         mh->msg_name = msg->peer != NULL ? &msg->peer->sa : NULL;
1078         if (msg->peer != NULL && dgram_get_sock_family(b) == AF_INET)
1079             mh->msg_namelen = sizeof(struct sockaddr_in);
1080 #  if OPENSSL_USE_IPV6
1081         else if (msg->peer != NULL && dgram_get_sock_family(b) == AF_INET6)
1082             mh->msg_namelen = sizeof(struct sockaddr_in6);
1083 #  endif
1084         else
1085             mh->msg_namelen = 0;
1086     } else {
1087         mh->msg_name = NULL;
1088         mh->msg_namelen = 0;
1089     }
1090 
1091     mh->msg_iov         = iov;
1092     mh->msg_iovlen      = 1;
1093     mh->msg_control     = msg->local != NULL ? control : NULL;
1094     mh->msg_controllen  = msg->local != NULL ? BIO_CMSG_ALLOC_LEN : 0;
1095     mh->msg_flags       = 0;
1096 }
1097 # endif
1098 
1099 # if M_METHOD == M_METHOD_RECVMMSG || M_METHOD == M_METHOD_RECVMSG || M_METHOD == M_METHOD_WSARECVMSG
1100 /* Extracts destination address from the control buffer. */
extract_local(BIO * b,MSGHDR_TYPE * mh,BIO_ADDR * local)1101 static int extract_local(BIO *b, MSGHDR_TYPE *mh, BIO_ADDR *local) {
1102 #  if defined(IP_PKTINFO) || defined(IP_RECVDSTADDR) || defined(IPV6_PKTINFO)
1103     CMSGHDR_TYPE *cmsg;
1104     int af = dgram_get_sock_family(b);
1105 
1106     for (cmsg = BIO_CMSG_FIRSTHDR(mh); cmsg != NULL;
1107          cmsg = BIO_CMSG_NXTHDR(mh, cmsg)) {
1108         if (af == AF_INET) {
1109             if (cmsg->cmsg_level != IPPROTO_IP)
1110                 continue;
1111 
1112 #   if defined(IP_PKTINFO)
1113             if (cmsg->cmsg_type != IP_PKTINFO)
1114                 continue;
1115 
1116             local->s_in.sin_addr =
1117                 ((struct in_pktinfo *)BIO_CMSG_DATA(cmsg))->ipi_addr;
1118 
1119 #   elif defined(IP_RECVDSTADDR)
1120             if (cmsg->cmsg_type != IP_RECVDSTADDR)
1121                 continue;
1122 
1123             local->s_in.sin_addr = *(struct in_addr *)BIO_CMSG_DATA(cmsg);
1124 #   endif
1125 
1126 #   if defined(IP_PKTINFO) || defined(IP_RECVDSTADDR)
1127             {
1128                 bio_dgram_data *data = b->ptr;
1129 
1130                 local->s_in.sin_family = AF_INET;
1131                 local->s_in.sin_port   = data->local_addr.s_in.sin_port;
1132             }
1133             return 1;
1134 #   endif
1135         }
1136 #   if OPENSSL_USE_IPV6
1137         else if (af == AF_INET6) {
1138             if (cmsg->cmsg_level != IPPROTO_IPV6)
1139                 continue;
1140 
1141 #    if defined(IPV6_RECVPKTINFO)
1142             if (cmsg->cmsg_type != IPV6_PKTINFO)
1143                 continue;
1144 
1145             {
1146                 bio_dgram_data *data = b->ptr;
1147 
1148                 local->s_in6.sin6_addr     =
1149                     ((struct in6_pktinfo *)BIO_CMSG_DATA(cmsg))->ipi6_addr;
1150                 local->s_in6.sin6_family   = AF_INET6;
1151                 local->s_in6.sin6_port     = data->local_addr.s_in6.sin6_port;
1152                 local->s_in6.sin6_scope_id =
1153                     data->local_addr.s_in6.sin6_scope_id;
1154                 local->s_in6.sin6_flowinfo = 0;
1155             }
1156             return 1;
1157 #    endif
1158         }
1159 #   endif
1160     }
1161 #  endif
1162 
1163     return 0;
1164 }
1165 
pack_local(BIO * b,MSGHDR_TYPE * mh,const BIO_ADDR * local)1166 static int pack_local(BIO *b, MSGHDR_TYPE *mh, const BIO_ADDR *local) {
1167     int af = dgram_get_sock_family(b);
1168 #  if defined(IP_PKTINFO) || defined(IP_RECVDSTADDR) || defined(IPV6_PKTINFO)
1169     CMSGHDR_TYPE *cmsg;
1170     bio_dgram_data *data = b->ptr;
1171 #  endif
1172 
1173     if (af == AF_INET) {
1174 #  if defined(IP_PKTINFO)
1175         struct in_pktinfo *info;
1176 
1177 #   if defined(OPENSSL_SYS_WINDOWS)
1178         cmsg = (CMSGHDR_TYPE *)mh->Control.buf;
1179 #   else
1180         cmsg = (CMSGHDR_TYPE *)mh->msg_control;
1181 #   endif
1182 
1183         cmsg->cmsg_len   = BIO_CMSG_LEN(sizeof(struct in_pktinfo));
1184         cmsg->cmsg_level = IPPROTO_IP;
1185         cmsg->cmsg_type  = IP_PKTINFO;
1186 
1187         info = (struct in_pktinfo *)BIO_CMSG_DATA(cmsg);
1188 #   if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_CYGWIN) && !defined(__FreeBSD__) && !defined(__QNX__)
1189         info->ipi_spec_dst      = local->s_in.sin_addr;
1190 #   endif
1191         info->ipi_addr.s_addr   = 0;
1192         info->ipi_ifindex       = 0;
1193 
1194         /*
1195          * We cannot override source port using this API, therefore
1196          * ensure the application specified a source port of 0
1197          * or the one we are bound to. (Better to error than silently
1198          * ignore this.)
1199          */
1200         if (local->s_in.sin_port != 0
1201             && data->local_addr.s_in.sin_port != local->s_in.sin_port) {
1202             ERR_raise(ERR_LIB_BIO, BIO_R_PORT_MISMATCH);
1203             return 0;
1204         }
1205 
1206 #   if defined(OPENSSL_SYS_WINDOWS)
1207         mh->Control.len = BIO_CMSG_SPACE(sizeof(struct in_pktinfo));
1208 #   else
1209         mh->msg_controllen = BIO_CMSG_SPACE(sizeof(struct in_pktinfo));
1210 #   endif
1211         return 1;
1212 
1213 #  elif defined(IP_SENDSRCADDR)
1214         struct in_addr *info;
1215 
1216         /*
1217          * At least FreeBSD is very pedantic about using IP_SENDSRCADDR when we
1218          * are not bound to 0.0.0.0 or ::, even if the address matches what we
1219          * bound to. Support this by not packing the structure if the address
1220          * matches our understanding of our local address. IP_SENDSRCADDR is a
1221          * BSD thing, so we don't need an explicit test for BSD here.
1222          */
1223         if (local->s_in.sin_addr.s_addr == data->local_addr.s_in.sin_addr.s_addr) {
1224             mh->msg_control    = NULL;
1225             mh->msg_controllen = 0;
1226             return 1;
1227         }
1228 
1229         cmsg = (struct cmsghdr *)mh->msg_control;
1230         cmsg->cmsg_len   = BIO_CMSG_LEN(sizeof(struct in_addr));
1231         cmsg->cmsg_level = IPPROTO_IP;
1232         cmsg->cmsg_type  = IP_SENDSRCADDR;
1233 
1234         info = (struct in_addr *)BIO_CMSG_DATA(cmsg);
1235         *info = local->s_in.sin_addr;
1236 
1237         /* See comment above. */
1238         if (local->s_in.sin_port != 0
1239             && data->local_addr.s_in.sin_port != local->s_in.sin_port) {
1240             ERR_raise(ERR_LIB_BIO, BIO_R_PORT_MISMATCH);
1241             return 0;
1242         }
1243 
1244         mh->msg_controllen = BIO_CMSG_SPACE(sizeof(struct in_addr));
1245         return 1;
1246 #  endif
1247     }
1248 #  if OPENSSL_USE_IPV6
1249     else if (af == AF_INET6) {
1250 #   if defined(IPV6_PKTINFO)
1251         struct in6_pktinfo *info;
1252 
1253 #    if defined(OPENSSL_SYS_WINDOWS)
1254         cmsg = (CMSGHDR_TYPE *)mh->Control.buf;
1255 #    else
1256         cmsg = (CMSGHDR_TYPE *)mh->msg_control;
1257 #    endif
1258         cmsg->cmsg_len   = BIO_CMSG_LEN(sizeof(struct in6_pktinfo));
1259         cmsg->cmsg_level = IPPROTO_IPV6;
1260         cmsg->cmsg_type  = IPV6_PKTINFO;
1261 
1262         info = (struct in6_pktinfo *)BIO_CMSG_DATA(cmsg);
1263         info->ipi6_addr     = local->s_in6.sin6_addr;
1264         info->ipi6_ifindex  = 0;
1265 
1266         /*
1267          * See comment above, but also applies to the other fields
1268          * in sockaddr_in6.
1269          */
1270         if (local->s_in6.sin6_port != 0
1271             && data->local_addr.s_in6.sin6_port != local->s_in6.sin6_port) {
1272             ERR_raise(ERR_LIB_BIO, BIO_R_PORT_MISMATCH);
1273             return 0;
1274         }
1275 
1276         if (local->s_in6.sin6_scope_id != 0
1277             && data->local_addr.s_in6.sin6_scope_id != local->s_in6.sin6_scope_id) {
1278             ERR_raise(ERR_LIB_BIO, BIO_R_PORT_MISMATCH);
1279             return 0;
1280         }
1281 
1282 #    if defined(OPENSSL_SYS_WINDOWS)
1283         mh->Control.len = BIO_CMSG_SPACE(sizeof(struct in6_pktinfo));
1284 #    else
1285         mh->msg_controllen = BIO_CMSG_SPACE(sizeof(struct in6_pktinfo));
1286 #    endif
1287         return 1;
1288 #   endif
1289     }
1290 #  endif
1291 
1292     return 0;
1293 }
1294 # endif
1295 
1296 /*
1297  * Converts flags passed to BIO_sendmmsg or BIO_recvmmsg to syscall flags. You
1298  * should mask out any system flags returned by this function you cannot support
1299  * in a particular circumstance. Currently no flags are defined.
1300  */
1301 # if M_METHOD != M_METHOD_NONE
translate_flags(uint64_t flags)1302 static int translate_flags(uint64_t flags) {
1303     return 0;
1304 }
1305 # endif
1306 
dgram_sendmmsg(BIO * b,BIO_MSG * msg,size_t stride,size_t num_msg,uint64_t flags,size_t * num_processed)1307 static int dgram_sendmmsg(BIO *b, BIO_MSG *msg, size_t stride,
1308                           size_t num_msg, uint64_t flags, size_t *num_processed)
1309 {
1310 # if M_METHOD != M_METHOD_NONE && M_METHOD != M_METHOD_RECVMSG
1311     int ret;
1312 # endif
1313 # if M_METHOD == M_METHOD_RECVMMSG
1314 #  define BIO_MAX_MSGS_PER_CALL   64
1315     int sysflags;
1316     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
1317     size_t i;
1318     struct mmsghdr mh[BIO_MAX_MSGS_PER_CALL];
1319     struct iovec iov[BIO_MAX_MSGS_PER_CALL];
1320     unsigned char control[BIO_MAX_MSGS_PER_CALL][BIO_CMSG_ALLOC_LEN];
1321     int have_local_enabled = data->local_addr_enabled;
1322 # elif M_METHOD == M_METHOD_RECVMSG
1323     int sysflags;
1324     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
1325     ossl_ssize_t l;
1326     struct msghdr mh;
1327     struct iovec iov;
1328     unsigned char control[BIO_CMSG_ALLOC_LEN];
1329     int have_local_enabled = data->local_addr_enabled;
1330 # elif M_METHOD == M_METHOD_WSARECVMSG
1331     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
1332     int have_local_enabled = data->local_addr_enabled;
1333     WSAMSG wmsg;
1334     WSABUF wbuf;
1335     DWORD num_bytes_sent = 0;
1336     unsigned char control[BIO_CMSG_ALLOC_LEN];
1337 # endif
1338 # if M_METHOD == M_METHOD_RECVFROM || M_METHOD == M_METHOD_WSARECVMSG
1339     int sysflags;
1340 # endif
1341 
1342     if (num_msg == 0) {
1343         *num_processed = 0;
1344         return 1;
1345     }
1346 
1347     if (num_msg > OSSL_SSIZE_MAX)
1348         num_msg = OSSL_SSIZE_MAX;
1349 
1350 # if M_METHOD != M_METHOD_NONE
1351     sysflags = translate_flags(flags);
1352 # endif
1353 
1354 # if M_METHOD == M_METHOD_RECVMMSG
1355     /*
1356      * In the sendmmsg/recvmmsg case, we need to allocate our translated struct
1357      * msghdr and struct iovec on the stack to support multithreaded use. Thus
1358      * we place a fixed limit on the number of messages per call, in the
1359      * expectation that we will be called again if there were more messages to
1360      * be sent.
1361      */
1362     if (num_msg > BIO_MAX_MSGS_PER_CALL)
1363         num_msg = BIO_MAX_MSGS_PER_CALL;
1364 
1365     for (i = 0; i < num_msg; ++i) {
1366         translate_msg(b, &mh[i].msg_hdr, &iov[i],
1367                       control[i], &BIO_MSG_N(msg, stride, i));
1368 
1369         /* If local address was requested, it must have been enabled */
1370         if (BIO_MSG_N(msg, stride, i).local != NULL) {
1371             if (!have_local_enabled) {
1372                 ERR_raise(ERR_LIB_BIO, BIO_R_LOCAL_ADDR_NOT_AVAILABLE);
1373                 *num_processed = 0;
1374                 return 0;
1375             }
1376 
1377             if (pack_local(b, &mh[i].msg_hdr,
1378                            BIO_MSG_N(msg, stride, i).local) < 1) {
1379                 ERR_raise(ERR_LIB_BIO, BIO_R_LOCAL_ADDR_NOT_AVAILABLE);
1380                 *num_processed = 0;
1381                 return 0;
1382             }
1383         }
1384     }
1385 
1386     /* Do the batch */
1387     ret = sendmmsg(b->num, mh, num_msg, sysflags);
1388     if (ret < 0) {
1389         ERR_raise(ERR_LIB_SYS, get_last_socket_error());
1390         *num_processed = 0;
1391         return 0;
1392     }
1393 
1394     for (i = 0; i < (size_t)ret; ++i) {
1395         BIO_MSG_N(msg, stride, i).data_len = mh[i].msg_len;
1396         BIO_MSG_N(msg, stride, i).flags    = 0;
1397     }
1398 
1399     *num_processed = (size_t)ret;
1400     return 1;
1401 
1402 # elif M_METHOD == M_METHOD_RECVMSG
1403     /*
1404      * If sendmsg is available, use it.
1405      */
1406     translate_msg(b, &mh, &iov, control, msg);
1407 
1408     if (msg->local != NULL) {
1409         if (!have_local_enabled) {
1410             ERR_raise(ERR_LIB_BIO, BIO_R_LOCAL_ADDR_NOT_AVAILABLE);
1411             *num_processed = 0;
1412             return 0;
1413         }
1414 
1415         if (pack_local(b, &mh, msg->local) < 1) {
1416             ERR_raise(ERR_LIB_BIO, BIO_R_LOCAL_ADDR_NOT_AVAILABLE);
1417             *num_processed = 0;
1418             return 0;
1419         }
1420     }
1421 
1422     l = sendmsg(b->num, &mh, sysflags);
1423     if (l < 0) {
1424         ERR_raise(ERR_LIB_SYS, get_last_socket_error());
1425         *num_processed = 0;
1426         return 0;
1427     }
1428 
1429     msg->data_len   = (size_t)l;
1430     msg->flags      = 0;
1431     *num_processed  = 1;
1432     return 1;
1433 
1434 # elif M_METHOD == M_METHOD_WSARECVMSG || M_METHOD == M_METHOD_RECVFROM
1435 #  if M_METHOD == M_METHOD_WSARECVMSG
1436     if (bio_WSASendMsg != NULL) {
1437         /* WSASendMsg-based implementation for Windows. */
1438         translate_msg_win(b, &wmsg, &wbuf, control, msg);
1439 
1440         if (msg[0].local != NULL) {
1441             if (!have_local_enabled) {
1442                 ERR_raise(ERR_LIB_BIO, BIO_R_LOCAL_ADDR_NOT_AVAILABLE);
1443                 *num_processed = 0;
1444                 return 0;
1445             }
1446 
1447             if (pack_local(b, &wmsg, msg[0].local) < 1) {
1448                 ERR_raise(ERR_LIB_BIO, BIO_R_LOCAL_ADDR_NOT_AVAILABLE);
1449                 *num_processed = 0;
1450                 return 0;
1451             }
1452         }
1453 
1454         ret = WSASendMsg((SOCKET)b->num, &wmsg, 0, &num_bytes_sent, NULL, NULL);
1455         if (ret < 0) {
1456             ERR_raise(ERR_LIB_SYS, get_last_socket_error());
1457             *num_processed = 0;
1458             return 0;
1459         }
1460 
1461         msg[0].data_len = num_bytes_sent;
1462         msg[0].flags    = 0;
1463         *num_processed  = 1;
1464         return 1;
1465     }
1466 #  endif
1467 
1468     /*
1469      * Fallback to sendto and send a single message.
1470      */
1471     if (msg[0].local != NULL) {
1472         /*
1473          * We cannot set the local address if using sendto
1474          * so fail in this case
1475          */
1476         ERR_raise(ERR_LIB_BIO, BIO_R_LOCAL_ADDR_NOT_AVAILABLE);
1477         *num_processed = 0;
1478         return 0;
1479     }
1480 
1481     ret = sendto(b->num, msg[0].data,
1482 #  if defined(OPENSSL_SYS_WINDOWS)
1483                  (int)msg[0].data_len,
1484 #  else
1485                  msg[0].data_len,
1486 #  endif
1487                  sysflags,
1488                  msg[0].peer != NULL ? BIO_ADDR_sockaddr(msg[0].peer) : NULL,
1489                  msg[0].peer != NULL ? BIO_ADDR_sockaddr_size(msg[0].peer) : 0);
1490     if (ret <= 0) {
1491         ERR_raise(ERR_LIB_SYS, get_last_socket_error());
1492         *num_processed = 0;
1493         return 0;
1494     }
1495 
1496     msg[0].data_len = ret;
1497     msg[0].flags    = 0;
1498     *num_processed  = 1;
1499     return 1;
1500 
1501 # else
1502     ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_METHOD);
1503     *num_processed = 0;
1504     return 0;
1505 # endif
1506 }
1507 
dgram_recvmmsg(BIO * b,BIO_MSG * msg,size_t stride,size_t num_msg,uint64_t flags,size_t * num_processed)1508 static int dgram_recvmmsg(BIO *b, BIO_MSG *msg,
1509                           size_t stride, size_t num_msg,
1510                           uint64_t flags, size_t *num_processed)
1511 {
1512 # if M_METHOD != M_METHOD_NONE && M_METHOD != M_METHOD_RECVMSG
1513     int ret;
1514 # endif
1515 # if M_METHOD == M_METHOD_RECVMMSG
1516     int sysflags;
1517     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
1518     size_t i;
1519     struct mmsghdr mh[BIO_MAX_MSGS_PER_CALL];
1520     struct iovec iov[BIO_MAX_MSGS_PER_CALL];
1521     unsigned char control[BIO_MAX_MSGS_PER_CALL][BIO_CMSG_ALLOC_LEN];
1522     int have_local_enabled = data->local_addr_enabled;
1523 # elif M_METHOD == M_METHOD_RECVMSG
1524     int sysflags;
1525     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
1526     ossl_ssize_t l;
1527     struct msghdr mh;
1528     struct iovec iov;
1529     unsigned char control[BIO_CMSG_ALLOC_LEN];
1530     int have_local_enabled = data->local_addr_enabled;
1531 # elif M_METHOD == M_METHOD_WSARECVMSG
1532     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
1533     int have_local_enabled = data->local_addr_enabled;
1534     WSAMSG wmsg;
1535     WSABUF wbuf;
1536     DWORD num_bytes_received = 0;
1537     unsigned char control[BIO_CMSG_ALLOC_LEN];
1538 # endif
1539 # if M_METHOD == M_METHOD_RECVFROM || M_METHOD == M_METHOD_WSARECVMSG
1540     int sysflags;
1541     socklen_t slen;
1542 # endif
1543 
1544     if (num_msg == 0) {
1545         *num_processed = 0;
1546         return 1;
1547     }
1548 
1549     if (num_msg > OSSL_SSIZE_MAX)
1550         num_msg = OSSL_SSIZE_MAX;
1551 
1552 # if M_METHOD != M_METHOD_NONE
1553     sysflags = translate_flags(flags);
1554 # endif
1555 
1556 # if M_METHOD == M_METHOD_RECVMMSG
1557     /*
1558      * In the sendmmsg/recvmmsg case, we need to allocate our translated struct
1559      * msghdr and struct iovec on the stack to support multithreaded use. Thus
1560      * we place a fixed limit on the number of messages per call, in the
1561      * expectation that we will be called again if there were more messages to
1562      * be sent.
1563      */
1564     if (num_msg > BIO_MAX_MSGS_PER_CALL)
1565         num_msg = BIO_MAX_MSGS_PER_CALL;
1566 
1567     for (i = 0; i < num_msg; ++i) {
1568         translate_msg(b, &mh[i].msg_hdr, &iov[i],
1569                       control[i], &BIO_MSG_N(msg, stride, i));
1570 
1571         /* If local address was requested, it must have been enabled */
1572         if (BIO_MSG_N(msg, stride, i).local != NULL && !have_local_enabled) {
1573             ERR_raise(ERR_LIB_BIO, BIO_R_LOCAL_ADDR_NOT_AVAILABLE);
1574             *num_processed = 0;
1575             return 0;
1576         }
1577     }
1578 
1579     /* Do the batch */
1580     ret = recvmmsg(b->num, mh, num_msg, sysflags, NULL);
1581     if (ret < 0) {
1582         ERR_raise(ERR_LIB_SYS, get_last_socket_error());
1583         *num_processed = 0;
1584         return 0;
1585     }
1586 
1587     for (i = 0; i < (size_t)ret; ++i) {
1588         BIO_MSG_N(msg, stride, i).data_len = mh[i].msg_len;
1589         BIO_MSG_N(msg, stride, i).flags    = 0;
1590         /*
1591          * *(msg->peer) will have been filled in by recvmmsg;
1592          * for msg->local we parse the control data returned
1593          */
1594         if (BIO_MSG_N(msg, stride, i).local != NULL)
1595             if (extract_local(b, &mh[i].msg_hdr,
1596                               BIO_MSG_N(msg, stride, i).local) < 1)
1597                 /*
1598                  * It appears BSDs do not support local addresses for
1599                  * loopback sockets. In this case, just clear the local
1600                  * address, as for OS X and Windows in some circumstances
1601                  * (see below).
1602                  */
1603                 BIO_ADDR_clear(msg->local);
1604     }
1605 
1606     *num_processed = (size_t)ret;
1607     return 1;
1608 
1609 # elif M_METHOD == M_METHOD_RECVMSG
1610     /*
1611      * If recvmsg is available, use it.
1612      */
1613     translate_msg(b, &mh, &iov, control, msg);
1614 
1615     /* If local address was requested, it must have been enabled */
1616     if (msg->local != NULL && !have_local_enabled) {
1617         /*
1618          * If we have done at least one message, we must return the
1619          * count; if we haven't done any, we can give an error code
1620          */
1621         ERR_raise(ERR_LIB_BIO, BIO_R_LOCAL_ADDR_NOT_AVAILABLE);
1622         *num_processed = 0;
1623         return 0;
1624     }
1625 
1626     l = recvmsg(b->num, &mh, sysflags);
1627     if (l < 0) {
1628         ERR_raise(ERR_LIB_SYS, get_last_socket_error());
1629         *num_processed = 0;
1630         return 0;
1631     }
1632 
1633     msg->data_len   = (size_t)l;
1634     msg->flags      = 0;
1635 
1636     if (msg->local != NULL)
1637         if (extract_local(b, &mh, msg->local) < 1)
1638             /*
1639              * OS X exhibits odd behaviour where it appears that if a packet is
1640              * sent before the receiving interface enables IP_PKTINFO, it will
1641              * sometimes not have any control data returned even if the
1642              * receiving interface enables IP_PKTINFO before calling recvmsg().
1643              * This appears to occur non-deterministically. Presumably, OS X
1644              * handles IP_PKTINFO at the time the packet is enqueued into a
1645              * socket's receive queue, rather than at the time recvmsg() is
1646              * called, unlike most other operating systems. Thus (if this
1647              * hypothesis is correct) there is a race between where IP_PKTINFO
1648              * is enabled by the process and when the kernel's network stack
1649              * queues the incoming message.
1650              *
1651              * We cannot return the local address if we do not have it, but this
1652              * is not a caller error either, so just return a zero address
1653              * structure. This is similar to how we handle Windows loopback
1654              * interfaces (see below). We enable this workaround for all
1655              * platforms, not just Apple, as this kind of quirk in OS networking
1656              * stacks seems to be common enough that failing hard if a local
1657              * address is not provided appears to be too brittle.
1658              */
1659             BIO_ADDR_clear(msg->local);
1660 
1661     *num_processed = 1;
1662     return 1;
1663 
1664 # elif M_METHOD == M_METHOD_RECVFROM || M_METHOD == M_METHOD_WSARECVMSG
1665 #  if M_METHOD == M_METHOD_WSARECVMSG
1666     if (bio_WSARecvMsg != NULL) {
1667         /* WSARecvMsg-based implementation for Windows. */
1668         translate_msg_win(b, &wmsg, &wbuf, control, msg);
1669 
1670         /* If local address was requested, it must have been enabled */
1671         if (msg[0].local != NULL && !have_local_enabled) {
1672             ERR_raise(ERR_LIB_BIO, BIO_R_LOCAL_ADDR_NOT_AVAILABLE);
1673             *num_processed = 0;
1674             return 0;
1675         }
1676 
1677         ret = WSARecvMsg((SOCKET)b->num, &wmsg, &num_bytes_received, NULL, NULL);
1678         if (ret < 0) {
1679             ERR_raise(ERR_LIB_SYS, get_last_socket_error());
1680             *num_processed = 0;
1681             return 0;
1682         }
1683 
1684         msg[0].data_len = num_bytes_received;
1685         msg[0].flags    = 0;
1686         if (msg[0].local != NULL)
1687             if (extract_local(b, &wmsg, msg[0].local) < 1)
1688                 /*
1689                  * On Windows, loopback is not a "proper" interface and it works
1690                  * differently; packets are essentially short-circuited and
1691                  * don't go through all of the normal processing. A consequence
1692                  * of this is that packets sent from the local machine to the
1693                  * local machine _will not have IP_PKTINFO_ even if the
1694                  * IP_PKTINFO socket option is enabled. WSARecvMsg just sets
1695                  * Control.len to 0 on returning.
1696                  *
1697                  * This applies regardless of whether the loopback address,
1698                  * 127.0.0.1 is used, or a local interface address (e.g.
1699                  * 192.168.1.1); in both cases IP_PKTINFO will not be present.
1700                  *
1701                  * We report this condition by setting the local BIO_ADDR's
1702                  * family to 0.
1703                  */
1704                 BIO_ADDR_clear(msg[0].local);
1705 
1706         *num_processed = 1;
1707         return 1;
1708     }
1709 #  endif
1710 
1711     /*
1712      * Fallback to recvfrom and receive a single message.
1713      */
1714     if (msg[0].local != NULL) {
1715         /*
1716          * We cannot determine the local address if using recvfrom
1717          * so fail in this case
1718          */
1719         ERR_raise(ERR_LIB_BIO, BIO_R_LOCAL_ADDR_NOT_AVAILABLE);
1720         *num_processed = 0;
1721         return 0;
1722     }
1723 
1724     slen = sizeof(*msg[0].peer);
1725     ret = recvfrom(b->num, msg[0].data,
1726 #  if defined(OPENSSL_SYS_WINDOWS)
1727                    (int)msg[0].data_len,
1728 #  else
1729                    msg[0].data_len,
1730 #  endif
1731                    sysflags,
1732                    msg[0].peer != NULL ? &msg[0].peer->sa : NULL,
1733                    msg[0].peer != NULL ? &slen : NULL);
1734     if (ret <= 0) {
1735         ERR_raise(ERR_LIB_SYS, get_last_socket_error());
1736         return 0;
1737     }
1738 
1739     msg[0].data_len = ret;
1740     msg[0].flags    = 0;
1741     *num_processed = 1;
1742     return 1;
1743 
1744 # else
1745     ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_METHOD);
1746     *num_processed = 0;
1747     return 0;
1748 # endif
1749 }
1750 
1751 # ifndef OPENSSL_NO_SCTP
BIO_s_datagram_sctp(void)1752 const BIO_METHOD *BIO_s_datagram_sctp(void)
1753 {
1754     return &methods_dgramp_sctp;
1755 }
1756 
BIO_new_dgram_sctp(int fd,int close_flag)1757 BIO *BIO_new_dgram_sctp(int fd, int close_flag)
1758 {
1759     BIO *bio;
1760     int ret, optval = 20000;
1761     int auth_data = 0, auth_forward = 0;
1762     unsigned char *p;
1763     struct sctp_authchunk auth;
1764     struct sctp_authchunks *authchunks;
1765     socklen_t sockopt_len;
1766 #  ifdef SCTP_AUTHENTICATION_EVENT
1767 #   ifdef SCTP_EVENT
1768     struct sctp_event event;
1769 #   else
1770     struct sctp_event_subscribe event;
1771 #   endif
1772 #  endif
1773 
1774     bio = BIO_new(BIO_s_datagram_sctp());
1775     if (bio == NULL)
1776         return NULL;
1777     BIO_set_fd(bio, fd, close_flag);
1778 
1779     /* Activate SCTP-AUTH for DATA and FORWARD-TSN chunks */
1780     auth.sauth_chunk = OPENSSL_SCTP_DATA_CHUNK_TYPE;
1781     ret =
1782         setsockopt(fd, IPPROTO_SCTP, SCTP_AUTH_CHUNK, &auth,
1783                    sizeof(struct sctp_authchunk));
1784     if (ret < 0) {
1785         BIO_vfree(bio);
1786         ERR_raise_data(ERR_LIB_BIO, ERR_R_SYS_LIB,
1787                        "Ensure SCTP AUTH chunks are enabled in kernel");
1788         return NULL;
1789     }
1790     auth.sauth_chunk = OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE;
1791     ret =
1792         setsockopt(fd, IPPROTO_SCTP, SCTP_AUTH_CHUNK, &auth,
1793                    sizeof(struct sctp_authchunk));
1794     if (ret < 0) {
1795         BIO_vfree(bio);
1796         ERR_raise_data(ERR_LIB_BIO, ERR_R_SYS_LIB,
1797                        "Ensure SCTP AUTH chunks are enabled in kernel");
1798         return NULL;
1799     }
1800 
1801     /*
1802      * Test if activation was successful. When using accept(), SCTP-AUTH has
1803      * to be activated for the listening socket already, otherwise the
1804      * connected socket won't use it. Similarly with connect(): the socket
1805      * prior to connection must be activated for SCTP-AUTH
1806      */
1807     sockopt_len = (socklen_t) (sizeof(sctp_assoc_t) + 256 * sizeof(uint8_t));
1808     authchunks = OPENSSL_zalloc(sockopt_len);
1809     if (authchunks == NULL) {
1810         BIO_vfree(bio);
1811         return NULL;
1812     }
1813     ret = getsockopt(fd, IPPROTO_SCTP, SCTP_LOCAL_AUTH_CHUNKS, authchunks,
1814                    &sockopt_len);
1815     if (ret < 0) {
1816         OPENSSL_free(authchunks);
1817         BIO_vfree(bio);
1818         return NULL;
1819     }
1820 
1821     for (p = (unsigned char *)authchunks->gauth_chunks;
1822          p < (unsigned char *)authchunks + sockopt_len;
1823          p += sizeof(uint8_t)) {
1824         if (*p == OPENSSL_SCTP_DATA_CHUNK_TYPE)
1825             auth_data = 1;
1826         if (*p == OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE)
1827             auth_forward = 1;
1828     }
1829 
1830     OPENSSL_free(authchunks);
1831 
1832     if (!auth_data || !auth_forward) {
1833         BIO_vfree(bio);
1834         ERR_raise_data(ERR_LIB_BIO, ERR_R_SYS_LIB,
1835                        "Ensure SCTP AUTH chunks are enabled on the "
1836                        "underlying socket");
1837         return NULL;
1838     }
1839 
1840 #  ifdef SCTP_AUTHENTICATION_EVENT
1841 #   ifdef SCTP_EVENT
1842     memset(&event, 0, sizeof(event));
1843     event.se_assoc_id = 0;
1844     event.se_type = SCTP_AUTHENTICATION_EVENT;
1845     event.se_on = 1;
1846     ret =
1847         setsockopt(fd, IPPROTO_SCTP, SCTP_EVENT, &event,
1848                    sizeof(struct sctp_event));
1849     if (ret < 0) {
1850         BIO_vfree(bio);
1851         return NULL;
1852     }
1853 #   else
1854     sockopt_len = (socklen_t) sizeof(struct sctp_event_subscribe);
1855     ret = getsockopt(fd, IPPROTO_SCTP, SCTP_EVENTS, &event, &sockopt_len);
1856     if (ret < 0) {
1857         BIO_vfree(bio);
1858         return NULL;
1859     }
1860 
1861     event.sctp_authentication_event = 1;
1862 
1863     ret =
1864         setsockopt(fd, IPPROTO_SCTP, SCTP_EVENTS, &event,
1865                    sizeof(struct sctp_event_subscribe));
1866     if (ret < 0) {
1867         BIO_vfree(bio);
1868         return NULL;
1869     }
1870 #   endif
1871 #  endif
1872 
1873     /*
1874      * Disable partial delivery by setting the min size larger than the max
1875      * record size of 2^14 + 2048 + 13
1876      */
1877     ret =
1878         setsockopt(fd, IPPROTO_SCTP, SCTP_PARTIAL_DELIVERY_POINT, &optval,
1879                    sizeof(optval));
1880     if (ret < 0) {
1881         BIO_vfree(bio);
1882         return NULL;
1883     }
1884 
1885     return bio;
1886 }
1887 
BIO_dgram_is_sctp(BIO * bio)1888 int BIO_dgram_is_sctp(BIO *bio)
1889 {
1890     return (BIO_method_type(bio) == BIO_TYPE_DGRAM_SCTP);
1891 }
1892 
dgram_sctp_new(BIO * bi)1893 static int dgram_sctp_new(BIO *bi)
1894 {
1895     bio_dgram_sctp_data *data = NULL;
1896 
1897     bi->init = 0;
1898     bi->num = 0;
1899     if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL)
1900         return 0;
1901 #  ifdef SCTP_PR_SCTP_NONE
1902     data->prinfo.pr_policy = SCTP_PR_SCTP_NONE;
1903 #  endif
1904     bi->ptr = data;
1905 
1906     bi->flags = 0;
1907     return 1;
1908 }
1909 
dgram_sctp_free(BIO * a)1910 static int dgram_sctp_free(BIO *a)
1911 {
1912     bio_dgram_sctp_data *data;
1913 
1914     if (a == NULL)
1915         return 0;
1916     if (!dgram_clear(a))
1917         return 0;
1918 
1919     data = (bio_dgram_sctp_data *) a->ptr;
1920     if (data != NULL)
1921         OPENSSL_free(data);
1922 
1923     return 1;
1924 }
1925 
1926 #  ifdef SCTP_AUTHENTICATION_EVENT
dgram_sctp_handle_auth_free_key_event(BIO * b,union sctp_notification * snp)1927 void dgram_sctp_handle_auth_free_key_event(BIO *b,
1928                                            union sctp_notification *snp)
1929 {
1930     int ret;
1931     struct sctp_authkey_event *authkeyevent = &snp->sn_auth_event;
1932 
1933     if (authkeyevent->auth_indication == SCTP_AUTH_FREE_KEY) {
1934         struct sctp_authkeyid authkeyid;
1935 
1936         /* delete key */
1937         authkeyid.scact_keynumber = authkeyevent->auth_keynumber;
1938         ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DELETE_KEY,
1939                          &authkeyid, sizeof(struct sctp_authkeyid));
1940     }
1941 }
1942 #  endif
1943 
dgram_sctp_read(BIO * b,char * out,int outl)1944 static int dgram_sctp_read(BIO *b, char *out, int outl)
1945 {
1946     int ret = 0, n = 0, i, optval;
1947     socklen_t optlen;
1948     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
1949     struct msghdr msg;
1950     struct iovec iov;
1951     struct cmsghdr *cmsg;
1952     char cmsgbuf[512];
1953 
1954     if (out != NULL) {
1955         clear_socket_error();
1956 
1957         do {
1958             memset(&data->rcvinfo, 0, sizeof(data->rcvinfo));
1959             iov.iov_base = out;
1960             iov.iov_len = outl;
1961             msg.msg_name = NULL;
1962             msg.msg_namelen = 0;
1963             msg.msg_iov = &iov;
1964             msg.msg_iovlen = 1;
1965             msg.msg_control = cmsgbuf;
1966             msg.msg_controllen = 512;
1967             msg.msg_flags = 0;
1968             n = recvmsg(b->num, &msg, 0);
1969 
1970             if (n <= 0) {
1971                 if (n < 0)
1972                     ret = n;
1973                 break;
1974             }
1975 
1976             if (msg.msg_controllen > 0) {
1977                 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg;
1978                      cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1979                     if (cmsg->cmsg_level != IPPROTO_SCTP)
1980                         continue;
1981 #  ifdef SCTP_RCVINFO
1982                     if (cmsg->cmsg_type == SCTP_RCVINFO) {
1983                         struct sctp_rcvinfo *rcvinfo;
1984 
1985                         rcvinfo = (struct sctp_rcvinfo *)CMSG_DATA(cmsg);
1986                         data->rcvinfo.rcv_sid = rcvinfo->rcv_sid;
1987                         data->rcvinfo.rcv_ssn = rcvinfo->rcv_ssn;
1988                         data->rcvinfo.rcv_flags = rcvinfo->rcv_flags;
1989                         data->rcvinfo.rcv_ppid = rcvinfo->rcv_ppid;
1990                         data->rcvinfo.rcv_tsn = rcvinfo->rcv_tsn;
1991                         data->rcvinfo.rcv_cumtsn = rcvinfo->rcv_cumtsn;
1992                         data->rcvinfo.rcv_context = rcvinfo->rcv_context;
1993                     }
1994 #  endif
1995 #  ifdef SCTP_SNDRCV
1996                     if (cmsg->cmsg_type == SCTP_SNDRCV) {
1997                         struct sctp_sndrcvinfo *sndrcvinfo;
1998 
1999                         sndrcvinfo =
2000                             (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
2001                         data->rcvinfo.rcv_sid = sndrcvinfo->sinfo_stream;
2002                         data->rcvinfo.rcv_ssn = sndrcvinfo->sinfo_ssn;
2003                         data->rcvinfo.rcv_flags = sndrcvinfo->sinfo_flags;
2004                         data->rcvinfo.rcv_ppid = sndrcvinfo->sinfo_ppid;
2005                         data->rcvinfo.rcv_tsn = sndrcvinfo->sinfo_tsn;
2006                         data->rcvinfo.rcv_cumtsn = sndrcvinfo->sinfo_cumtsn;
2007                         data->rcvinfo.rcv_context = sndrcvinfo->sinfo_context;
2008                     }
2009 #  endif
2010                 }
2011             }
2012 
2013             if (msg.msg_flags & MSG_NOTIFICATION) {
2014                 union sctp_notification snp;
2015 
2016                 memcpy(&snp, out, sizeof(snp));
2017                 if (snp.sn_header.sn_type == SCTP_SENDER_DRY_EVENT) {
2018 #  ifdef SCTP_EVENT
2019                     struct sctp_event event;
2020 #  else
2021                     struct sctp_event_subscribe event;
2022                     socklen_t eventsize;
2023 #  endif
2024 
2025                     /* disable sender dry event */
2026 #  ifdef SCTP_EVENT
2027                     memset(&event, 0, sizeof(event));
2028                     event.se_assoc_id = 0;
2029                     event.se_type = SCTP_SENDER_DRY_EVENT;
2030                     event.se_on = 0;
2031                     i = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event,
2032                                    sizeof(struct sctp_event));
2033                     if (i < 0) {
2034                         ret = i;
2035                         break;
2036                     }
2037 #  else
2038                     eventsize = sizeof(struct sctp_event_subscribe);
2039                     i = getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
2040                                    &eventsize);
2041                     if (i < 0) {
2042                         ret = i;
2043                         break;
2044                     }
2045 
2046                     event.sctp_sender_dry_event = 0;
2047 
2048                     i = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
2049                                    sizeof(struct sctp_event_subscribe));
2050                     if (i < 0) {
2051                         ret = i;
2052                         break;
2053                     }
2054 #  endif
2055                 }
2056 #  ifdef SCTP_AUTHENTICATION_EVENT
2057                 if (snp.sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
2058                     dgram_sctp_handle_auth_free_key_event(b, &snp);
2059 #  endif
2060 
2061                 if (data->handle_notifications != NULL)
2062                     data->handle_notifications(b, data->notification_context,
2063                                                (void *)out);
2064 
2065                 memset(&snp, 0, sizeof(snp));
2066                 memset(out, 0, outl);
2067             } else {
2068                 ret += n;
2069             }
2070         }
2071         while ((msg.msg_flags & MSG_NOTIFICATION) && (msg.msg_flags & MSG_EOR)
2072                && (ret < outl));
2073 
2074         if (ret > 0 && !(msg.msg_flags & MSG_EOR)) {
2075             /* Partial message read, this should never happen! */
2076 
2077             /*
2078              * The buffer was too small, this means the peer sent a message
2079              * that was larger than allowed.
2080              */
2081             if (ret == outl)
2082                 return -1;
2083 
2084             /*
2085              * Test if socket buffer can handle max record size (2^14 + 2048
2086              * + 13)
2087              */
2088             optlen = (socklen_t) sizeof(int);
2089             ret = getsockopt(b->num, SOL_SOCKET, SO_RCVBUF, &optval, &optlen);
2090             if (ret >= 0)
2091                 OPENSSL_assert(optval >= 18445);
2092 
2093             /*
2094              * Test if SCTP doesn't partially deliver below max record size
2095              * (2^14 + 2048 + 13)
2096              */
2097             optlen = (socklen_t) sizeof(int);
2098             ret =
2099                 getsockopt(b->num, IPPROTO_SCTP, SCTP_PARTIAL_DELIVERY_POINT,
2100                            &optval, &optlen);
2101             if (ret >= 0)
2102                 OPENSSL_assert(optval >= 18445);
2103 
2104             /*
2105              * Partially delivered notification??? Probably a bug....
2106              */
2107             OPENSSL_assert(!(msg.msg_flags & MSG_NOTIFICATION));
2108 
2109             /*
2110              * Everything seems ok till now, so it's most likely a message
2111              * dropped by PR-SCTP.
2112              */
2113             memset(out, 0, outl);
2114             BIO_set_retry_read(b);
2115             return -1;
2116         }
2117 
2118         BIO_clear_retry_flags(b);
2119         if (ret < 0) {
2120             if (BIO_dgram_should_retry(ret)) {
2121                 BIO_set_retry_read(b);
2122                 data->dgram._errno = get_last_socket_error();
2123             }
2124         }
2125 
2126         /* Test if peer uses SCTP-AUTH before continuing */
2127         if (!data->peer_auth_tested) {
2128             int ii, auth_data = 0, auth_forward = 0;
2129             unsigned char *p;
2130             struct sctp_authchunks *authchunks;
2131 
2132             optlen =
2133                 (socklen_t) (sizeof(sctp_assoc_t) + 256 * sizeof(uint8_t));
2134             authchunks = OPENSSL_malloc(optlen);
2135             if (authchunks == NULL)
2136                 return -1;
2137             memset(authchunks, 0, optlen);
2138             ii = getsockopt(b->num, IPPROTO_SCTP, SCTP_PEER_AUTH_CHUNKS,
2139                             authchunks, &optlen);
2140 
2141             if (ii >= 0)
2142                 for (p = (unsigned char *)authchunks->gauth_chunks;
2143                      p < (unsigned char *)authchunks + optlen;
2144                      p += sizeof(uint8_t)) {
2145                     if (*p == OPENSSL_SCTP_DATA_CHUNK_TYPE)
2146                         auth_data = 1;
2147                     if (*p == OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE)
2148                         auth_forward = 1;
2149                 }
2150 
2151             OPENSSL_free(authchunks);
2152 
2153             if (!auth_data || !auth_forward) {
2154                 ERR_raise(ERR_LIB_BIO, BIO_R_CONNECT_ERROR);
2155                 return -1;
2156             }
2157 
2158             data->peer_auth_tested = 1;
2159         }
2160     }
2161     return ret;
2162 }
2163 
2164 /*
2165  * dgram_sctp_write - send message on SCTP socket
2166  * @b: BIO to write to
2167  * @in: data to send
2168  * @inl: amount of bytes in @in to send
2169  *
2170  * Returns -1 on error or the sent amount of bytes on success
2171  */
dgram_sctp_write(BIO * b,const char * in,int inl)2172 static int dgram_sctp_write(BIO *b, const char *in, int inl)
2173 {
2174     int ret;
2175     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
2176     struct bio_dgram_sctp_sndinfo *sinfo = &(data->sndinfo);
2177     struct bio_dgram_sctp_prinfo *pinfo = &(data->prinfo);
2178     struct bio_dgram_sctp_sndinfo handshake_sinfo;
2179     struct iovec iov[1];
2180     struct msghdr msg;
2181     struct cmsghdr *cmsg;
2182 #  if defined(SCTP_SNDINFO) && defined(SCTP_PRINFO)
2183     char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndinfo)) +
2184                  CMSG_SPACE(sizeof(struct sctp_prinfo))];
2185     struct sctp_sndinfo *sndinfo;
2186     struct sctp_prinfo *prinfo;
2187 #  else
2188     char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndrcvinfo))];
2189     struct sctp_sndrcvinfo *sndrcvinfo;
2190 #  endif
2191 
2192     clear_socket_error();
2193 
2194     /*
2195      * If we're send anything else than application data, disable all user
2196      * parameters and flags.
2197      */
2198     if (in[0] != 23) {
2199         memset(&handshake_sinfo, 0, sizeof(handshake_sinfo));
2200 #  ifdef SCTP_SACK_IMMEDIATELY
2201         handshake_sinfo.snd_flags = SCTP_SACK_IMMEDIATELY;
2202 #  endif
2203         sinfo = &handshake_sinfo;
2204     }
2205 
2206     /* We can only send a shutdown alert if the socket is dry */
2207     if (data->save_shutdown) {
2208         ret = BIO_dgram_sctp_wait_for_dry(b);
2209         if (ret < 0)
2210             return -1;
2211         if (ret == 0) {
2212             BIO_clear_retry_flags(b);
2213             BIO_set_retry_write(b);
2214             return -1;
2215         }
2216     }
2217 
2218     iov[0].iov_base = (char *)in;
2219     iov[0].iov_len = inl;
2220     msg.msg_name = NULL;
2221     msg.msg_namelen = 0;
2222     msg.msg_iov = iov;
2223     msg.msg_iovlen = 1;
2224     msg.msg_control = (caddr_t) cmsgbuf;
2225     msg.msg_controllen = 0;
2226     msg.msg_flags = 0;
2227 #  if defined(SCTP_SNDINFO) && defined(SCTP_PRINFO)
2228     cmsg = (struct cmsghdr *)cmsgbuf;
2229     cmsg->cmsg_level = IPPROTO_SCTP;
2230     cmsg->cmsg_type = SCTP_SNDINFO;
2231     cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndinfo));
2232     sndinfo = (struct sctp_sndinfo *)CMSG_DATA(cmsg);
2233     memset(sndinfo, 0, sizeof(*sndinfo));
2234     sndinfo->snd_sid = sinfo->snd_sid;
2235     sndinfo->snd_flags = sinfo->snd_flags;
2236     sndinfo->snd_ppid = sinfo->snd_ppid;
2237     sndinfo->snd_context = sinfo->snd_context;
2238     msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_sndinfo));
2239 
2240     cmsg =
2241         (struct cmsghdr *)&cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndinfo))];
2242     cmsg->cmsg_level = IPPROTO_SCTP;
2243     cmsg->cmsg_type = SCTP_PRINFO;
2244     cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_prinfo));
2245     prinfo = (struct sctp_prinfo *)CMSG_DATA(cmsg);
2246     memset(prinfo, 0, sizeof(*prinfo));
2247     prinfo->pr_policy = pinfo->pr_policy;
2248     prinfo->pr_value = pinfo->pr_value;
2249     msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_prinfo));
2250 #  else
2251     cmsg = (struct cmsghdr *)cmsgbuf;
2252     cmsg->cmsg_level = IPPROTO_SCTP;
2253     cmsg->cmsg_type = SCTP_SNDRCV;
2254     cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
2255     sndrcvinfo = (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
2256     memset(sndrcvinfo, 0, sizeof(*sndrcvinfo));
2257     sndrcvinfo->sinfo_stream = sinfo->snd_sid;
2258     sndrcvinfo->sinfo_flags = sinfo->snd_flags;
2259 #   ifdef __FreeBSD__
2260     sndrcvinfo->sinfo_flags |= pinfo->pr_policy;
2261 #   endif
2262     sndrcvinfo->sinfo_ppid = sinfo->snd_ppid;
2263     sndrcvinfo->sinfo_context = sinfo->snd_context;
2264     sndrcvinfo->sinfo_timetolive = pinfo->pr_value;
2265     msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_sndrcvinfo));
2266 #  endif
2267 
2268     ret = sendmsg(b->num, &msg, 0);
2269 
2270     BIO_clear_retry_flags(b);
2271     if (ret <= 0) {
2272         if (BIO_dgram_should_retry(ret)) {
2273             BIO_set_retry_write(b);
2274             data->dgram._errno = get_last_socket_error();
2275         }
2276     }
2277     return ret;
2278 }
2279 
dgram_sctp_ctrl(BIO * b,int cmd,long num,void * ptr)2280 static long dgram_sctp_ctrl(BIO *b, int cmd, long num, void *ptr)
2281 {
2282     long ret = 1;
2283     bio_dgram_sctp_data *data = NULL;
2284     socklen_t sockopt_len = 0;
2285     struct sctp_authkeyid authkeyid;
2286     struct sctp_authkey *authkey = NULL;
2287 
2288     data = (bio_dgram_sctp_data *) b->ptr;
2289 
2290     switch (cmd) {
2291     case BIO_CTRL_DGRAM_QUERY_MTU:
2292         /*
2293          * Set to maximum (2^14) and ignore user input to enable transport
2294          * protocol fragmentation. Returns always 2^14.
2295          */
2296         data->dgram.mtu = 16384;
2297         ret = data->dgram.mtu;
2298         break;
2299     case BIO_CTRL_DGRAM_SET_MTU:
2300         /*
2301          * Set to maximum (2^14) and ignore input to enable transport
2302          * protocol fragmentation. Returns always 2^14.
2303          */
2304         data->dgram.mtu = 16384;
2305         ret = data->dgram.mtu;
2306         break;
2307     case BIO_CTRL_DGRAM_SET_CONNECTED:
2308     case BIO_CTRL_DGRAM_CONNECT:
2309         /* Returns always -1. */
2310         ret = -1;
2311         break;
2312     case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
2313         /*
2314          * SCTP doesn't need the DTLS timer Returns always 1.
2315          */
2316         break;
2317     case BIO_CTRL_DGRAM_GET_MTU_OVERHEAD:
2318         /*
2319          * We allow transport protocol fragmentation so this is irrelevant
2320          */
2321         ret = 0;
2322         break;
2323     case BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE:
2324         if (num > 0)
2325             data->in_handshake = 1;
2326         else
2327             data->in_handshake = 0;
2328 
2329         ret =
2330             setsockopt(b->num, IPPROTO_SCTP, SCTP_NODELAY,
2331                        &data->in_handshake, sizeof(int));
2332         break;
2333     case BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY:
2334         /*
2335          * New shared key for SCTP AUTH. Returns 0 on success, -1 otherwise.
2336          */
2337 
2338         /* Get active key */
2339         sockopt_len = sizeof(struct sctp_authkeyid);
2340         ret =
2341             getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY, &authkeyid,
2342                        &sockopt_len);
2343         if (ret < 0)
2344             break;
2345 
2346         /* Add new key */
2347         sockopt_len = sizeof(struct sctp_authkey) + 64 * sizeof(uint8_t);
2348         authkey = OPENSSL_malloc(sockopt_len);
2349         if (authkey == NULL) {
2350             ret = -1;
2351             break;
2352         }
2353         memset(authkey, 0, sockopt_len);
2354         authkey->sca_keynumber = authkeyid.scact_keynumber + 1;
2355 #  ifndef __FreeBSD__
2356         /*
2357          * This field is missing in FreeBSD 8.2 and earlier, and FreeBSD 8.3
2358          * and higher work without it.
2359          */
2360         authkey->sca_keylength = 64;
2361 #  endif
2362         memcpy(&authkey->sca_key[0], ptr, 64 * sizeof(uint8_t));
2363 
2364         ret =
2365             setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_KEY, authkey,
2366                        sockopt_len);
2367         OPENSSL_free(authkey);
2368         authkey = NULL;
2369         if (ret < 0)
2370             break;
2371 
2372         /* Reset active key */
2373         ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY,
2374                          &authkeyid, sizeof(struct sctp_authkeyid));
2375         if (ret < 0)
2376             break;
2377 
2378         break;
2379     case BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY:
2380         /* Returns 0 on success, -1 otherwise. */
2381 
2382         /* Get active key */
2383         sockopt_len = sizeof(struct sctp_authkeyid);
2384         ret =
2385             getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY, &authkeyid,
2386                        &sockopt_len);
2387         if (ret < 0)
2388             break;
2389 
2390         /* Set active key */
2391         authkeyid.scact_keynumber = authkeyid.scact_keynumber + 1;
2392         ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY,
2393                          &authkeyid, sizeof(struct sctp_authkeyid));
2394         if (ret < 0)
2395             break;
2396 
2397         /*
2398          * CCS has been sent, so remember that and fall through to check if
2399          * we need to deactivate an old key
2400          */
2401         data->ccs_sent = 1;
2402         /* fall-through */
2403 
2404     case BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD:
2405         /* Returns 0 on success, -1 otherwise. */
2406 
2407         /*
2408          * Has this command really been called or is this just a
2409          * fall-through?
2410          */
2411         if (cmd == BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD)
2412             data->ccs_rcvd = 1;
2413 
2414         /*
2415          * CSS has been both, received and sent, so deactivate an old key
2416          */
2417         if (data->ccs_rcvd == 1 && data->ccs_sent == 1) {
2418             /* Get active key */
2419             sockopt_len = sizeof(struct sctp_authkeyid);
2420             ret =
2421                 getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY,
2422                            &authkeyid, &sockopt_len);
2423             if (ret < 0)
2424                 break;
2425 
2426             /*
2427              * Deactivate key or delete second last key if
2428              * SCTP_AUTHENTICATION_EVENT is not available.
2429              */
2430             authkeyid.scact_keynumber = authkeyid.scact_keynumber - 1;
2431 #  ifdef SCTP_AUTH_DEACTIVATE_KEY
2432             sockopt_len = sizeof(struct sctp_authkeyid);
2433             ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DEACTIVATE_KEY,
2434                              &authkeyid, sockopt_len);
2435             if (ret < 0)
2436                 break;
2437 #  endif
2438 #  ifndef SCTP_AUTHENTICATION_EVENT
2439             if (authkeyid.scact_keynumber > 0) {
2440                 authkeyid.scact_keynumber = authkeyid.scact_keynumber - 1;
2441                 ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DELETE_KEY,
2442                                  &authkeyid, sizeof(struct sctp_authkeyid));
2443                 if (ret < 0)
2444                     break;
2445             }
2446 #  endif
2447 
2448             data->ccs_rcvd = 0;
2449             data->ccs_sent = 0;
2450         }
2451         break;
2452     case BIO_CTRL_DGRAM_SCTP_GET_SNDINFO:
2453         /* Returns the size of the copied struct. */
2454         if (num > (long)sizeof(struct bio_dgram_sctp_sndinfo))
2455             num = sizeof(struct bio_dgram_sctp_sndinfo);
2456 
2457         memcpy(ptr, &(data->sndinfo), num);
2458         ret = num;
2459         break;
2460     case BIO_CTRL_DGRAM_SCTP_SET_SNDINFO:
2461         /* Returns the size of the copied struct. */
2462         if (num > (long)sizeof(struct bio_dgram_sctp_sndinfo))
2463             num = sizeof(struct bio_dgram_sctp_sndinfo);
2464 
2465         memcpy(&(data->sndinfo), ptr, num);
2466         break;
2467     case BIO_CTRL_DGRAM_SCTP_GET_RCVINFO:
2468         /* Returns the size of the copied struct. */
2469         if (num > (long)sizeof(struct bio_dgram_sctp_rcvinfo))
2470             num = sizeof(struct bio_dgram_sctp_rcvinfo);
2471 
2472         memcpy(ptr, &data->rcvinfo, num);
2473 
2474         ret = num;
2475         break;
2476     case BIO_CTRL_DGRAM_SCTP_SET_RCVINFO:
2477         /* Returns the size of the copied struct. */
2478         if (num > (long)sizeof(struct bio_dgram_sctp_rcvinfo))
2479             num = sizeof(struct bio_dgram_sctp_rcvinfo);
2480 
2481         memcpy(&(data->rcvinfo), ptr, num);
2482         break;
2483     case BIO_CTRL_DGRAM_SCTP_GET_PRINFO:
2484         /* Returns the size of the copied struct. */
2485         if (num > (long)sizeof(struct bio_dgram_sctp_prinfo))
2486             num = sizeof(struct bio_dgram_sctp_prinfo);
2487 
2488         memcpy(ptr, &(data->prinfo), num);
2489         ret = num;
2490         break;
2491     case BIO_CTRL_DGRAM_SCTP_SET_PRINFO:
2492         /* Returns the size of the copied struct. */
2493         if (num > (long)sizeof(struct bio_dgram_sctp_prinfo))
2494             num = sizeof(struct bio_dgram_sctp_prinfo);
2495 
2496         memcpy(&(data->prinfo), ptr, num);
2497         break;
2498     case BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN:
2499         /* Returns always 1. */
2500         if (num > 0)
2501             data->save_shutdown = 1;
2502         else
2503             data->save_shutdown = 0;
2504         break;
2505     case BIO_CTRL_DGRAM_SCTP_WAIT_FOR_DRY:
2506         return dgram_sctp_wait_for_dry(b);
2507     case BIO_CTRL_DGRAM_SCTP_MSG_WAITING:
2508         return dgram_sctp_msg_waiting(b);
2509 
2510     default:
2511         /*
2512          * Pass to default ctrl function to process SCTP unspecific commands
2513          */
2514         ret = dgram_ctrl(b, cmd, num, ptr);
2515         break;
2516     }
2517     return ret;
2518 }
2519 
BIO_dgram_sctp_notification_cb(BIO * b,BIO_dgram_sctp_notification_handler_fn handle_notifications,void * context)2520 int BIO_dgram_sctp_notification_cb(BIO *b,
2521                 BIO_dgram_sctp_notification_handler_fn handle_notifications,
2522                 void *context)
2523 {
2524     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
2525 
2526     if (handle_notifications != NULL) {
2527         data->handle_notifications = handle_notifications;
2528         data->notification_context = context;
2529     } else
2530         return -1;
2531 
2532     return 0;
2533 }
2534 
2535 /*
2536  * BIO_dgram_sctp_wait_for_dry - Wait for SCTP SENDER_DRY event
2537  * @b: The BIO to check for the dry event
2538  *
2539  * Wait until the peer confirms all packets have been received, and so that
2540  * our kernel doesn't have anything to send anymore.  This is only received by
2541  * the peer's kernel, not the application.
2542  *
2543  * Returns:
2544  * -1 on error
2545  *  0 when not dry yet
2546  *  1 when dry
2547  */
BIO_dgram_sctp_wait_for_dry(BIO * b)2548 int BIO_dgram_sctp_wait_for_dry(BIO *b)
2549 {
2550     return (int)BIO_ctrl(b, BIO_CTRL_DGRAM_SCTP_WAIT_FOR_DRY, 0, NULL);
2551 }
2552 
dgram_sctp_wait_for_dry(BIO * b)2553 static int dgram_sctp_wait_for_dry(BIO *b)
2554 {
2555     int is_dry = 0;
2556     int sockflags = 0;
2557     int n, ret;
2558     union sctp_notification snp;
2559     struct msghdr msg;
2560     struct iovec iov;
2561 #  ifdef SCTP_EVENT
2562     struct sctp_event event;
2563 #  else
2564     struct sctp_event_subscribe event;
2565     socklen_t eventsize;
2566 #  endif
2567     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
2568 
2569     /* set sender dry event */
2570 #  ifdef SCTP_EVENT
2571     memset(&event, 0, sizeof(event));
2572     event.se_assoc_id = 0;
2573     event.se_type = SCTP_SENDER_DRY_EVENT;
2574     event.se_on = 1;
2575     ret =
2576         setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event,
2577                    sizeof(struct sctp_event));
2578 #  else
2579     eventsize = sizeof(struct sctp_event_subscribe);
2580     ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, &eventsize);
2581     if (ret < 0)
2582         return -1;
2583 
2584     event.sctp_sender_dry_event = 1;
2585 
2586     ret =
2587         setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
2588                    sizeof(struct sctp_event_subscribe));
2589 #  endif
2590     if (ret < 0)
2591         return -1;
2592 
2593     /* peek for notification */
2594     memset(&snp, 0, sizeof(snp));
2595     iov.iov_base = (char *)&snp;
2596     iov.iov_len = sizeof(union sctp_notification);
2597     msg.msg_name = NULL;
2598     msg.msg_namelen = 0;
2599     msg.msg_iov = &iov;
2600     msg.msg_iovlen = 1;
2601     msg.msg_control = NULL;
2602     msg.msg_controllen = 0;
2603     msg.msg_flags = 0;
2604 
2605     n = recvmsg(b->num, &msg, MSG_PEEK);
2606     if (n <= 0) {
2607         if ((n < 0) && (get_last_socket_error() != EAGAIN)
2608             && (get_last_socket_error() != EWOULDBLOCK))
2609             return -1;
2610         else
2611             return 0;
2612     }
2613 
2614     /* if we find a notification, process it and try again if necessary */
2615     while (msg.msg_flags & MSG_NOTIFICATION) {
2616         memset(&snp, 0, sizeof(snp));
2617         iov.iov_base = (char *)&snp;
2618         iov.iov_len = sizeof(union sctp_notification);
2619         msg.msg_name = NULL;
2620         msg.msg_namelen = 0;
2621         msg.msg_iov = &iov;
2622         msg.msg_iovlen = 1;
2623         msg.msg_control = NULL;
2624         msg.msg_controllen = 0;
2625         msg.msg_flags = 0;
2626 
2627         n = recvmsg(b->num, &msg, 0);
2628         if (n <= 0) {
2629             if ((n < 0) && (get_last_socket_error() != EAGAIN)
2630                 && (get_last_socket_error() != EWOULDBLOCK))
2631                 return -1;
2632             else
2633                 return is_dry;
2634         }
2635 
2636         if (snp.sn_header.sn_type == SCTP_SENDER_DRY_EVENT) {
2637             is_dry = 1;
2638 
2639             /* disable sender dry event */
2640 #  ifdef SCTP_EVENT
2641             memset(&event, 0, sizeof(event));
2642             event.se_assoc_id = 0;
2643             event.se_type = SCTP_SENDER_DRY_EVENT;
2644             event.se_on = 0;
2645             ret =
2646                 setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event,
2647                            sizeof(struct sctp_event));
2648 #  else
2649             eventsize = (socklen_t) sizeof(struct sctp_event_subscribe);
2650             ret =
2651                 getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
2652                            &eventsize);
2653             if (ret < 0)
2654                 return -1;
2655 
2656             event.sctp_sender_dry_event = 0;
2657 
2658             ret =
2659                 setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
2660                            sizeof(struct sctp_event_subscribe));
2661 #  endif
2662             if (ret < 0)
2663                 return -1;
2664         }
2665 #  ifdef SCTP_AUTHENTICATION_EVENT
2666         if (snp.sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
2667             dgram_sctp_handle_auth_free_key_event(b, &snp);
2668 #  endif
2669 
2670         if (data->handle_notifications != NULL)
2671             data->handle_notifications(b, data->notification_context,
2672                                        (void *)&snp);
2673 
2674         /* found notification, peek again */
2675         memset(&snp, 0, sizeof(snp));
2676         iov.iov_base = (char *)&snp;
2677         iov.iov_len = sizeof(union sctp_notification);
2678         msg.msg_name = NULL;
2679         msg.msg_namelen = 0;
2680         msg.msg_iov = &iov;
2681         msg.msg_iovlen = 1;
2682         msg.msg_control = NULL;
2683         msg.msg_controllen = 0;
2684         msg.msg_flags = 0;
2685 
2686         /* if we have seen the dry already, don't wait */
2687         if (is_dry) {
2688             sockflags = fcntl(b->num, F_GETFL, 0);
2689             fcntl(b->num, F_SETFL, O_NONBLOCK);
2690         }
2691 
2692         n = recvmsg(b->num, &msg, MSG_PEEK);
2693 
2694         if (is_dry) {
2695             fcntl(b->num, F_SETFL, sockflags);
2696         }
2697 
2698         if (n <= 0) {
2699             if ((n < 0) && (get_last_socket_error() != EAGAIN)
2700                 && (get_last_socket_error() != EWOULDBLOCK))
2701                 return -1;
2702             else
2703                 return is_dry;
2704         }
2705     }
2706 
2707     /* read anything else */
2708     return is_dry;
2709 }
2710 
BIO_dgram_sctp_msg_waiting(BIO * b)2711 int BIO_dgram_sctp_msg_waiting(BIO *b)
2712 {
2713     return (int)BIO_ctrl(b, BIO_CTRL_DGRAM_SCTP_MSG_WAITING, 0, NULL);
2714 }
2715 
dgram_sctp_msg_waiting(BIO * b)2716 static int dgram_sctp_msg_waiting(BIO *b)
2717 {
2718     int n, sockflags;
2719     union sctp_notification snp;
2720     struct msghdr msg;
2721     struct iovec iov;
2722     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
2723 
2724     /* Check if there are any messages waiting to be read */
2725     do {
2726         memset(&snp, 0, sizeof(snp));
2727         iov.iov_base = (char *)&snp;
2728         iov.iov_len = sizeof(union sctp_notification);
2729         msg.msg_name = NULL;
2730         msg.msg_namelen = 0;
2731         msg.msg_iov = &iov;
2732         msg.msg_iovlen = 1;
2733         msg.msg_control = NULL;
2734         msg.msg_controllen = 0;
2735         msg.msg_flags = 0;
2736 
2737         sockflags = fcntl(b->num, F_GETFL, 0);
2738         fcntl(b->num, F_SETFL, O_NONBLOCK);
2739         n = recvmsg(b->num, &msg, MSG_PEEK);
2740         fcntl(b->num, F_SETFL, sockflags);
2741 
2742         /* if notification, process and try again */
2743         if (n > 0 && (msg.msg_flags & MSG_NOTIFICATION)) {
2744 #  ifdef SCTP_AUTHENTICATION_EVENT
2745             if (snp.sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
2746                 dgram_sctp_handle_auth_free_key_event(b, &snp);
2747 #  endif
2748 
2749             memset(&snp, 0, sizeof(snp));
2750             iov.iov_base = (char *)&snp;
2751             iov.iov_len = sizeof(union sctp_notification);
2752             msg.msg_name = NULL;
2753             msg.msg_namelen = 0;
2754             msg.msg_iov = &iov;
2755             msg.msg_iovlen = 1;
2756             msg.msg_control = NULL;
2757             msg.msg_controllen = 0;
2758             msg.msg_flags = 0;
2759             n = recvmsg(b->num, &msg, 0);
2760 
2761             if (data->handle_notifications != NULL)
2762                 data->handle_notifications(b, data->notification_context,
2763                                            (void *)&snp);
2764         }
2765 
2766     } while (n > 0 && (msg.msg_flags & MSG_NOTIFICATION));
2767 
2768     /* Return 1 if there is a message to be read, return 0 otherwise. */
2769     if (n > 0)
2770         return 1;
2771     else
2772         return 0;
2773 }
2774 
dgram_sctp_puts(BIO * bp,const char * str)2775 static int dgram_sctp_puts(BIO *bp, const char *str)
2776 {
2777     int n, ret;
2778 
2779     n = strlen(str);
2780     ret = dgram_sctp_write(bp, str, n);
2781     return ret;
2782 }
2783 # endif
2784 
BIO_dgram_should_retry(int i)2785 static int BIO_dgram_should_retry(int i)
2786 {
2787     int err;
2788 
2789     if ((i == 0) || (i == -1)) {
2790         err = get_last_socket_error();
2791 
2792 # if defined(OPENSSL_SYS_WINDOWS)
2793         /*
2794          * If the socket return value (i) is -1 and err is unexpectedly 0 at
2795          * this point, the error code was overwritten by another system call
2796          * before this error handling is called.
2797          */
2798 # endif
2799 
2800         return BIO_dgram_non_fatal_error(err);
2801     }
2802     return 0;
2803 }
2804 
BIO_dgram_non_fatal_error(int err)2805 int BIO_dgram_non_fatal_error(int err)
2806 {
2807     switch (err) {
2808 # if defined(OPENSSL_SYS_WINDOWS)
2809 #  if defined(WSAEWOULDBLOCK)
2810     case WSAEWOULDBLOCK:
2811 #  endif
2812 # endif
2813 
2814 # ifdef EWOULDBLOCK
2815 #  ifdef WSAEWOULDBLOCK
2816 #   if WSAEWOULDBLOCK != EWOULDBLOCK
2817     case EWOULDBLOCK:
2818 #   endif
2819 #  else
2820     case EWOULDBLOCK:
2821 #  endif
2822 # endif
2823 
2824 # ifdef EINTR
2825     case EINTR:
2826 # endif
2827 
2828 # ifdef EAGAIN
2829 #  if EWOULDBLOCK != EAGAIN
2830     case EAGAIN:
2831 #  endif
2832 # endif
2833 
2834 # ifdef EPROTO
2835     case EPROTO:
2836 # endif
2837 
2838 # ifdef EINPROGRESS
2839     case EINPROGRESS:
2840 # endif
2841 
2842 # ifdef EALREADY
2843     case EALREADY:
2844 # endif
2845 
2846         return 1;
2847     default:
2848         break;
2849     }
2850     return 0;
2851 }
2852 
2853 #endif
2854