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