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