737359722aaef6f227474263c42c9859f3df6474
[openssl.git] / crypto / bio / bss_dgram.c
1 /* crypto/bio/bio_dgram.c */
2 /*
3  * DTLS implementation written by Nagendra Modadugu
4  * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
5  */
6 /* ====================================================================
7  * Copyright (c) 1999-2005 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    openssl-core@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59
60 #include <stdio.h>
61 #include <errno.h>
62 #define USE_SOCKETS
63 #include "cryptlib.h"
64
65 #include <openssl/bio.h>
66 #ifndef OPENSSL_NO_DGRAM
67
68 # if !(defined(_WIN32) || defined(OPENSSL_SYS_VMS))
69 #  include <sys/time.h>
70 # endif
71 # if defined(OPENSSL_SYS_VMS)
72 #  include <sys/timeb.h>
73 # endif
74
75 # ifndef OPENSSL_NO_SCTP
76 #  include <netinet/sctp.h>
77 #  include <fcntl.h>
78 #  define OPENSSL_SCTP_DATA_CHUNK_TYPE            0x00
79 #  define OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE 0xc0
80 # endif
81
82 # if defined(OPENSSL_SYS_LINUX) && !defined(IP_MTU)
83 #  define IP_MTU      14        /* linux is lame */
84 # endif
85
86 # if OPENSSL_USE_IPV6 && !defined(IPPROTO_IPV6)
87 #  define IPPROTO_IPV6 41       /* windows is lame */
88 # endif
89
90 # if defined(__FreeBSD__) && defined(IN6_IS_ADDR_V4MAPPED)
91 /* Standard definition causes type-punning problems. */
92 #  undef IN6_IS_ADDR_V4MAPPED
93 #  define s6_addr32 __u6_addr.__u6_addr32
94 #  define IN6_IS_ADDR_V4MAPPED(a)               \
95         (((a)->s6_addr32[0] == 0) &&          \
96          ((a)->s6_addr32[1] == 0) &&          \
97          ((a)->s6_addr32[2] == htonl(0x0000ffff)))
98 # endif
99
100 # ifdef WATT32
101 #  define sock_write SockWrite  /* Watt-32 uses same names */
102 #  define sock_read  SockRead
103 #  define sock_puts  SockPuts
104 # endif
105
106 static int dgram_write(BIO *h, const char *buf, int num);
107 static int dgram_read(BIO *h, char *buf, int size);
108 static int dgram_puts(BIO *h, const char *str);
109 static long dgram_ctrl(BIO *h, int cmd, long arg1, void *arg2);
110 static int dgram_new(BIO *h);
111 static int dgram_free(BIO *data);
112 static int dgram_clear(BIO *bio);
113
114 # ifndef OPENSSL_NO_SCTP
115 static int dgram_sctp_write(BIO *h, const char *buf, int num);
116 static int dgram_sctp_read(BIO *h, char *buf, int size);
117 static int dgram_sctp_puts(BIO *h, const char *str);
118 static long dgram_sctp_ctrl(BIO *h, int cmd, long arg1, void *arg2);
119 static int dgram_sctp_new(BIO *h);
120 static int dgram_sctp_free(BIO *data);
121 #  ifdef SCTP_AUTHENTICATION_EVENT
122 static void dgram_sctp_handle_auth_free_key_event(BIO *b, union sctp_notification
123                                                   *snp);
124 #  endif
125 # endif
126
127 static int BIO_dgram_should_retry(int s);
128
129 static void get_current_time(struct timeval *t);
130
131 static BIO_METHOD methods_dgramp = {
132     BIO_TYPE_DGRAM,
133     "datagram socket",
134     dgram_write,
135     dgram_read,
136     dgram_puts,
137     NULL,                       /* dgram_gets, */
138     dgram_ctrl,
139     dgram_new,
140     dgram_free,
141     NULL,
142 };
143
144 # ifndef OPENSSL_NO_SCTP
145 static BIO_METHOD methods_dgramp_sctp = {
146     BIO_TYPE_DGRAM_SCTP,
147     "datagram sctp socket",
148     dgram_sctp_write,
149     dgram_sctp_read,
150     dgram_sctp_puts,
151     NULL,                       /* dgram_gets, */
152     dgram_sctp_ctrl,
153     dgram_sctp_new,
154     dgram_sctp_free,
155     NULL,
156 };
157 # endif
158
159 typedef struct bio_dgram_data_st {
160     union {
161         struct sockaddr sa;
162         struct sockaddr_in sa_in;
163 # if OPENSSL_USE_IPV6
164         struct sockaddr_in6 sa_in6;
165 # endif
166     } peer;
167     unsigned int connected;
168     unsigned int _errno;
169     unsigned int mtu;
170     struct timeval next_timeout;
171     struct timeval socket_timeout;
172 } bio_dgram_data;
173
174 # ifndef OPENSSL_NO_SCTP
175 typedef struct bio_dgram_sctp_save_message_st {
176     BIO *bio;
177     char *data;
178     int length;
179 } bio_dgram_sctp_save_message;
180
181 typedef struct bio_dgram_sctp_data_st {
182     union {
183         struct sockaddr sa;
184         struct sockaddr_in sa_in;
185 #  if OPENSSL_USE_IPV6
186         struct sockaddr_in6 sa_in6;
187 #  endif
188     } peer;
189     unsigned int connected;
190     unsigned int _errno;
191     unsigned int mtu;
192     struct bio_dgram_sctp_sndinfo sndinfo;
193     struct bio_dgram_sctp_rcvinfo rcvinfo;
194     struct bio_dgram_sctp_prinfo prinfo;
195     void (*handle_notifications) (BIO *bio, void *context, void *buf);
196     void *notification_context;
197     int in_handshake;
198     int ccs_rcvd;
199     int ccs_sent;
200     int save_shutdown;
201     int peer_auth_tested;
202     bio_dgram_sctp_save_message saved_message;
203 } bio_dgram_sctp_data;
204 # endif
205
206 BIO_METHOD *BIO_s_datagram(void)
207 {
208     return (&methods_dgramp);
209 }
210
211 BIO *BIO_new_dgram(int fd, int close_flag)
212 {
213     BIO *ret;
214
215     ret = BIO_new(BIO_s_datagram());
216     if (ret == NULL)
217         return (NULL);
218     BIO_set_fd(ret, fd, close_flag);
219     return (ret);
220 }
221
222 static int dgram_new(BIO *bi)
223 {
224     bio_dgram_data *data = NULL;
225
226     bi->init = 0;
227     bi->num = 0;
228     data = OPENSSL_malloc(sizeof(bio_dgram_data));
229     if (data == NULL)
230         return 0;
231     memset(data, 0x00, sizeof(bio_dgram_data));
232     bi->ptr = data;
233
234     bi->flags = 0;
235     return (1);
236 }
237
238 static int dgram_free(BIO *a)
239 {
240     bio_dgram_data *data;
241
242     if (a == NULL)
243         return (0);
244     if (!dgram_clear(a))
245         return 0;
246
247     data = (bio_dgram_data *)a->ptr;
248     if (data != NULL)
249         OPENSSL_free(data);
250
251     return (1);
252 }
253
254 static int dgram_clear(BIO *a)
255 {
256     if (a == NULL)
257         return (0);
258     if (a->shutdown) {
259         if (a->init) {
260             SHUTDOWN2(a->num);
261         }
262         a->init = 0;
263         a->flags = 0;
264     }
265     return (1);
266 }
267
268 static void dgram_adjust_rcv_timeout(BIO *b)
269 {
270 # if defined(SO_RCVTIMEO)
271     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
272     union {
273         size_t s;
274         int i;
275     } sz = {
276         0
277     };
278
279     /* Is a timer active? */
280     if (data->next_timeout.tv_sec > 0 || data->next_timeout.tv_usec > 0) {
281         struct timeval timenow, timeleft;
282
283         /* Read current socket timeout */
284 #  ifdef OPENSSL_SYS_WINDOWS
285         int timeout;
286
287         sz.i = sizeof(timeout);
288         if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
289                        (void *)&timeout, &sz.i) < 0) {
290             perror("getsockopt");
291         } else {
292             data->socket_timeout.tv_sec = timeout / 1000;
293             data->socket_timeout.tv_usec = (timeout % 1000) * 1000;
294         }
295 #  else
296         sz.i = sizeof(data->socket_timeout);
297         if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
298                        &(data->socket_timeout), (void *)&sz) < 0) {
299             perror("getsockopt");
300         } else if (sizeof(sz.s) != sizeof(sz.i) && sz.i == 0)
301             OPENSSL_assert(sz.s <= sizeof(data->socket_timeout));
302 #  endif
303
304         /* Get current time */
305         get_current_time(&timenow);
306
307         /* Calculate time left until timer expires */
308         memcpy(&timeleft, &(data->next_timeout), sizeof(struct timeval));
309         timeleft.tv_sec -= timenow.tv_sec;
310         timeleft.tv_usec -= timenow.tv_usec;
311         if (timeleft.tv_usec < 0) {
312             timeleft.tv_sec--;
313             timeleft.tv_usec += 1000000;
314         }
315
316         if (timeleft.tv_sec < 0) {
317             timeleft.tv_sec = 0;
318             timeleft.tv_usec = 1;
319         }
320
321         /*
322          * Adjust socket timeout if next handhake message timer will expire
323          * earlier.
324          */
325         if ((data->socket_timeout.tv_sec == 0
326              && data->socket_timeout.tv_usec == 0)
327             || (data->socket_timeout.tv_sec > timeleft.tv_sec)
328             || (data->socket_timeout.tv_sec == timeleft.tv_sec
329                 && data->socket_timeout.tv_usec >= timeleft.tv_usec)) {
330 #  ifdef OPENSSL_SYS_WINDOWS
331             timeout = timeleft.tv_sec * 1000 + timeleft.tv_usec / 1000;
332             if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
333                            (void *)&timeout, sizeof(timeout)) < 0) {
334                 perror("setsockopt");
335             }
336 #  else
337             if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, &timeleft,
338                            sizeof(struct timeval)) < 0) {
339                 perror("setsockopt");
340             }
341 #  endif
342         }
343     }
344 # endif
345 }
346
347 static void dgram_reset_rcv_timeout(BIO *b)
348 {
349 # if defined(SO_RCVTIMEO)
350     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
351
352     /* Is a timer active? */
353     if (data->next_timeout.tv_sec > 0 || data->next_timeout.tv_usec > 0) {
354 #  ifdef OPENSSL_SYS_WINDOWS
355         int timeout = data->socket_timeout.tv_sec * 1000 +
356             data->socket_timeout.tv_usec / 1000;
357         if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
358                        (void *)&timeout, sizeof(timeout)) < 0) {
359             perror("setsockopt");
360         }
361 #  else
362         if (setsockopt
363             (b->num, SOL_SOCKET, SO_RCVTIMEO, &(data->socket_timeout),
364              sizeof(struct timeval)) < 0) {
365             perror("setsockopt");
366         }
367 #  endif
368     }
369 # endif
370 }
371
372 static int dgram_read(BIO *b, char *out, int outl)
373 {
374     int ret = 0;
375     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
376
377     struct {
378         /*
379          * See commentary in b_sock.c. <appro>
380          */
381         union {
382             size_t s;
383             int i;
384         } len;
385         union {
386             struct sockaddr sa;
387             struct sockaddr_in sa_in;
388 # if OPENSSL_USE_IPV6
389             struct sockaddr_in6 sa_in6;
390 # endif
391         } peer;
392     } sa;
393
394     sa.len.s = 0;
395     sa.len.i = sizeof(sa.peer);
396
397     if (out != NULL) {
398         clear_socket_error();
399         memset(&sa.peer, 0x00, sizeof(sa.peer));
400         dgram_adjust_rcv_timeout(b);
401         ret = recvfrom(b->num, out, outl, 0, &sa.peer.sa, (void *)&sa.len);
402         if (sizeof(sa.len.i) != sizeof(sa.len.s) && sa.len.i == 0) {
403             OPENSSL_assert(sa.len.s <= sizeof(sa.peer));
404             sa.len.i = (int)sa.len.s;
405         }
406
407         if (!data->connected && ret >= 0)
408             BIO_ctrl(b, BIO_CTRL_DGRAM_SET_PEER, 0, &sa.peer);
409
410         BIO_clear_retry_flags(b);
411         if (ret < 0) {
412             if (BIO_dgram_should_retry(ret)) {
413                 BIO_set_retry_read(b);
414                 data->_errno = get_last_socket_error();
415             }
416         }
417
418         dgram_reset_rcv_timeout(b);
419     }
420     return (ret);
421 }
422
423 static int dgram_write(BIO *b, const char *in, int inl)
424 {
425     int ret;
426     bio_dgram_data *data = (bio_dgram_data *)b->ptr;
427     clear_socket_error();
428
429     if (data->connected)
430         ret = writesocket(b->num, in, inl);
431     else {
432         int peerlen = sizeof(data->peer);
433
434         if (data->peer.sa.sa_family == AF_INET)
435             peerlen = sizeof(data->peer.sa_in);
436 # if OPENSSL_USE_IPV6
437         else if (data->peer.sa.sa_family == AF_INET6)
438             peerlen = sizeof(data->peer.sa_in6);
439 # endif
440 # if defined(NETWARE_CLIB) && defined(NETWARE_BSDSOCK)
441         ret = sendto(b->num, (char *)in, inl, 0, &data->peer.sa, peerlen);
442 # else
443         ret = sendto(b->num, in, inl, 0, &data->peer.sa, peerlen);
444 # endif
445     }
446
447     BIO_clear_retry_flags(b);
448     if (ret <= 0) {
449         if (BIO_dgram_should_retry(ret)) {
450             BIO_set_retry_write(b);
451             data->_errno = get_last_socket_error();
452
453 # if 0                          /* higher layers are responsible for querying
454                                  * MTU, if necessary */
455             if (data->_errno == EMSGSIZE)
456                 /* retrieve the new MTU */
457                 BIO_ctrl(b, BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
458 # endif
459         }
460     }
461     return (ret);
462 }
463
464 static long dgram_get_mtu_overhead(bio_dgram_data *data)
465 {
466     long ret;
467
468     switch (data->peer.sa.sa_family) {
469     case AF_INET:
470         /*
471          * Assume this is UDP - 20 bytes for IP, 8 bytes for UDP
472          */
473         ret = 28;
474         break;
475 # if OPENSSL_USE_IPV6
476     case AF_INET6:
477 #  ifdef IN6_IS_ADDR_V4MAPPED
478         if (IN6_IS_ADDR_V4MAPPED(&data->peer.sa_in6.sin6_addr))
479             /*
480              * Assume this is UDP - 20 bytes for IP, 8 bytes for UDP
481              */
482             ret = 28;
483         else
484 #  endif
485             /*
486              * Assume this is UDP - 40 bytes for IP, 8 bytes for UDP
487              */
488             ret = 48;
489         break;
490 # endif
491     default:
492         /* We don't know. Go with the historical default */
493         ret = 28;
494         break;
495     }
496     return ret;
497 }
498
499 static long dgram_ctrl(BIO *b, int cmd, long num, void *ptr)
500 {
501     long ret = 1;
502     int *ip;
503     struct sockaddr *to = NULL;
504     bio_dgram_data *data = NULL;
505     int sockopt_val = 0;
506 # if defined(OPENSSL_SYS_LINUX) && (defined(IP_MTU_DISCOVER) || defined(IP_MTU))
507     socklen_t sockopt_len;      /* assume that system supporting IP_MTU is
508                                  * modern enough to define socklen_t */
509     socklen_t addr_len;
510     union {
511         struct sockaddr sa;
512         struct sockaddr_in s4;
513 #  if OPENSSL_USE_IPV6
514         struct sockaddr_in6 s6;
515 #  endif
516     } addr;
517 # endif
518
519     data = (bio_dgram_data *)b->ptr;
520
521     switch (cmd) {
522     case BIO_CTRL_RESET:
523         num = 0;
524     case BIO_C_FILE_SEEK:
525         ret = 0;
526         break;
527     case BIO_C_FILE_TELL:
528     case BIO_CTRL_INFO:
529         ret = 0;
530         break;
531     case BIO_C_SET_FD:
532         dgram_clear(b);
533         b->num = *((int *)ptr);
534         b->shutdown = (int)num;
535         b->init = 1;
536         break;
537     case BIO_C_GET_FD:
538         if (b->init) {
539             ip = (int *)ptr;
540             if (ip != NULL)
541                 *ip = b->num;
542             ret = b->num;
543         } else
544             ret = -1;
545         break;
546     case BIO_CTRL_GET_CLOSE:
547         ret = b->shutdown;
548         break;
549     case BIO_CTRL_SET_CLOSE:
550         b->shutdown = (int)num;
551         break;
552     case BIO_CTRL_PENDING:
553     case BIO_CTRL_WPENDING:
554         ret = 0;
555         break;
556     case BIO_CTRL_DUP:
557     case BIO_CTRL_FLUSH:
558         ret = 1;
559         break;
560     case BIO_CTRL_DGRAM_CONNECT:
561         to = (struct sockaddr *)ptr;
562 # if 0
563         if (connect(b->num, to, sizeof(struct sockaddr)) < 0) {
564             perror("connect");
565             ret = 0;
566         } else {
567 # endif
568             switch (to->sa_family) {
569             case AF_INET:
570                 memcpy(&data->peer, to, sizeof(data->peer.sa_in));
571                 break;
572 # if OPENSSL_USE_IPV6
573             case AF_INET6:
574                 memcpy(&data->peer, to, sizeof(data->peer.sa_in6));
575                 break;
576 # endif
577             default:
578                 memcpy(&data->peer, to, sizeof(data->peer.sa));
579                 break;
580             }
581 # if 0
582         }
583 # endif
584         break;
585         /* (Linux)kernel sets DF bit on outgoing IP packets */
586     case BIO_CTRL_DGRAM_MTU_DISCOVER:
587 # if defined(OPENSSL_SYS_LINUX) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
588         addr_len = (socklen_t) sizeof(addr);
589         memset((void *)&addr, 0, sizeof(addr));
590         if (getsockname(b->num, &addr.sa, &addr_len) < 0) {
591             ret = 0;
592             break;
593         }
594         switch (addr.sa.sa_family) {
595         case AF_INET:
596             sockopt_val = IP_PMTUDISC_DO;
597             if ((ret = setsockopt(b->num, IPPROTO_IP, IP_MTU_DISCOVER,
598                                   &sockopt_val, sizeof(sockopt_val))) < 0)
599                 perror("setsockopt");
600             break;
601 #  if OPENSSL_USE_IPV6 && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
602         case AF_INET6:
603             sockopt_val = IPV6_PMTUDISC_DO;
604             if ((ret = setsockopt(b->num, IPPROTO_IPV6, IPV6_MTU_DISCOVER,
605                                   &sockopt_val, sizeof(sockopt_val))) < 0)
606                 perror("setsockopt");
607             break;
608 #  endif
609         default:
610             ret = -1;
611             break;
612         }
613 # else
614         ret = -1;
615 # endif
616         break;
617     case BIO_CTRL_DGRAM_QUERY_MTU:
618 # if defined(OPENSSL_SYS_LINUX) && defined(IP_MTU)
619         addr_len = (socklen_t) sizeof(addr);
620         memset((void *)&addr, 0, sizeof(addr));
621         if (getsockname(b->num, &addr.sa, &addr_len) < 0) {
622             ret = 0;
623             break;
624         }
625         sockopt_len = sizeof(sockopt_val);
626         switch (addr.sa.sa_family) {
627         case AF_INET:
628             if ((ret =
629                  getsockopt(b->num, IPPROTO_IP, IP_MTU, (void *)&sockopt_val,
630                             &sockopt_len)) < 0 || sockopt_val < 0) {
631                 ret = 0;
632             } else {
633                 /*
634                  * we assume that the transport protocol is UDP and no IP
635                  * options are used.
636                  */
637                 data->mtu = sockopt_val - 8 - 20;
638                 ret = data->mtu;
639             }
640             break;
641 #  if OPENSSL_USE_IPV6 && defined(IPV6_MTU)
642         case AF_INET6:
643             if ((ret =
644                  getsockopt(b->num, IPPROTO_IPV6, IPV6_MTU,
645                             (void *)&sockopt_val, &sockopt_len)) < 0
646                 || sockopt_val < 0) {
647                 ret = 0;
648             } else {
649                 /*
650                  * we assume that the transport protocol is UDP and no IPV6
651                  * options are used.
652                  */
653                 data->mtu = sockopt_val - 8 - 40;
654                 ret = data->mtu;
655             }
656             break;
657 #  endif
658         default:
659             ret = 0;
660             break;
661         }
662 # else
663         ret = 0;
664 # endif
665         break;
666     case BIO_CTRL_DGRAM_GET_FALLBACK_MTU:
667         ret = -dgram_get_mtu_overhead(data);
668         switch (data->peer.sa.sa_family) {
669         case AF_INET:
670             ret += 576;
671             break;
672 # if OPENSSL_USE_IPV6
673         case AF_INET6:
674 #  ifdef IN6_IS_ADDR_V4MAPPED
675             if (IN6_IS_ADDR_V4MAPPED(&data->peer.sa_in6.sin6_addr))
676                 ret += 576;
677             else
678 #  endif
679                 ret += 1280;
680             break;
681 # endif
682         default:
683             ret += 576;
684             break;
685         }
686         break;
687     case BIO_CTRL_DGRAM_GET_MTU:
688         return data->mtu;
689     case BIO_CTRL_DGRAM_SET_MTU:
690         data->mtu = num;
691         ret = num;
692         break;
693     case BIO_CTRL_DGRAM_SET_CONNECTED:
694         to = (struct sockaddr *)ptr;
695
696         if (to != NULL) {
697             data->connected = 1;
698             switch (to->sa_family) {
699             case AF_INET:
700                 memcpy(&data->peer, to, sizeof(data->peer.sa_in));
701                 break;
702 # if OPENSSL_USE_IPV6
703             case AF_INET6:
704                 memcpy(&data->peer, to, sizeof(data->peer.sa_in6));
705                 break;
706 # endif
707             default:
708                 memcpy(&data->peer, to, sizeof(data->peer.sa));
709                 break;
710             }
711         } else {
712             data->connected = 0;
713             memset(&(data->peer), 0x00, sizeof(data->peer));
714         }
715         break;
716     case BIO_CTRL_DGRAM_GET_PEER:
717         switch (data->peer.sa.sa_family) {
718         case AF_INET:
719             ret = sizeof(data->peer.sa_in);
720             break;
721 # if OPENSSL_USE_IPV6
722         case AF_INET6:
723             ret = sizeof(data->peer.sa_in6);
724             break;
725 # endif
726         default:
727             ret = sizeof(data->peer.sa);
728             break;
729         }
730         if (num == 0 || num > ret)
731             num = ret;
732         memcpy(ptr, &data->peer, (ret = num));
733         break;
734     case BIO_CTRL_DGRAM_SET_PEER:
735         to = (struct sockaddr *)ptr;
736         switch (to->sa_family) {
737         case AF_INET:
738             memcpy(&data->peer, to, sizeof(data->peer.sa_in));
739             break;
740 # if OPENSSL_USE_IPV6
741         case AF_INET6:
742             memcpy(&data->peer, to, sizeof(data->peer.sa_in6));
743             break;
744 # endif
745         default:
746             memcpy(&data->peer, to, sizeof(data->peer.sa));
747             break;
748         }
749         break;
750     case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
751         memcpy(&(data->next_timeout), ptr, sizeof(struct timeval));
752         break;
753 # if defined(SO_RCVTIMEO)
754     case BIO_CTRL_DGRAM_SET_RECV_TIMEOUT:
755 #  ifdef OPENSSL_SYS_WINDOWS
756         {
757             struct timeval *tv = (struct timeval *)ptr;
758             int timeout = tv->tv_sec * 1000 + tv->tv_usec / 1000;
759             if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
760                            (void *)&timeout, sizeof(timeout)) < 0) {
761                 perror("setsockopt");
762                 ret = -1;
763             }
764         }
765 #  else
766         if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, ptr,
767                        sizeof(struct timeval)) < 0) {
768             perror("setsockopt");
769             ret = -1;
770         }
771 #  endif
772         break;
773     case BIO_CTRL_DGRAM_GET_RECV_TIMEOUT:
774         {
775             union {
776                 size_t s;
777                 int i;
778             } sz = {
779                 0
780             };
781 #  ifdef OPENSSL_SYS_WINDOWS
782             int timeout;
783             struct timeval *tv = (struct timeval *)ptr;
784
785             sz.i = sizeof(timeout);
786             if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
787                            (void *)&timeout, &sz.i) < 0) {
788                 perror("getsockopt");
789                 ret = -1;
790             } else {
791                 tv->tv_sec = timeout / 1000;
792                 tv->tv_usec = (timeout % 1000) * 1000;
793                 ret = sizeof(*tv);
794             }
795 #  else
796             sz.i = sizeof(struct timeval);
797             if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
798                            ptr, (void *)&sz) < 0) {
799                 perror("getsockopt");
800                 ret = -1;
801             } else if (sizeof(sz.s) != sizeof(sz.i) && sz.i == 0) {
802                 OPENSSL_assert(sz.s <= sizeof(struct timeval));
803                 ret = (int)sz.s;
804             } else
805                 ret = sz.i;
806 #  endif
807         }
808         break;
809 # endif
810 # if defined(SO_SNDTIMEO)
811     case BIO_CTRL_DGRAM_SET_SEND_TIMEOUT:
812 #  ifdef OPENSSL_SYS_WINDOWS
813         {
814             struct timeval *tv = (struct timeval *)ptr;
815             int timeout = tv->tv_sec * 1000 + tv->tv_usec / 1000;
816             if (setsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
817                            (void *)&timeout, sizeof(timeout)) < 0) {
818                 perror("setsockopt");
819                 ret = -1;
820             }
821         }
822 #  else
823         if (setsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO, ptr,
824                        sizeof(struct timeval)) < 0) {
825             perror("setsockopt");
826             ret = -1;
827         }
828 #  endif
829         break;
830     case BIO_CTRL_DGRAM_GET_SEND_TIMEOUT:
831         {
832             union {
833                 size_t s;
834                 int i;
835             } sz = {
836                 0
837             };
838 #  ifdef OPENSSL_SYS_WINDOWS
839             int timeout;
840             struct timeval *tv = (struct timeval *)ptr;
841
842             sz.i = sizeof(timeout);
843             if (getsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
844                            (void *)&timeout, &sz.i) < 0) {
845                 perror("getsockopt");
846                 ret = -1;
847             } else {
848                 tv->tv_sec = timeout / 1000;
849                 tv->tv_usec = (timeout % 1000) * 1000;
850                 ret = sizeof(*tv);
851             }
852 #  else
853             sz.i = sizeof(struct timeval);
854             if (getsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
855                            ptr, (void *)&sz) < 0) {
856                 perror("getsockopt");
857                 ret = -1;
858             } else if (sizeof(sz.s) != sizeof(sz.i) && sz.i == 0) {
859                 OPENSSL_assert(sz.s <= sizeof(struct timeval));
860                 ret = (int)sz.s;
861             } else
862                 ret = sz.i;
863 #  endif
864         }
865         break;
866 # endif
867     case BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP:
868         /* fall-through */
869     case BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP:
870 # ifdef OPENSSL_SYS_WINDOWS
871         if (data->_errno == WSAETIMEDOUT)
872 # else
873         if (data->_errno == EAGAIN)
874 # endif
875         {
876             ret = 1;
877             data->_errno = 0;
878         } else
879             ret = 0;
880         break;
881 # ifdef EMSGSIZE
882     case BIO_CTRL_DGRAM_MTU_EXCEEDED:
883         if (data->_errno == EMSGSIZE) {
884             ret = 1;
885             data->_errno = 0;
886         } else
887             ret = 0;
888         break;
889 # endif
890     case BIO_CTRL_DGRAM_SET_DONT_FRAG:
891         sockopt_val = num ? 1 : 0;
892
893         switch (data->peer.sa.sa_family) {
894         case AF_INET:
895 # if defined(IP_DONTFRAG)
896             if ((ret = setsockopt(b->num, IPPROTO_IP, IP_DONTFRAG,
897                                   &sockopt_val, sizeof(sockopt_val))) < 0) {
898                 perror("setsockopt");
899                 ret = -1;
900             }
901 # elif defined(OPENSSL_SYS_LINUX) && defined(IP_MTUDISCOVER)
902             if ((sockopt_val = num ? IP_PMTUDISC_PROBE : IP_PMTUDISC_DONT),
903                 (ret = setsockopt(b->num, IPPROTO_IP, IP_MTU_DISCOVER,
904                                   &sockopt_val, sizeof(sockopt_val))) < 0) {
905                 perror("setsockopt");
906                 ret = -1;
907             }
908 # elif defined(OPENSSL_SYS_WINDOWS) && defined(IP_DONTFRAGMENT)
909             if ((ret = setsockopt(b->num, IPPROTO_IP, IP_DONTFRAGMENT,
910                                   (const char *)&sockopt_val,
911                                   sizeof(sockopt_val))) < 0) {
912                 perror("setsockopt");
913                 ret = -1;
914             }
915 # else
916             ret = -1;
917 # endif
918             break;
919 # if OPENSSL_USE_IPV6
920         case AF_INET6:
921 #  if defined(IPV6_DONTFRAG)
922             if ((ret = setsockopt(b->num, IPPROTO_IPV6, IPV6_DONTFRAG,
923                                   (const void *)&sockopt_val,
924                                   sizeof(sockopt_val))) < 0) {
925                 perror("setsockopt");
926                 ret = -1;
927             }
928 #  elif defined(OPENSSL_SYS_LINUX) && defined(IPV6_MTUDISCOVER)
929             if ((sockopt_val = num ? IP_PMTUDISC_PROBE : IP_PMTUDISC_DONT),
930                 (ret = setsockopt(b->num, IPPROTO_IPV6, IPV6_MTU_DISCOVER,
931                                   &sockopt_val, sizeof(sockopt_val))) < 0) {
932                 perror("setsockopt");
933                 ret = -1;
934             }
935 #  else
936             ret = -1;
937 #  endif
938             break;
939 # endif
940         default:
941             ret = -1;
942             break;
943         }
944         break;
945     case BIO_CTRL_DGRAM_GET_MTU_OVERHEAD:
946         ret = dgram_get_mtu_overhead(data);
947         break;
948     default:
949         ret = 0;
950         break;
951     }
952     return (ret);
953 }
954
955 static int dgram_puts(BIO *bp, const char *str)
956 {
957     int n, ret;
958
959     n = strlen(str);
960     ret = dgram_write(bp, str, n);
961     return (ret);
962 }
963
964 # ifndef OPENSSL_NO_SCTP
965 BIO_METHOD *BIO_s_datagram_sctp(void)
966 {
967     return (&methods_dgramp_sctp);
968 }
969
970 BIO *BIO_new_dgram_sctp(int fd, int close_flag)
971 {
972     BIO *bio;
973     int ret, optval = 20000;
974     int auth_data = 0, auth_forward = 0;
975     unsigned char *p;
976     struct sctp_authchunk auth;
977     struct sctp_authchunks *authchunks;
978     socklen_t sockopt_len;
979 #  ifdef SCTP_AUTHENTICATION_EVENT
980 #   ifdef SCTP_EVENT
981     struct sctp_event event;
982 #   else
983     struct sctp_event_subscribe event;
984 #   endif
985 #  endif
986
987     bio = BIO_new(BIO_s_datagram_sctp());
988     if (bio == NULL)
989         return (NULL);
990     BIO_set_fd(bio, fd, close_flag);
991
992     /* Activate SCTP-AUTH for DATA and FORWARD-TSN chunks */
993     auth.sauth_chunk = OPENSSL_SCTP_DATA_CHUNK_TYPE;
994     ret =
995         setsockopt(fd, IPPROTO_SCTP, SCTP_AUTH_CHUNK, &auth,
996                    sizeof(struct sctp_authchunk));
997     if (ret < 0) {
998         BIO_vfree(bio);
999         return (NULL);
1000     }
1001     auth.sauth_chunk = OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE;
1002     ret =
1003         setsockopt(fd, IPPROTO_SCTP, SCTP_AUTH_CHUNK, &auth,
1004                    sizeof(struct sctp_authchunk));
1005     if (ret < 0) {
1006         BIO_vfree(bio);
1007         return (NULL);
1008     }
1009
1010     /*
1011      * Test if activation was successful. When using accept(), SCTP-AUTH has
1012      * to be activated for the listening socket already, otherwise the
1013      * connected socket won't use it.
1014      */
1015     sockopt_len = (socklen_t) (sizeof(sctp_assoc_t) + 256 * sizeof(uint8_t));
1016     authchunks = OPENSSL_malloc(sockopt_len);
1017     memset(authchunks, 0, sockopt_len);
1018     ret =
1019         getsockopt(fd, IPPROTO_SCTP, SCTP_LOCAL_AUTH_CHUNKS, authchunks,
1020                    &sockopt_len);
1021
1022     if (ret < 0) {
1023         OPENSSL_free(authchunks);
1024         BIO_vfree(bio);
1025         return (NULL);
1026     }
1027
1028     for (p = (unsigned char *)authchunks->gauth_chunks;
1029          p < (unsigned char *)authchunks + sockopt_len;
1030          p += sizeof(uint8_t)) {
1031         if (*p == OPENSSL_SCTP_DATA_CHUNK_TYPE)
1032             auth_data = 1;
1033         if (*p == OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE)
1034             auth_forward = 1;
1035     }
1036
1037     OPENSSL_free(authchunks);
1038
1039     OPENSSL_assert(auth_data);
1040     OPENSSL_assert(auth_forward);
1041
1042 #  ifdef SCTP_AUTHENTICATION_EVENT
1043 #   ifdef SCTP_EVENT
1044     memset(&event, 0, sizeof(struct sctp_event));
1045     event.se_assoc_id = 0;
1046     event.se_type = SCTP_AUTHENTICATION_EVENT;
1047     event.se_on = 1;
1048     ret =
1049         setsockopt(fd, IPPROTO_SCTP, SCTP_EVENT, &event,
1050                    sizeof(struct sctp_event));
1051     if (ret < 0) {
1052         BIO_vfree(bio);
1053         return (NULL);
1054     }
1055 #   else
1056     sockopt_len = (socklen_t) sizeof(struct sctp_event_subscribe);
1057     ret = getsockopt(fd, IPPROTO_SCTP, SCTP_EVENTS, &event, &sockopt_len);
1058     if (ret < 0) {
1059         BIO_vfree(bio);
1060         return (NULL);
1061     }
1062
1063     event.sctp_authentication_event = 1;
1064
1065     ret =
1066         setsockopt(fd, IPPROTO_SCTP, SCTP_EVENTS, &event,
1067                    sizeof(struct sctp_event_subscribe));
1068     if (ret < 0) {
1069         BIO_vfree(bio);
1070         return (NULL);
1071     }
1072 #   endif
1073 #  endif
1074
1075     /*
1076      * Disable partial delivery by setting the min size larger than the max
1077      * record size of 2^14 + 2048 + 13
1078      */
1079     ret =
1080         setsockopt(fd, IPPROTO_SCTP, SCTP_PARTIAL_DELIVERY_POINT, &optval,
1081                    sizeof(optval));
1082     if (ret < 0) {
1083         BIO_vfree(bio);
1084         return (NULL);
1085     }
1086
1087     return (bio);
1088 }
1089
1090 int BIO_dgram_is_sctp(BIO *bio)
1091 {
1092     return (BIO_method_type(bio) == BIO_TYPE_DGRAM_SCTP);
1093 }
1094
1095 static int dgram_sctp_new(BIO *bi)
1096 {
1097     bio_dgram_sctp_data *data = NULL;
1098
1099     bi->init = 0;
1100     bi->num = 0;
1101     data = OPENSSL_malloc(sizeof(bio_dgram_sctp_data));
1102     if (data == NULL)
1103         return 0;
1104     memset(data, 0x00, sizeof(bio_dgram_sctp_data));
1105 #  ifdef SCTP_PR_SCTP_NONE
1106     data->prinfo.pr_policy = SCTP_PR_SCTP_NONE;
1107 #  endif
1108     bi->ptr = data;
1109
1110     bi->flags = 0;
1111     return (1);
1112 }
1113
1114 static int dgram_sctp_free(BIO *a)
1115 {
1116     bio_dgram_sctp_data *data;
1117
1118     if (a == NULL)
1119         return (0);
1120     if (!dgram_clear(a))
1121         return 0;
1122
1123     data = (bio_dgram_sctp_data *) a->ptr;
1124     if (data != NULL) {
1125         if (data->saved_message.data != NULL)
1126             OPENSSL_free(data->saved_message.data);
1127         OPENSSL_free(data);
1128     }
1129
1130     return (1);
1131 }
1132
1133 #  ifdef SCTP_AUTHENTICATION_EVENT
1134 void dgram_sctp_handle_auth_free_key_event(BIO *b,
1135                                            union sctp_notification *snp)
1136 {
1137     int ret;
1138     struct sctp_authkey_event *authkeyevent = &snp->sn_auth_event;
1139
1140     if (authkeyevent->auth_indication == SCTP_AUTH_FREE_KEY) {
1141         struct sctp_authkeyid authkeyid;
1142
1143         /* delete key */
1144         authkeyid.scact_keynumber = authkeyevent->auth_keynumber;
1145         ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DELETE_KEY,
1146                          &authkeyid, sizeof(struct sctp_authkeyid));
1147     }
1148 }
1149 #  endif
1150
1151 static int dgram_sctp_read(BIO *b, char *out, int outl)
1152 {
1153     int ret = 0, n = 0, i, optval;
1154     socklen_t optlen;
1155     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
1156     union sctp_notification *snp;
1157     struct msghdr msg;
1158     struct iovec iov;
1159     struct cmsghdr *cmsg;
1160     char cmsgbuf[512];
1161
1162     if (out != NULL) {
1163         clear_socket_error();
1164
1165         do {
1166             memset(&data->rcvinfo, 0x00,
1167                    sizeof(struct bio_dgram_sctp_rcvinfo));
1168             iov.iov_base = out;
1169             iov.iov_len = outl;
1170             msg.msg_name = NULL;
1171             msg.msg_namelen = 0;
1172             msg.msg_iov = &iov;
1173             msg.msg_iovlen = 1;
1174             msg.msg_control = cmsgbuf;
1175             msg.msg_controllen = 512;
1176             msg.msg_flags = 0;
1177             n = recvmsg(b->num, &msg, 0);
1178
1179             if (n <= 0) {
1180                 if (n < 0)
1181                     ret = n;
1182                 break;
1183             }
1184
1185             if (msg.msg_controllen > 0) {
1186                 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg;
1187                      cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1188                     if (cmsg->cmsg_level != IPPROTO_SCTP)
1189                         continue;
1190 #  ifdef SCTP_RCVINFO
1191                     if (cmsg->cmsg_type == SCTP_RCVINFO) {
1192                         struct sctp_rcvinfo *rcvinfo;
1193
1194                         rcvinfo = (struct sctp_rcvinfo *)CMSG_DATA(cmsg);
1195                         data->rcvinfo.rcv_sid = rcvinfo->rcv_sid;
1196                         data->rcvinfo.rcv_ssn = rcvinfo->rcv_ssn;
1197                         data->rcvinfo.rcv_flags = rcvinfo->rcv_flags;
1198                         data->rcvinfo.rcv_ppid = rcvinfo->rcv_ppid;
1199                         data->rcvinfo.rcv_tsn = rcvinfo->rcv_tsn;
1200                         data->rcvinfo.rcv_cumtsn = rcvinfo->rcv_cumtsn;
1201                         data->rcvinfo.rcv_context = rcvinfo->rcv_context;
1202                     }
1203 #  endif
1204 #  ifdef SCTP_SNDRCV
1205                     if (cmsg->cmsg_type == SCTP_SNDRCV) {
1206                         struct sctp_sndrcvinfo *sndrcvinfo;
1207
1208                         sndrcvinfo =
1209                             (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
1210                         data->rcvinfo.rcv_sid = sndrcvinfo->sinfo_stream;
1211                         data->rcvinfo.rcv_ssn = sndrcvinfo->sinfo_ssn;
1212                         data->rcvinfo.rcv_flags = sndrcvinfo->sinfo_flags;
1213                         data->rcvinfo.rcv_ppid = sndrcvinfo->sinfo_ppid;
1214                         data->rcvinfo.rcv_tsn = sndrcvinfo->sinfo_tsn;
1215                         data->rcvinfo.rcv_cumtsn = sndrcvinfo->sinfo_cumtsn;
1216                         data->rcvinfo.rcv_context = sndrcvinfo->sinfo_context;
1217                     }
1218 #  endif
1219                 }
1220             }
1221
1222             if (msg.msg_flags & MSG_NOTIFICATION) {
1223                 snp = (union sctp_notification *)out;
1224                 if (snp->sn_header.sn_type == SCTP_SENDER_DRY_EVENT) {
1225 #  ifdef SCTP_EVENT
1226                     struct sctp_event event;
1227 #  else
1228                     struct sctp_event_subscribe event;
1229                     socklen_t eventsize;
1230 #  endif
1231                     /*
1232                      * If a message has been delayed until the socket is dry,
1233                      * it can be sent now.
1234                      */
1235                     if (data->saved_message.length > 0) {
1236                         dgram_sctp_write(data->saved_message.bio,
1237                                          data->saved_message.data,
1238                                          data->saved_message.length);
1239                         OPENSSL_free(data->saved_message.data);
1240                         data->saved_message.data = NULL;
1241                         data->saved_message.length = 0;
1242                     }
1243
1244                     /* disable sender dry event */
1245 #  ifdef SCTP_EVENT
1246                     memset(&event, 0, sizeof(struct sctp_event));
1247                     event.se_assoc_id = 0;
1248                     event.se_type = SCTP_SENDER_DRY_EVENT;
1249                     event.se_on = 0;
1250                     i = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event,
1251                                    sizeof(struct sctp_event));
1252                     if (i < 0) {
1253                         ret = i;
1254                         break;
1255                     }
1256 #  else
1257                     eventsize = sizeof(struct sctp_event_subscribe);
1258                     i = getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
1259                                    &eventsize);
1260                     if (i < 0) {
1261                         ret = i;
1262                         break;
1263                     }
1264
1265                     event.sctp_sender_dry_event = 0;
1266
1267                     i = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
1268                                    sizeof(struct sctp_event_subscribe));
1269                     if (i < 0) {
1270                         ret = i;
1271                         break;
1272                     }
1273 #  endif
1274                 }
1275 #  ifdef SCTP_AUTHENTICATION_EVENT
1276                 if (snp->sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
1277                     dgram_sctp_handle_auth_free_key_event(b, snp);
1278 #  endif
1279
1280                 if (data->handle_notifications != NULL)
1281                     data->handle_notifications(b, data->notification_context,
1282                                                (void *)out);
1283
1284                 memset(out, 0, outl);
1285             } else
1286                 ret += n;
1287         }
1288         while ((msg.msg_flags & MSG_NOTIFICATION) && (msg.msg_flags & MSG_EOR)
1289                && (ret < outl));
1290
1291         if (ret > 0 && !(msg.msg_flags & MSG_EOR)) {
1292             /* Partial message read, this should never happen! */
1293
1294             /*
1295              * The buffer was too small, this means the peer sent a message
1296              * that was larger than allowed.
1297              */
1298             if (ret == outl)
1299                 return -1;
1300
1301             /*
1302              * Test if socket buffer can handle max record size (2^14 + 2048
1303              * + 13)
1304              */
1305             optlen = (socklen_t) sizeof(int);
1306             ret = getsockopt(b->num, SOL_SOCKET, SO_RCVBUF, &optval, &optlen);
1307             if (ret >= 0)
1308                 OPENSSL_assert(optval >= 18445);
1309
1310             /*
1311              * Test if SCTP doesn't partially deliver below max record size
1312              * (2^14 + 2048 + 13)
1313              */
1314             optlen = (socklen_t) sizeof(int);
1315             ret =
1316                 getsockopt(b->num, IPPROTO_SCTP, SCTP_PARTIAL_DELIVERY_POINT,
1317                            &optval, &optlen);
1318             if (ret >= 0)
1319                 OPENSSL_assert(optval >= 18445);
1320
1321             /*
1322              * Partially delivered notification??? Probably a bug....
1323              */
1324             OPENSSL_assert(!(msg.msg_flags & MSG_NOTIFICATION));
1325
1326             /*
1327              * Everything seems ok till now, so it's most likely a message
1328              * dropped by PR-SCTP.
1329              */
1330             memset(out, 0, outl);
1331             BIO_set_retry_read(b);
1332             return -1;
1333         }
1334
1335         BIO_clear_retry_flags(b);
1336         if (ret < 0) {
1337             if (BIO_dgram_should_retry(ret)) {
1338                 BIO_set_retry_read(b);
1339                 data->_errno = get_last_socket_error();
1340             }
1341         }
1342
1343         /* Test if peer uses SCTP-AUTH before continuing */
1344         if (!data->peer_auth_tested) {
1345             int ii, auth_data = 0, auth_forward = 0;
1346             unsigned char *p;
1347             struct sctp_authchunks *authchunks;
1348
1349             optlen =
1350                 (socklen_t) (sizeof(sctp_assoc_t) + 256 * sizeof(uint8_t));
1351             authchunks = OPENSSL_malloc(optlen);
1352             memset(authchunks, 0, optlen);
1353             ii = getsockopt(b->num, IPPROTO_SCTP, SCTP_PEER_AUTH_CHUNKS,
1354                             authchunks, &optlen);
1355
1356             if (ii >= 0)
1357                 for (p = (unsigned char *)authchunks->gauth_chunks;
1358                      p < (unsigned char *)authchunks + optlen;
1359                      p += sizeof(uint8_t)) {
1360                     if (*p == OPENSSL_SCTP_DATA_CHUNK_TYPE)
1361                         auth_data = 1;
1362                     if (*p == OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE)
1363                         auth_forward = 1;
1364                 }
1365
1366             OPENSSL_free(authchunks);
1367
1368             if (!auth_data || !auth_forward) {
1369                 BIOerr(BIO_F_DGRAM_SCTP_READ, BIO_R_CONNECT_ERROR);
1370                 return -1;
1371             }
1372
1373             data->peer_auth_tested = 1;
1374         }
1375     }
1376     return (ret);
1377 }
1378
1379 static int dgram_sctp_write(BIO *b, const char *in, int inl)
1380 {
1381     int ret;
1382     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
1383     struct bio_dgram_sctp_sndinfo *sinfo = &(data->sndinfo);
1384     struct bio_dgram_sctp_prinfo *pinfo = &(data->prinfo);
1385     struct bio_dgram_sctp_sndinfo handshake_sinfo;
1386     struct iovec iov[1];
1387     struct msghdr msg;
1388     struct cmsghdr *cmsg;
1389 #  if defined(SCTP_SNDINFO) && defined(SCTP_PRINFO)
1390     char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndinfo)) +
1391                  CMSG_SPACE(sizeof(struct sctp_prinfo))];
1392     struct sctp_sndinfo *sndinfo;
1393     struct sctp_prinfo *prinfo;
1394 #  else
1395     char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndrcvinfo))];
1396     struct sctp_sndrcvinfo *sndrcvinfo;
1397 #  endif
1398
1399     clear_socket_error();
1400
1401     /*
1402      * If we're send anything else than application data, disable all user
1403      * parameters and flags.
1404      */
1405     if (in[0] != 23) {
1406         memset(&handshake_sinfo, 0x00, sizeof(struct bio_dgram_sctp_sndinfo));
1407 #  ifdef SCTP_SACK_IMMEDIATELY
1408         handshake_sinfo.snd_flags = SCTP_SACK_IMMEDIATELY;
1409 #  endif
1410         sinfo = &handshake_sinfo;
1411     }
1412
1413     /*
1414      * If we have to send a shutdown alert message and the socket is not dry
1415      * yet, we have to save it and send it as soon as the socket gets dry.
1416      */
1417     if (data->save_shutdown && !BIO_dgram_sctp_wait_for_dry(b)) {
1418         data->saved_message.bio = b;
1419         if (data->saved_message.data)
1420             OPENSSL_free(data->saved_message.data);
1421         data->saved_message.data = OPENSSL_malloc(inl);
1422         memcpy(data->saved_message.data, in, inl);
1423         data->saved_message.length = inl;
1424         return inl;
1425     }
1426
1427     iov[0].iov_base = (char *)in;
1428     iov[0].iov_len = inl;
1429     msg.msg_name = NULL;
1430     msg.msg_namelen = 0;
1431     msg.msg_iov = iov;
1432     msg.msg_iovlen = 1;
1433     msg.msg_control = (caddr_t) cmsgbuf;
1434     msg.msg_controllen = 0;
1435     msg.msg_flags = 0;
1436 #  if defined(SCTP_SNDINFO) && defined(SCTP_PRINFO)
1437     cmsg = (struct cmsghdr *)cmsgbuf;
1438     cmsg->cmsg_level = IPPROTO_SCTP;
1439     cmsg->cmsg_type = SCTP_SNDINFO;
1440     cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndinfo));
1441     sndinfo = (struct sctp_sndinfo *)CMSG_DATA(cmsg);
1442     memset(sndinfo, 0, sizeof(struct sctp_sndinfo));
1443     sndinfo->snd_sid = sinfo->snd_sid;
1444     sndinfo->snd_flags = sinfo->snd_flags;
1445     sndinfo->snd_ppid = sinfo->snd_ppid;
1446     sndinfo->snd_context = sinfo->snd_context;
1447     msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_sndinfo));
1448
1449     cmsg =
1450         (struct cmsghdr *)&cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndinfo))];
1451     cmsg->cmsg_level = IPPROTO_SCTP;
1452     cmsg->cmsg_type = SCTP_PRINFO;
1453     cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_prinfo));
1454     prinfo = (struct sctp_prinfo *)CMSG_DATA(cmsg);
1455     memset(prinfo, 0, sizeof(struct sctp_prinfo));
1456     prinfo->pr_policy = pinfo->pr_policy;
1457     prinfo->pr_value = pinfo->pr_value;
1458     msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_prinfo));
1459 #  else
1460     cmsg = (struct cmsghdr *)cmsgbuf;
1461     cmsg->cmsg_level = IPPROTO_SCTP;
1462     cmsg->cmsg_type = SCTP_SNDRCV;
1463     cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
1464     sndrcvinfo = (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
1465     memset(sndrcvinfo, 0, sizeof(struct sctp_sndrcvinfo));
1466     sndrcvinfo->sinfo_stream = sinfo->snd_sid;
1467     sndrcvinfo->sinfo_flags = sinfo->snd_flags;
1468 #   ifdef __FreeBSD__
1469     sndrcvinfo->sinfo_flags |= pinfo->pr_policy;
1470 #   endif
1471     sndrcvinfo->sinfo_ppid = sinfo->snd_ppid;
1472     sndrcvinfo->sinfo_context = sinfo->snd_context;
1473     sndrcvinfo->sinfo_timetolive = pinfo->pr_value;
1474     msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_sndrcvinfo));
1475 #  endif
1476
1477     ret = sendmsg(b->num, &msg, 0);
1478
1479     BIO_clear_retry_flags(b);
1480     if (ret <= 0) {
1481         if (BIO_dgram_should_retry(ret)) {
1482             BIO_set_retry_write(b);
1483             data->_errno = get_last_socket_error();
1484         }
1485     }
1486     return (ret);
1487 }
1488
1489 static long dgram_sctp_ctrl(BIO *b, int cmd, long num, void *ptr)
1490 {
1491     long ret = 1;
1492     bio_dgram_sctp_data *data = NULL;
1493     socklen_t sockopt_len = 0;
1494     struct sctp_authkeyid authkeyid;
1495     struct sctp_authkey *authkey = NULL;
1496
1497     data = (bio_dgram_sctp_data *) b->ptr;
1498
1499     switch (cmd) {
1500     case BIO_CTRL_DGRAM_QUERY_MTU:
1501         /*
1502          * Set to maximum (2^14) and ignore user input to enable transport
1503          * protocol fragmentation. Returns always 2^14.
1504          */
1505         data->mtu = 16384;
1506         ret = data->mtu;
1507         break;
1508     case BIO_CTRL_DGRAM_SET_MTU:
1509         /*
1510          * Set to maximum (2^14) and ignore input to enable transport
1511          * protocol fragmentation. Returns always 2^14.
1512          */
1513         data->mtu = 16384;
1514         ret = data->mtu;
1515         break;
1516     case BIO_CTRL_DGRAM_SET_CONNECTED:
1517     case BIO_CTRL_DGRAM_CONNECT:
1518         /* Returns always -1. */
1519         ret = -1;
1520         break;
1521     case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
1522         /*
1523          * SCTP doesn't need the DTLS timer Returns always 1.
1524          */
1525         break;
1526     case BIO_CTRL_DGRAM_GET_MTU_OVERHEAD:
1527         /*
1528          * We allow transport protocol fragmentation so this is irrelevant
1529          */
1530         ret = 0;
1531         break;
1532     case BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE:
1533         if (num > 0)
1534             data->in_handshake = 1;
1535         else
1536             data->in_handshake = 0;
1537
1538         ret =
1539             setsockopt(b->num, IPPROTO_SCTP, SCTP_NODELAY,
1540                        &data->in_handshake, sizeof(int));
1541         break;
1542     case BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY:
1543         /*
1544          * New shared key for SCTP AUTH. Returns 0 on success, -1 otherwise.
1545          */
1546
1547         /* Get active key */
1548         sockopt_len = sizeof(struct sctp_authkeyid);
1549         ret =
1550             getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY, &authkeyid,
1551                        &sockopt_len);
1552         if (ret < 0)
1553             break;
1554
1555         /* Add new key */
1556         sockopt_len = sizeof(struct sctp_authkey) + 64 * sizeof(uint8_t);
1557         authkey = OPENSSL_malloc(sockopt_len);
1558         if (authkey == NULL) {
1559             ret = -1;
1560             break;
1561         }
1562         memset(authkey, 0x00, sockopt_len);
1563         authkey->sca_keynumber = authkeyid.scact_keynumber + 1;
1564 #  ifndef __FreeBSD__
1565         /*
1566          * This field is missing in FreeBSD 8.2 and earlier, and FreeBSD 8.3
1567          * and higher work without it.
1568          */
1569         authkey->sca_keylength = 64;
1570 #  endif
1571         memcpy(&authkey->sca_key[0], ptr, 64 * sizeof(uint8_t));
1572
1573         ret =
1574             setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_KEY, authkey,
1575                        sockopt_len);
1576         OPENSSL_free(authkey);
1577         authkey = NULL;
1578         if (ret < 0)
1579             break;
1580
1581         /* Reset active key */
1582         ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY,
1583                          &authkeyid, sizeof(struct sctp_authkeyid));
1584         if (ret < 0)
1585             break;
1586
1587         break;
1588     case BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY:
1589         /* Returns 0 on success, -1 otherwise. */
1590
1591         /* Get active key */
1592         sockopt_len = sizeof(struct sctp_authkeyid);
1593         ret =
1594             getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY, &authkeyid,
1595                        &sockopt_len);
1596         if (ret < 0)
1597             break;
1598
1599         /* Set active key */
1600         authkeyid.scact_keynumber = authkeyid.scact_keynumber + 1;
1601         ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY,
1602                          &authkeyid, sizeof(struct sctp_authkeyid));
1603         if (ret < 0)
1604             break;
1605
1606         /*
1607          * CCS has been sent, so remember that and fall through to check if
1608          * we need to deactivate an old key
1609          */
1610         data->ccs_sent = 1;
1611
1612     case BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD:
1613         /* Returns 0 on success, -1 otherwise. */
1614
1615         /*
1616          * Has this command really been called or is this just a
1617          * fall-through?
1618          */
1619         if (cmd == BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD)
1620             data->ccs_rcvd = 1;
1621
1622         /*
1623          * CSS has been both, received and sent, so deactivate an old key
1624          */
1625         if (data->ccs_rcvd == 1 && data->ccs_sent == 1) {
1626             /* Get active key */
1627             sockopt_len = sizeof(struct sctp_authkeyid);
1628             ret =
1629                 getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY,
1630                            &authkeyid, &sockopt_len);
1631             if (ret < 0)
1632                 break;
1633
1634             /*
1635              * Deactivate key or delete second last key if
1636              * SCTP_AUTHENTICATION_EVENT is not available.
1637              */
1638             authkeyid.scact_keynumber = authkeyid.scact_keynumber - 1;
1639 #  ifdef SCTP_AUTH_DEACTIVATE_KEY
1640             sockopt_len = sizeof(struct sctp_authkeyid);
1641             ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DEACTIVATE_KEY,
1642                              &authkeyid, sockopt_len);
1643             if (ret < 0)
1644                 break;
1645 #  endif
1646 #  ifndef SCTP_AUTHENTICATION_EVENT
1647             if (authkeyid.scact_keynumber > 0) {
1648                 authkeyid.scact_keynumber = authkeyid.scact_keynumber - 1;
1649                 ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DELETE_KEY,
1650                                  &authkeyid, sizeof(struct sctp_authkeyid));
1651                 if (ret < 0)
1652                     break;
1653             }
1654 #  endif
1655
1656             data->ccs_rcvd = 0;
1657             data->ccs_sent = 0;
1658         }
1659         break;
1660     case BIO_CTRL_DGRAM_SCTP_GET_SNDINFO:
1661         /* Returns the size of the copied struct. */
1662         if (num > (long)sizeof(struct bio_dgram_sctp_sndinfo))
1663             num = sizeof(struct bio_dgram_sctp_sndinfo);
1664
1665         memcpy(ptr, &(data->sndinfo), num);
1666         ret = num;
1667         break;
1668     case BIO_CTRL_DGRAM_SCTP_SET_SNDINFO:
1669         /* Returns the size of the copied struct. */
1670         if (num > (long)sizeof(struct bio_dgram_sctp_sndinfo))
1671             num = sizeof(struct bio_dgram_sctp_sndinfo);
1672
1673         memcpy(&(data->sndinfo), ptr, num);
1674         break;
1675     case BIO_CTRL_DGRAM_SCTP_GET_RCVINFO:
1676         /* Returns the size of the copied struct. */
1677         if (num > (long)sizeof(struct bio_dgram_sctp_rcvinfo))
1678             num = sizeof(struct bio_dgram_sctp_rcvinfo);
1679
1680         memcpy(ptr, &data->rcvinfo, num);
1681
1682         ret = num;
1683         break;
1684     case BIO_CTRL_DGRAM_SCTP_SET_RCVINFO:
1685         /* Returns the size of the copied struct. */
1686         if (num > (long)sizeof(struct bio_dgram_sctp_rcvinfo))
1687             num = sizeof(struct bio_dgram_sctp_rcvinfo);
1688
1689         memcpy(&(data->rcvinfo), ptr, num);
1690         break;
1691     case BIO_CTRL_DGRAM_SCTP_GET_PRINFO:
1692         /* Returns the size of the copied struct. */
1693         if (num > (long)sizeof(struct bio_dgram_sctp_prinfo))
1694             num = sizeof(struct bio_dgram_sctp_prinfo);
1695
1696         memcpy(ptr, &(data->prinfo), num);
1697         ret = num;
1698         break;
1699     case BIO_CTRL_DGRAM_SCTP_SET_PRINFO:
1700         /* Returns the size of the copied struct. */
1701         if (num > (long)sizeof(struct bio_dgram_sctp_prinfo))
1702             num = sizeof(struct bio_dgram_sctp_prinfo);
1703
1704         memcpy(&(data->prinfo), ptr, num);
1705         break;
1706     case BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN:
1707         /* Returns always 1. */
1708         if (num > 0)
1709             data->save_shutdown = 1;
1710         else
1711             data->save_shutdown = 0;
1712         break;
1713
1714     default:
1715         /*
1716          * Pass to default ctrl function to process SCTP unspecific commands
1717          */
1718         ret = dgram_ctrl(b, cmd, num, ptr);
1719         break;
1720     }
1721     return (ret);
1722 }
1723
1724 int BIO_dgram_sctp_notification_cb(BIO *b,
1725                                    void (*handle_notifications) (BIO *bio,
1726                                                                  void
1727                                                                  *context,
1728                                                                  void *buf),
1729                                    void *context)
1730 {
1731     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
1732
1733     if (handle_notifications != NULL) {
1734         data->handle_notifications = handle_notifications;
1735         data->notification_context = context;
1736     } else
1737         return -1;
1738
1739     return 0;
1740 }
1741
1742 int BIO_dgram_sctp_wait_for_dry(BIO *b)
1743 {
1744     int is_dry = 0;
1745     int n, sockflags, ret;
1746     union sctp_notification snp;
1747     struct msghdr msg;
1748     struct iovec iov;
1749 #  ifdef SCTP_EVENT
1750     struct sctp_event event;
1751 #  else
1752     struct sctp_event_subscribe event;
1753     socklen_t eventsize;
1754 #  endif
1755     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
1756
1757     /* set sender dry event */
1758 #  ifdef SCTP_EVENT
1759     memset(&event, 0, sizeof(struct sctp_event));
1760     event.se_assoc_id = 0;
1761     event.se_type = SCTP_SENDER_DRY_EVENT;
1762     event.se_on = 1;
1763     ret =
1764         setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event,
1765                    sizeof(struct sctp_event));
1766 #  else
1767     eventsize = sizeof(struct sctp_event_subscribe);
1768     ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, &eventsize);
1769     if (ret < 0)
1770         return -1;
1771
1772     event.sctp_sender_dry_event = 1;
1773
1774     ret =
1775         setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
1776                    sizeof(struct sctp_event_subscribe));
1777 #  endif
1778     if (ret < 0)
1779         return -1;
1780
1781     /* peek for notification */
1782     memset(&snp, 0x00, sizeof(union sctp_notification));
1783     iov.iov_base = (char *)&snp;
1784     iov.iov_len = sizeof(union sctp_notification);
1785     msg.msg_name = NULL;
1786     msg.msg_namelen = 0;
1787     msg.msg_iov = &iov;
1788     msg.msg_iovlen = 1;
1789     msg.msg_control = NULL;
1790     msg.msg_controllen = 0;
1791     msg.msg_flags = 0;
1792
1793     n = recvmsg(b->num, &msg, MSG_PEEK);
1794     if (n <= 0) {
1795         if ((n < 0) && (get_last_socket_error() != EAGAIN)
1796             && (get_last_socket_error() != EWOULDBLOCK))
1797             return -1;
1798         else
1799             return 0;
1800     }
1801
1802     /* if we find a notification, process it and try again if necessary */
1803     while (msg.msg_flags & MSG_NOTIFICATION) {
1804         memset(&snp, 0x00, sizeof(union sctp_notification));
1805         iov.iov_base = (char *)&snp;
1806         iov.iov_len = sizeof(union sctp_notification);
1807         msg.msg_name = NULL;
1808         msg.msg_namelen = 0;
1809         msg.msg_iov = &iov;
1810         msg.msg_iovlen = 1;
1811         msg.msg_control = NULL;
1812         msg.msg_controllen = 0;
1813         msg.msg_flags = 0;
1814
1815         n = recvmsg(b->num, &msg, 0);
1816         if (n <= 0) {
1817             if ((n < 0) && (get_last_socket_error() != EAGAIN)
1818                 && (get_last_socket_error() != EWOULDBLOCK))
1819                 return -1;
1820             else
1821                 return is_dry;
1822         }
1823
1824         if (snp.sn_header.sn_type == SCTP_SENDER_DRY_EVENT) {
1825             is_dry = 1;
1826
1827             /* disable sender dry event */
1828 #  ifdef SCTP_EVENT
1829             memset(&event, 0, sizeof(struct sctp_event));
1830             event.se_assoc_id = 0;
1831             event.se_type = SCTP_SENDER_DRY_EVENT;
1832             event.se_on = 0;
1833             ret =
1834                 setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event,
1835                            sizeof(struct sctp_event));
1836 #  else
1837             eventsize = (socklen_t) sizeof(struct sctp_event_subscribe);
1838             ret =
1839                 getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
1840                            &eventsize);
1841             if (ret < 0)
1842                 return -1;
1843
1844             event.sctp_sender_dry_event = 0;
1845
1846             ret =
1847                 setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
1848                            sizeof(struct sctp_event_subscribe));
1849 #  endif
1850             if (ret < 0)
1851                 return -1;
1852         }
1853 #  ifdef SCTP_AUTHENTICATION_EVENT
1854         if (snp.sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
1855             dgram_sctp_handle_auth_free_key_event(b, &snp);
1856 #  endif
1857
1858         if (data->handle_notifications != NULL)
1859             data->handle_notifications(b, data->notification_context,
1860                                        (void *)&snp);
1861
1862         /* found notification, peek again */
1863         memset(&snp, 0x00, sizeof(union sctp_notification));
1864         iov.iov_base = (char *)&snp;
1865         iov.iov_len = sizeof(union sctp_notification);
1866         msg.msg_name = NULL;
1867         msg.msg_namelen = 0;
1868         msg.msg_iov = &iov;
1869         msg.msg_iovlen = 1;
1870         msg.msg_control = NULL;
1871         msg.msg_controllen = 0;
1872         msg.msg_flags = 0;
1873
1874         /* if we have seen the dry already, don't wait */
1875         if (is_dry) {
1876             sockflags = fcntl(b->num, F_GETFL, 0);
1877             fcntl(b->num, F_SETFL, O_NONBLOCK);
1878         }
1879
1880         n = recvmsg(b->num, &msg, MSG_PEEK);
1881
1882         if (is_dry) {
1883             fcntl(b->num, F_SETFL, sockflags);
1884         }
1885
1886         if (n <= 0) {
1887             if ((n < 0) && (get_last_socket_error() != EAGAIN)
1888                 && (get_last_socket_error() != EWOULDBLOCK))
1889                 return -1;
1890             else
1891                 return is_dry;
1892         }
1893     }
1894
1895     /* read anything else */
1896     return is_dry;
1897 }
1898
1899 int BIO_dgram_sctp_msg_waiting(BIO *b)
1900 {
1901     int n, sockflags;
1902     union sctp_notification snp;
1903     struct msghdr msg;
1904     struct iovec iov;
1905     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
1906
1907     /* Check if there are any messages waiting to be read */
1908     do {
1909         memset(&snp, 0x00, sizeof(union sctp_notification));
1910         iov.iov_base = (char *)&snp;
1911         iov.iov_len = sizeof(union sctp_notification);
1912         msg.msg_name = NULL;
1913         msg.msg_namelen = 0;
1914         msg.msg_iov = &iov;
1915         msg.msg_iovlen = 1;
1916         msg.msg_control = NULL;
1917         msg.msg_controllen = 0;
1918         msg.msg_flags = 0;
1919
1920         sockflags = fcntl(b->num, F_GETFL, 0);
1921         fcntl(b->num, F_SETFL, O_NONBLOCK);
1922         n = recvmsg(b->num, &msg, MSG_PEEK);
1923         fcntl(b->num, F_SETFL, sockflags);
1924
1925         /* if notification, process and try again */
1926         if (n > 0 && (msg.msg_flags & MSG_NOTIFICATION)) {
1927 #  ifdef SCTP_AUTHENTICATION_EVENT
1928             if (snp.sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
1929                 dgram_sctp_handle_auth_free_key_event(b, &snp);
1930 #  endif
1931
1932             memset(&snp, 0x00, sizeof(union sctp_notification));
1933             iov.iov_base = (char *)&snp;
1934             iov.iov_len = sizeof(union sctp_notification);
1935             msg.msg_name = NULL;
1936             msg.msg_namelen = 0;
1937             msg.msg_iov = &iov;
1938             msg.msg_iovlen = 1;
1939             msg.msg_control = NULL;
1940             msg.msg_controllen = 0;
1941             msg.msg_flags = 0;
1942             n = recvmsg(b->num, &msg, 0);
1943
1944             if (data->handle_notifications != NULL)
1945                 data->handle_notifications(b, data->notification_context,
1946                                            (void *)&snp);
1947         }
1948
1949     } while (n > 0 && (msg.msg_flags & MSG_NOTIFICATION));
1950
1951     /* Return 1 if there is a message to be read, return 0 otherwise. */
1952     if (n > 0)
1953         return 1;
1954     else
1955         return 0;
1956 }
1957
1958 static int dgram_sctp_puts(BIO *bp, const char *str)
1959 {
1960     int n, ret;
1961
1962     n = strlen(str);
1963     ret = dgram_sctp_write(bp, str, n);
1964     return (ret);
1965 }
1966 # endif
1967
1968 static int BIO_dgram_should_retry(int i)
1969 {
1970     int err;
1971
1972     if ((i == 0) || (i == -1)) {
1973         err = get_last_socket_error();
1974
1975 # if defined(OPENSSL_SYS_WINDOWS)
1976         /*
1977          * If the socket return value (i) is -1 and err is unexpectedly 0 at
1978          * this point, the error code was overwritten by another system call
1979          * before this error handling is called.
1980          */
1981 # endif
1982
1983         return (BIO_dgram_non_fatal_error(err));
1984     }
1985     return (0);
1986 }
1987
1988 int BIO_dgram_non_fatal_error(int err)
1989 {
1990     switch (err) {
1991 # if defined(OPENSSL_SYS_WINDOWS)
1992 #  if defined(WSAEWOULDBLOCK)
1993     case WSAEWOULDBLOCK:
1994 #  endif
1995
1996 #  if 0                         /* This appears to always be an error */
1997 #   if defined(WSAENOTCONN)
1998     case WSAENOTCONN:
1999 #   endif
2000 #  endif
2001 # endif
2002
2003 # ifdef EWOULDBLOCK
2004 #  ifdef WSAEWOULDBLOCK
2005 #   if WSAEWOULDBLOCK != EWOULDBLOCK
2006     case EWOULDBLOCK:
2007 #   endif
2008 #  else
2009     case EWOULDBLOCK:
2010 #  endif
2011 # endif
2012
2013 # ifdef EINTR
2014     case EINTR:
2015 # endif
2016
2017 # ifdef EAGAIN
2018 #  if EWOULDBLOCK != EAGAIN
2019     case EAGAIN:
2020 #  endif
2021 # endif
2022
2023 # ifdef EPROTO
2024     case EPROTO:
2025 # endif
2026
2027 # ifdef EINPROGRESS
2028     case EINPROGRESS:
2029 # endif
2030
2031 # ifdef EALREADY
2032     case EALREADY:
2033 # endif
2034
2035         return (1);
2036         /* break; */
2037     default:
2038         break;
2039     }
2040     return (0);
2041 }
2042
2043 static void get_current_time(struct timeval *t)
2044 {
2045 # if defined(_WIN32)
2046     SYSTEMTIME st;
2047     union {
2048         unsigned __int64 ul;
2049         FILETIME ft;
2050     } now;
2051
2052     GetSystemTime(&st);
2053     SystemTimeToFileTime(&st, &now.ft);
2054 #  ifdef  __MINGW32__
2055     now.ul -= 116444736000000000ULL;
2056 #  else
2057     now.ul -= 116444736000000000UI64; /* re-bias to 1/1/1970 */
2058 #  endif
2059     t->tv_sec = (long)(now.ul / 10000000);
2060     t->tv_usec = ((int)(now.ul % 10000000)) / 10;
2061 # elif defined(OPENSSL_SYS_VMS)
2062     struct timeb tb;
2063     ftime(&tb);
2064     t->tv_sec = (long)tb.time;
2065     t->tv_usec = (long)tb.millitm * 1000;
2066 # else
2067     gettimeofday(t, NULL);
2068 # endif
2069 }
2070
2071 #endif