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