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