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