Dead code removal: #if 0 bio, comp, rand
[oweals/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     }
454     return (ret);
455 }
456
457 static long dgram_get_mtu_overhead(bio_dgram_data *data)
458 {
459     long ret;
460
461     switch (data->peer.sa.sa_family) {
462     case AF_INET:
463         /*
464          * Assume this is UDP - 20 bytes for IP, 8 bytes for UDP
465          */
466         ret = 28;
467         break;
468 # if OPENSSL_USE_IPV6
469     case AF_INET6:
470 #  ifdef IN6_IS_ADDR_V4MAPPED
471         if (IN6_IS_ADDR_V4MAPPED(&data->peer.sa_in6.sin6_addr))
472             /*
473              * Assume this is UDP - 20 bytes for IP, 8 bytes for UDP
474              */
475             ret = 28;
476         else
477 #  endif
478             /*
479              * Assume this is UDP - 40 bytes for IP, 8 bytes for UDP
480              */
481             ret = 48;
482         break;
483 # endif
484     default:
485         /* We don't know. Go with the historical default */
486         ret = 28;
487         break;
488     }
489     return ret;
490 }
491
492 static long dgram_ctrl(BIO *b, int cmd, long num, void *ptr)
493 {
494     long ret = 1;
495     int *ip;
496     struct sockaddr *to = NULL;
497     bio_dgram_data *data = NULL;
498     int sockopt_val = 0;
499 # if defined(OPENSSL_SYS_LINUX) && (defined(IP_MTU_DISCOVER) || defined(IP_MTU))
500     socklen_t sockopt_len;      /* assume that system supporting IP_MTU is
501                                  * modern enough to define socklen_t */
502     socklen_t addr_len;
503     union {
504         struct sockaddr sa;
505         struct sockaddr_in s4;
506 #  if OPENSSL_USE_IPV6
507         struct sockaddr_in6 s6;
508 #  endif
509     } addr;
510 # endif
511
512     data = (bio_dgram_data *)b->ptr;
513
514     switch (cmd) {
515     case BIO_CTRL_RESET:
516         num = 0;
517     case BIO_C_FILE_SEEK:
518         ret = 0;
519         break;
520     case BIO_C_FILE_TELL:
521     case BIO_CTRL_INFO:
522         ret = 0;
523         break;
524     case BIO_C_SET_FD:
525         dgram_clear(b);
526         b->num = *((int *)ptr);
527         b->shutdown = (int)num;
528         b->init = 1;
529         break;
530     case BIO_C_GET_FD:
531         if (b->init) {
532             ip = (int *)ptr;
533             if (ip != NULL)
534                 *ip = b->num;
535             ret = b->num;
536         } else
537             ret = -1;
538         break;
539     case BIO_CTRL_GET_CLOSE:
540         ret = b->shutdown;
541         break;
542     case BIO_CTRL_SET_CLOSE:
543         b->shutdown = (int)num;
544         break;
545     case BIO_CTRL_PENDING:
546     case BIO_CTRL_WPENDING:
547         ret = 0;
548         break;
549     case BIO_CTRL_DUP:
550     case BIO_CTRL_FLUSH:
551         ret = 1;
552         break;
553     case BIO_CTRL_DGRAM_CONNECT:
554         to = (struct sockaddr *)ptr;
555         switch (to->sa_family) {
556         case AF_INET:
557             memcpy(&data->peer, to, sizeof(data->peer.sa_in));
558             break;
559 # if OPENSSL_USE_IPV6
560         case AF_INET6:
561             memcpy(&data->peer, to, sizeof(data->peer.sa_in6));
562             break;
563 # endif
564         default:
565             memcpy(&data->peer, to, sizeof(data->peer.sa));
566             break;
567         }
568         break;
569         /* (Linux)kernel sets DF bit on outgoing IP packets */
570     case BIO_CTRL_DGRAM_MTU_DISCOVER:
571 # if defined(OPENSSL_SYS_LINUX) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
572         addr_len = (socklen_t) sizeof(addr);
573         memset((void *)&addr, 0, sizeof(addr));
574         if (getsockname(b->num, &addr.sa, &addr_len) < 0) {
575             ret = 0;
576             break;
577         }
578         switch (addr.sa.sa_family) {
579         case AF_INET:
580             sockopt_val = IP_PMTUDISC_DO;
581             if ((ret = setsockopt(b->num, IPPROTO_IP, IP_MTU_DISCOVER,
582                                   &sockopt_val, sizeof(sockopt_val))) < 0)
583                 perror("setsockopt");
584             break;
585 #  if OPENSSL_USE_IPV6 && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
586         case AF_INET6:
587             sockopt_val = IPV6_PMTUDISC_DO;
588             if ((ret = setsockopt(b->num, IPPROTO_IPV6, IPV6_MTU_DISCOVER,
589                                   &sockopt_val, sizeof(sockopt_val))) < 0)
590                 perror("setsockopt");
591             break;
592 #  endif
593         default:
594             ret = -1;
595             break;
596         }
597 # else
598         ret = -1;
599 # endif
600         break;
601     case BIO_CTRL_DGRAM_QUERY_MTU:
602 # if defined(OPENSSL_SYS_LINUX) && defined(IP_MTU)
603         addr_len = (socklen_t) sizeof(addr);
604         memset((void *)&addr, 0, sizeof(addr));
605         if (getsockname(b->num, &addr.sa, &addr_len) < 0) {
606             ret = 0;
607             break;
608         }
609         sockopt_len = sizeof(sockopt_val);
610         switch (addr.sa.sa_family) {
611         case AF_INET:
612             if ((ret =
613                  getsockopt(b->num, IPPROTO_IP, IP_MTU, (void *)&sockopt_val,
614                             &sockopt_len)) < 0 || sockopt_val < 0) {
615                 ret = 0;
616             } else {
617                 /*
618                  * we assume that the transport protocol is UDP and no IP
619                  * options are used.
620                  */
621                 data->mtu = sockopt_val - 8 - 20;
622                 ret = data->mtu;
623             }
624             break;
625 #  if OPENSSL_USE_IPV6 && defined(IPV6_MTU)
626         case AF_INET6:
627             if ((ret =
628                  getsockopt(b->num, IPPROTO_IPV6, IPV6_MTU,
629                             (void *)&sockopt_val, &sockopt_len)) < 0
630                 || sockopt_val < 0) {
631                 ret = 0;
632             } else {
633                 /*
634                  * we assume that the transport protocol is UDP and no IPV6
635                  * options are used.
636                  */
637                 data->mtu = sockopt_val - 8 - 40;
638                 ret = data->mtu;
639             }
640             break;
641 #  endif
642         default:
643             ret = 0;
644             break;
645         }
646 # else
647         ret = 0;
648 # endif
649         break;
650     case BIO_CTRL_DGRAM_GET_FALLBACK_MTU:
651         ret = -dgram_get_mtu_overhead(data);
652         switch (data->peer.sa.sa_family) {
653         case AF_INET:
654             ret += 576;
655             break;
656 # if OPENSSL_USE_IPV6
657         case AF_INET6:
658 #  ifdef IN6_IS_ADDR_V4MAPPED
659             if (IN6_IS_ADDR_V4MAPPED(&data->peer.sa_in6.sin6_addr))
660                 ret += 576;
661             else
662 #  endif
663                 ret += 1280;
664             break;
665 # endif
666         default:
667             ret += 576;
668             break;
669         }
670         break;
671     case BIO_CTRL_DGRAM_GET_MTU:
672         return data->mtu;
673     case BIO_CTRL_DGRAM_SET_MTU:
674         data->mtu = num;
675         ret = num;
676         break;
677     case BIO_CTRL_DGRAM_SET_CONNECTED:
678         to = (struct sockaddr *)ptr;
679
680         if (to != NULL) {
681             data->connected = 1;
682             switch (to->sa_family) {
683             case AF_INET:
684                 memcpy(&data->peer, to, sizeof(data->peer.sa_in));
685                 break;
686 # if OPENSSL_USE_IPV6
687             case AF_INET6:
688                 memcpy(&data->peer, to, sizeof(data->peer.sa_in6));
689                 break;
690 # endif
691             default:
692                 memcpy(&data->peer, to, sizeof(data->peer.sa));
693                 break;
694             }
695         } else {
696             data->connected = 0;
697             memset(&(data->peer), 0x00, sizeof(data->peer));
698         }
699         break;
700     case BIO_CTRL_DGRAM_GET_PEER:
701         switch (data->peer.sa.sa_family) {
702         case AF_INET:
703             ret = sizeof(data->peer.sa_in);
704             break;
705 # if OPENSSL_USE_IPV6
706         case AF_INET6:
707             ret = sizeof(data->peer.sa_in6);
708             break;
709 # endif
710         default:
711             ret = sizeof(data->peer.sa);
712             break;
713         }
714         if (num == 0 || num > ret)
715             num = ret;
716         memcpy(ptr, &data->peer, (ret = num));
717         break;
718     case BIO_CTRL_DGRAM_SET_PEER:
719         to = (struct sockaddr *)ptr;
720         switch (to->sa_family) {
721         case AF_INET:
722             memcpy(&data->peer, to, sizeof(data->peer.sa_in));
723             break;
724 # if OPENSSL_USE_IPV6
725         case AF_INET6:
726             memcpy(&data->peer, to, sizeof(data->peer.sa_in6));
727             break;
728 # endif
729         default:
730             memcpy(&data->peer, to, sizeof(data->peer.sa));
731             break;
732         }
733         break;
734     case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
735         memcpy(&(data->next_timeout), ptr, sizeof(struct timeval));
736         break;
737 # if defined(SO_RCVTIMEO)
738     case BIO_CTRL_DGRAM_SET_RECV_TIMEOUT:
739 #  ifdef OPENSSL_SYS_WINDOWS
740         {
741             struct timeval *tv = (struct timeval *)ptr;
742             int timeout = tv->tv_sec * 1000 + tv->tv_usec / 1000;
743             if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
744                            (void *)&timeout, sizeof(timeout)) < 0) {
745                 perror("setsockopt");
746                 ret = -1;
747             }
748         }
749 #  else
750         if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, ptr,
751                        sizeof(struct timeval)) < 0) {
752             perror("setsockopt");
753             ret = -1;
754         }
755 #  endif
756         break;
757     case BIO_CTRL_DGRAM_GET_RECV_TIMEOUT:
758         {
759             union {
760                 size_t s;
761                 int i;
762             } sz = {
763                 0
764             };
765 #  ifdef OPENSSL_SYS_WINDOWS
766             int timeout;
767             struct timeval *tv = (struct timeval *)ptr;
768
769             sz.i = sizeof(timeout);
770             if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
771                            (void *)&timeout, &sz.i) < 0) {
772                 perror("getsockopt");
773                 ret = -1;
774             } else {
775                 tv->tv_sec = timeout / 1000;
776                 tv->tv_usec = (timeout % 1000) * 1000;
777                 ret = sizeof(*tv);
778             }
779 #  else
780             sz.i = sizeof(struct timeval);
781             if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
782                            ptr, (void *)&sz) < 0) {
783                 perror("getsockopt");
784                 ret = -1;
785             } else if (sizeof(sz.s) != sizeof(sz.i) && sz.i == 0) {
786                 OPENSSL_assert(sz.s <= sizeof(struct timeval));
787                 ret = (int)sz.s;
788             } else
789                 ret = sz.i;
790 #  endif
791         }
792         break;
793 # endif
794 # if defined(SO_SNDTIMEO)
795     case BIO_CTRL_DGRAM_SET_SEND_TIMEOUT:
796 #  ifdef OPENSSL_SYS_WINDOWS
797         {
798             struct timeval *tv = (struct timeval *)ptr;
799             int timeout = tv->tv_sec * 1000 + tv->tv_usec / 1000;
800             if (setsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
801                            (void *)&timeout, sizeof(timeout)) < 0) {
802                 perror("setsockopt");
803                 ret = -1;
804             }
805         }
806 #  else
807         if (setsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO, ptr,
808                        sizeof(struct timeval)) < 0) {
809             perror("setsockopt");
810             ret = -1;
811         }
812 #  endif
813         break;
814     case BIO_CTRL_DGRAM_GET_SEND_TIMEOUT:
815         {
816             union {
817                 size_t s;
818                 int i;
819             } sz = {
820                 0
821             };
822 #  ifdef OPENSSL_SYS_WINDOWS
823             int timeout;
824             struct timeval *tv = (struct timeval *)ptr;
825
826             sz.i = sizeof(timeout);
827             if (getsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
828                            (void *)&timeout, &sz.i) < 0) {
829                 perror("getsockopt");
830                 ret = -1;
831             } else {
832                 tv->tv_sec = timeout / 1000;
833                 tv->tv_usec = (timeout % 1000) * 1000;
834                 ret = sizeof(*tv);
835             }
836 #  else
837             sz.i = sizeof(struct timeval);
838             if (getsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
839                            ptr, (void *)&sz) < 0) {
840                 perror("getsockopt");
841                 ret = -1;
842             } else if (sizeof(sz.s) != sizeof(sz.i) && sz.i == 0) {
843                 OPENSSL_assert(sz.s <= sizeof(struct timeval));
844                 ret = (int)sz.s;
845             } else
846                 ret = sz.i;
847 #  endif
848         }
849         break;
850 # endif
851     case BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP:
852         /* fall-through */
853     case BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP:
854 # ifdef OPENSSL_SYS_WINDOWS
855         if (data->_errno == WSAETIMEDOUT)
856 # else
857         if (data->_errno == EAGAIN)
858 # endif
859         {
860             ret = 1;
861             data->_errno = 0;
862         } else
863             ret = 0;
864         break;
865 # ifdef EMSGSIZE
866     case BIO_CTRL_DGRAM_MTU_EXCEEDED:
867         if (data->_errno == EMSGSIZE) {
868             ret = 1;
869             data->_errno = 0;
870         } else
871             ret = 0;
872         break;
873 # endif
874     case BIO_CTRL_DGRAM_SET_DONT_FRAG:
875         sockopt_val = num ? 1 : 0;
876
877         switch (data->peer.sa.sa_family) {
878         case AF_INET:
879 # if defined(IP_DONTFRAG)
880             if ((ret = setsockopt(b->num, IPPROTO_IP, IP_DONTFRAG,
881                                   &sockopt_val, sizeof(sockopt_val))) < 0) {
882                 perror("setsockopt");
883                 ret = -1;
884             }
885 # elif defined(OPENSSL_SYS_LINUX) && defined(IP_MTUDISCOVER)
886             if ((sockopt_val = num ? IP_PMTUDISC_PROBE : IP_PMTUDISC_DONT),
887                 (ret = setsockopt(b->num, IPPROTO_IP, IP_MTU_DISCOVER,
888                                   &sockopt_val, sizeof(sockopt_val))) < 0) {
889                 perror("setsockopt");
890                 ret = -1;
891             }
892 # elif defined(OPENSSL_SYS_WINDOWS) && defined(IP_DONTFRAGMENT)
893             if ((ret = setsockopt(b->num, IPPROTO_IP, IP_DONTFRAGMENT,
894                                   (const char *)&sockopt_val,
895                                   sizeof(sockopt_val))) < 0) {
896                 perror("setsockopt");
897                 ret = -1;
898             }
899 # else
900             ret = -1;
901 # endif
902             break;
903 # if OPENSSL_USE_IPV6
904         case AF_INET6:
905 #  if defined(IPV6_DONTFRAG)
906             if ((ret = setsockopt(b->num, IPPROTO_IPV6, IPV6_DONTFRAG,
907                                   (const void *)&sockopt_val,
908                                   sizeof(sockopt_val))) < 0) {
909                 perror("setsockopt");
910                 ret = -1;
911             }
912 #  elif defined(OPENSSL_SYS_LINUX) && defined(IPV6_MTUDISCOVER)
913             if ((sockopt_val = num ? IP_PMTUDISC_PROBE : IP_PMTUDISC_DONT),
914                 (ret = setsockopt(b->num, IPPROTO_IPV6, IPV6_MTU_DISCOVER,
915                                   &sockopt_val, sizeof(sockopt_val))) < 0) {
916                 perror("setsockopt");
917                 ret = -1;
918             }
919 #  else
920             ret = -1;
921 #  endif
922             break;
923 # endif
924         default:
925             ret = -1;
926             break;
927         }
928         break;
929     case BIO_CTRL_DGRAM_GET_MTU_OVERHEAD:
930         ret = dgram_get_mtu_overhead(data);
931         break;
932     default:
933         ret = 0;
934         break;
935     }
936     return (ret);
937 }
938
939 static int dgram_puts(BIO *bp, const char *str)
940 {
941     int n, ret;
942
943     n = strlen(str);
944     ret = dgram_write(bp, str, n);
945     return (ret);
946 }
947
948 # ifndef OPENSSL_NO_SCTP
949 BIO_METHOD *BIO_s_datagram_sctp(void)
950 {
951     return (&methods_dgramp_sctp);
952 }
953
954 BIO *BIO_new_dgram_sctp(int fd, int close_flag)
955 {
956     BIO *bio;
957     int ret, optval = 20000;
958     int auth_data = 0, auth_forward = 0;
959     unsigned char *p;
960     struct sctp_authchunk auth;
961     struct sctp_authchunks *authchunks;
962     socklen_t sockopt_len;
963 #  ifdef SCTP_AUTHENTICATION_EVENT
964 #   ifdef SCTP_EVENT
965     struct sctp_event event;
966 #   else
967     struct sctp_event_subscribe event;
968 #   endif
969 #  endif
970
971     bio = BIO_new(BIO_s_datagram_sctp());
972     if (bio == NULL)
973         return (NULL);
974     BIO_set_fd(bio, fd, close_flag);
975
976     /* Activate SCTP-AUTH for DATA and FORWARD-TSN chunks */
977     auth.sauth_chunk = OPENSSL_SCTP_DATA_CHUNK_TYPE;
978     ret =
979         setsockopt(fd, IPPROTO_SCTP, SCTP_AUTH_CHUNK, &auth,
980                    sizeof(struct sctp_authchunk));
981     if (ret < 0) {
982         BIO_vfree(bio);
983         return (NULL);
984     }
985     auth.sauth_chunk = OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE;
986     ret =
987         setsockopt(fd, IPPROTO_SCTP, SCTP_AUTH_CHUNK, &auth,
988                    sizeof(struct sctp_authchunk));
989     if (ret < 0) {
990         BIO_vfree(bio);
991         return (NULL);
992     }
993
994     /*
995      * Test if activation was successful. When using accept(), SCTP-AUTH has
996      * to be activated for the listening socket already, otherwise the
997      * connected socket won't use it.
998      */
999     sockopt_len = (socklen_t) (sizeof(sctp_assoc_t) + 256 * sizeof(uint8_t));
1000     authchunks = OPENSSL_malloc(sockopt_len);
1001     memset(authchunks, 0, sockopt_len);
1002     ret =
1003         getsockopt(fd, IPPROTO_SCTP, SCTP_LOCAL_AUTH_CHUNKS, authchunks,
1004                    &sockopt_len);
1005
1006     if (ret < 0) {
1007         OPENSSL_free(authchunks);
1008         BIO_vfree(bio);
1009         return (NULL);
1010     }
1011
1012     for (p = (unsigned char *)authchunks->gauth_chunks;
1013          p < (unsigned char *)authchunks + sockopt_len;
1014          p += sizeof(uint8_t)) {
1015         if (*p == OPENSSL_SCTP_DATA_CHUNK_TYPE)
1016             auth_data = 1;
1017         if (*p == OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE)
1018             auth_forward = 1;
1019     }
1020
1021     OPENSSL_free(authchunks);
1022
1023     OPENSSL_assert(auth_data);
1024     OPENSSL_assert(auth_forward);
1025
1026 #  ifdef SCTP_AUTHENTICATION_EVENT
1027 #   ifdef SCTP_EVENT
1028     memset(&event, 0, sizeof(struct sctp_event));
1029     event.se_assoc_id = 0;
1030     event.se_type = SCTP_AUTHENTICATION_EVENT;
1031     event.se_on = 1;
1032     ret =
1033         setsockopt(fd, IPPROTO_SCTP, SCTP_EVENT, &event,
1034                    sizeof(struct sctp_event));
1035     if (ret < 0) {
1036         BIO_vfree(bio);
1037         return (NULL);
1038     }
1039 #   else
1040     sockopt_len = (socklen_t) sizeof(struct sctp_event_subscribe);
1041     ret = getsockopt(fd, IPPROTO_SCTP, SCTP_EVENTS, &event, &sockopt_len);
1042     if (ret < 0) {
1043         BIO_vfree(bio);
1044         return (NULL);
1045     }
1046
1047     event.sctp_authentication_event = 1;
1048
1049     ret =
1050         setsockopt(fd, IPPROTO_SCTP, SCTP_EVENTS, &event,
1051                    sizeof(struct sctp_event_subscribe));
1052     if (ret < 0) {
1053         BIO_vfree(bio);
1054         return (NULL);
1055     }
1056 #   endif
1057 #  endif
1058
1059     /*
1060      * Disable partial delivery by setting the min size larger than the max
1061      * record size of 2^14 + 2048 + 13
1062      */
1063     ret =
1064         setsockopt(fd, IPPROTO_SCTP, SCTP_PARTIAL_DELIVERY_POINT, &optval,
1065                    sizeof(optval));
1066     if (ret < 0) {
1067         BIO_vfree(bio);
1068         return (NULL);
1069     }
1070
1071     return (bio);
1072 }
1073
1074 int BIO_dgram_is_sctp(BIO *bio)
1075 {
1076     return (BIO_method_type(bio) == BIO_TYPE_DGRAM_SCTP);
1077 }
1078
1079 static int dgram_sctp_new(BIO *bi)
1080 {
1081     bio_dgram_sctp_data *data = NULL;
1082
1083     bi->init = 0;
1084     bi->num = 0;
1085     data = OPENSSL_malloc(sizeof(bio_dgram_sctp_data));
1086     if (data == NULL)
1087         return 0;
1088     memset(data, 0x00, sizeof(bio_dgram_sctp_data));
1089 #  ifdef SCTP_PR_SCTP_NONE
1090     data->prinfo.pr_policy = SCTP_PR_SCTP_NONE;
1091 #  endif
1092     bi->ptr = data;
1093
1094     bi->flags = 0;
1095     return (1);
1096 }
1097
1098 static int dgram_sctp_free(BIO *a)
1099 {
1100     bio_dgram_sctp_data *data;
1101
1102     if (a == NULL)
1103         return (0);
1104     if (!dgram_clear(a))
1105         return 0;
1106
1107     data = (bio_dgram_sctp_data *) a->ptr;
1108     if (data != NULL) {
1109         if (data->saved_message.data != NULL)
1110             OPENSSL_free(data->saved_message.data);
1111         OPENSSL_free(data);
1112     }
1113
1114     return (1);
1115 }
1116
1117 #  ifdef SCTP_AUTHENTICATION_EVENT
1118 void dgram_sctp_handle_auth_free_key_event(BIO *b,
1119                                            union sctp_notification *snp)
1120 {
1121     int ret;
1122     struct sctp_authkey_event *authkeyevent = &snp->sn_auth_event;
1123
1124     if (authkeyevent->auth_indication == SCTP_AUTH_FREE_KEY) {
1125         struct sctp_authkeyid authkeyid;
1126
1127         /* delete key */
1128         authkeyid.scact_keynumber = authkeyevent->auth_keynumber;
1129         ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DELETE_KEY,
1130                          &authkeyid, sizeof(struct sctp_authkeyid));
1131     }
1132 }
1133 #  endif
1134
1135 static int dgram_sctp_read(BIO *b, char *out, int outl)
1136 {
1137     int ret = 0, n = 0, i, optval;
1138     socklen_t optlen;
1139     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
1140     union sctp_notification *snp;
1141     struct msghdr msg;
1142     struct iovec iov;
1143     struct cmsghdr *cmsg;
1144     char cmsgbuf[512];
1145
1146     if (out != NULL) {
1147         clear_socket_error();
1148
1149         do {
1150             memset(&data->rcvinfo, 0x00,
1151                    sizeof(struct bio_dgram_sctp_rcvinfo));
1152             iov.iov_base = out;
1153             iov.iov_len = outl;
1154             msg.msg_name = NULL;
1155             msg.msg_namelen = 0;
1156             msg.msg_iov = &iov;
1157             msg.msg_iovlen = 1;
1158             msg.msg_control = cmsgbuf;
1159             msg.msg_controllen = 512;
1160             msg.msg_flags = 0;
1161             n = recvmsg(b->num, &msg, 0);
1162
1163             if (n <= 0) {
1164                 if (n < 0)
1165                     ret = n;
1166                 break;
1167             }
1168
1169             if (msg.msg_controllen > 0) {
1170                 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg;
1171                      cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1172                     if (cmsg->cmsg_level != IPPROTO_SCTP)
1173                         continue;
1174 #  ifdef SCTP_RCVINFO
1175                     if (cmsg->cmsg_type == SCTP_RCVINFO) {
1176                         struct sctp_rcvinfo *rcvinfo;
1177
1178                         rcvinfo = (struct sctp_rcvinfo *)CMSG_DATA(cmsg);
1179                         data->rcvinfo.rcv_sid = rcvinfo->rcv_sid;
1180                         data->rcvinfo.rcv_ssn = rcvinfo->rcv_ssn;
1181                         data->rcvinfo.rcv_flags = rcvinfo->rcv_flags;
1182                         data->rcvinfo.rcv_ppid = rcvinfo->rcv_ppid;
1183                         data->rcvinfo.rcv_tsn = rcvinfo->rcv_tsn;
1184                         data->rcvinfo.rcv_cumtsn = rcvinfo->rcv_cumtsn;
1185                         data->rcvinfo.rcv_context = rcvinfo->rcv_context;
1186                     }
1187 #  endif
1188 #  ifdef SCTP_SNDRCV
1189                     if (cmsg->cmsg_type == SCTP_SNDRCV) {
1190                         struct sctp_sndrcvinfo *sndrcvinfo;
1191
1192                         sndrcvinfo =
1193                             (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
1194                         data->rcvinfo.rcv_sid = sndrcvinfo->sinfo_stream;
1195                         data->rcvinfo.rcv_ssn = sndrcvinfo->sinfo_ssn;
1196                         data->rcvinfo.rcv_flags = sndrcvinfo->sinfo_flags;
1197                         data->rcvinfo.rcv_ppid = sndrcvinfo->sinfo_ppid;
1198                         data->rcvinfo.rcv_tsn = sndrcvinfo->sinfo_tsn;
1199                         data->rcvinfo.rcv_cumtsn = sndrcvinfo->sinfo_cumtsn;
1200                         data->rcvinfo.rcv_context = sndrcvinfo->sinfo_context;
1201                     }
1202 #  endif
1203                 }
1204             }
1205
1206             if (msg.msg_flags & MSG_NOTIFICATION) {
1207                 snp = (union sctp_notification *)out;
1208                 if (snp->sn_header.sn_type == SCTP_SENDER_DRY_EVENT) {
1209 #  ifdef SCTP_EVENT
1210                     struct sctp_event event;
1211 #  else
1212                     struct sctp_event_subscribe event;
1213                     socklen_t eventsize;
1214 #  endif
1215                     /*
1216                      * If a message has been delayed until the socket is dry,
1217                      * it can be sent now.
1218                      */
1219                     if (data->saved_message.length > 0) {
1220                         dgram_sctp_write(data->saved_message.bio,
1221                                          data->saved_message.data,
1222                                          data->saved_message.length);
1223                         OPENSSL_free(data->saved_message.data);
1224                         data->saved_message.data = NULL;
1225                         data->saved_message.length = 0;
1226                     }
1227
1228                     /* disable sender dry event */
1229 #  ifdef SCTP_EVENT
1230                     memset(&event, 0, sizeof(struct sctp_event));
1231                     event.se_assoc_id = 0;
1232                     event.se_type = SCTP_SENDER_DRY_EVENT;
1233                     event.se_on = 0;
1234                     i = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event,
1235                                    sizeof(struct sctp_event));
1236                     if (i < 0) {
1237                         ret = i;
1238                         break;
1239                     }
1240 #  else
1241                     eventsize = sizeof(struct sctp_event_subscribe);
1242                     i = getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
1243                                    &eventsize);
1244                     if (i < 0) {
1245                         ret = i;
1246                         break;
1247                     }
1248
1249                     event.sctp_sender_dry_event = 0;
1250
1251                     i = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
1252                                    sizeof(struct sctp_event_subscribe));
1253                     if (i < 0) {
1254                         ret = i;
1255                         break;
1256                     }
1257 #  endif
1258                 }
1259 #  ifdef SCTP_AUTHENTICATION_EVENT
1260                 if (snp->sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
1261                     dgram_sctp_handle_auth_free_key_event(b, snp);
1262 #  endif
1263
1264                 if (data->handle_notifications != NULL)
1265                     data->handle_notifications(b, data->notification_context,
1266                                                (void *)out);
1267
1268                 memset(out, 0, outl);
1269             } else
1270                 ret += n;
1271         }
1272         while ((msg.msg_flags & MSG_NOTIFICATION) && (msg.msg_flags & MSG_EOR)
1273                && (ret < outl));
1274
1275         if (ret > 0 && !(msg.msg_flags & MSG_EOR)) {
1276             /* Partial message read, this should never happen! */
1277
1278             /*
1279              * The buffer was too small, this means the peer sent a message
1280              * that was larger than allowed.
1281              */
1282             if (ret == outl)
1283                 return -1;
1284
1285             /*
1286              * Test if socket buffer can handle max record size (2^14 + 2048
1287              * + 13)
1288              */
1289             optlen = (socklen_t) sizeof(int);
1290             ret = getsockopt(b->num, SOL_SOCKET, SO_RCVBUF, &optval, &optlen);
1291             if (ret >= 0)
1292                 OPENSSL_assert(optval >= 18445);
1293
1294             /*
1295              * Test if SCTP doesn't partially deliver below max record size
1296              * (2^14 + 2048 + 13)
1297              */
1298             optlen = (socklen_t) sizeof(int);
1299             ret =
1300                 getsockopt(b->num, IPPROTO_SCTP, SCTP_PARTIAL_DELIVERY_POINT,
1301                            &optval, &optlen);
1302             if (ret >= 0)
1303                 OPENSSL_assert(optval >= 18445);
1304
1305             /*
1306              * Partially delivered notification??? Probably a bug....
1307              */
1308             OPENSSL_assert(!(msg.msg_flags & MSG_NOTIFICATION));
1309
1310             /*
1311              * Everything seems ok till now, so it's most likely a message
1312              * dropped by PR-SCTP.
1313              */
1314             memset(out, 0, outl);
1315             BIO_set_retry_read(b);
1316             return -1;
1317         }
1318
1319         BIO_clear_retry_flags(b);
1320         if (ret < 0) {
1321             if (BIO_dgram_should_retry(ret)) {
1322                 BIO_set_retry_read(b);
1323                 data->_errno = get_last_socket_error();
1324             }
1325         }
1326
1327         /* Test if peer uses SCTP-AUTH before continuing */
1328         if (!data->peer_auth_tested) {
1329             int ii, auth_data = 0, auth_forward = 0;
1330             unsigned char *p;
1331             struct sctp_authchunks *authchunks;
1332
1333             optlen =
1334                 (socklen_t) (sizeof(sctp_assoc_t) + 256 * sizeof(uint8_t));
1335             authchunks = OPENSSL_malloc(optlen);
1336             memset(authchunks, 0, optlen);
1337             ii = getsockopt(b->num, IPPROTO_SCTP, SCTP_PEER_AUTH_CHUNKS,
1338                             authchunks, &optlen);
1339
1340             if (ii >= 0)
1341                 for (p = (unsigned char *)authchunks->gauth_chunks;
1342                      p < (unsigned char *)authchunks + optlen;
1343                      p += sizeof(uint8_t)) {
1344                     if (*p == OPENSSL_SCTP_DATA_CHUNK_TYPE)
1345                         auth_data = 1;
1346                     if (*p == OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE)
1347                         auth_forward = 1;
1348                 }
1349
1350             OPENSSL_free(authchunks);
1351
1352             if (!auth_data || !auth_forward) {
1353                 BIOerr(BIO_F_DGRAM_SCTP_READ, BIO_R_CONNECT_ERROR);
1354                 return -1;
1355             }
1356
1357             data->peer_auth_tested = 1;
1358         }
1359     }
1360     return (ret);
1361 }
1362
1363 static int dgram_sctp_write(BIO *b, const char *in, int inl)
1364 {
1365     int ret;
1366     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
1367     struct bio_dgram_sctp_sndinfo *sinfo = &(data->sndinfo);
1368     struct bio_dgram_sctp_prinfo *pinfo = &(data->prinfo);
1369     struct bio_dgram_sctp_sndinfo handshake_sinfo;
1370     struct iovec iov[1];
1371     struct msghdr msg;
1372     struct cmsghdr *cmsg;
1373 #  if defined(SCTP_SNDINFO) && defined(SCTP_PRINFO)
1374     char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndinfo)) +
1375                  CMSG_SPACE(sizeof(struct sctp_prinfo))];
1376     struct sctp_sndinfo *sndinfo;
1377     struct sctp_prinfo *prinfo;
1378 #  else
1379     char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndrcvinfo))];
1380     struct sctp_sndrcvinfo *sndrcvinfo;
1381 #  endif
1382
1383     clear_socket_error();
1384
1385     /*
1386      * If we're send anything else than application data, disable all user
1387      * parameters and flags.
1388      */
1389     if (in[0] != 23) {
1390         memset(&handshake_sinfo, 0x00, sizeof(struct bio_dgram_sctp_sndinfo));
1391 #  ifdef SCTP_SACK_IMMEDIATELY
1392         handshake_sinfo.snd_flags = SCTP_SACK_IMMEDIATELY;
1393 #  endif
1394         sinfo = &handshake_sinfo;
1395     }
1396
1397     /*
1398      * If we have to send a shutdown alert message and the socket is not dry
1399      * yet, we have to save it and send it as soon as the socket gets dry.
1400      */
1401     if (data->save_shutdown && !BIO_dgram_sctp_wait_for_dry(b)) {
1402         data->saved_message.bio = b;
1403         if (data->saved_message.data)
1404             OPENSSL_free(data->saved_message.data);
1405         data->saved_message.data = OPENSSL_malloc(inl);
1406         memcpy(data->saved_message.data, in, inl);
1407         data->saved_message.length = inl;
1408         return inl;
1409     }
1410
1411     iov[0].iov_base = (char *)in;
1412     iov[0].iov_len = inl;
1413     msg.msg_name = NULL;
1414     msg.msg_namelen = 0;
1415     msg.msg_iov = iov;
1416     msg.msg_iovlen = 1;
1417     msg.msg_control = (caddr_t) cmsgbuf;
1418     msg.msg_controllen = 0;
1419     msg.msg_flags = 0;
1420 #  if defined(SCTP_SNDINFO) && defined(SCTP_PRINFO)
1421     cmsg = (struct cmsghdr *)cmsgbuf;
1422     cmsg->cmsg_level = IPPROTO_SCTP;
1423     cmsg->cmsg_type = SCTP_SNDINFO;
1424     cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndinfo));
1425     sndinfo = (struct sctp_sndinfo *)CMSG_DATA(cmsg);
1426     memset(sndinfo, 0, sizeof(struct sctp_sndinfo));
1427     sndinfo->snd_sid = sinfo->snd_sid;
1428     sndinfo->snd_flags = sinfo->snd_flags;
1429     sndinfo->snd_ppid = sinfo->snd_ppid;
1430     sndinfo->snd_context = sinfo->snd_context;
1431     msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_sndinfo));
1432
1433     cmsg =
1434         (struct cmsghdr *)&cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndinfo))];
1435     cmsg->cmsg_level = IPPROTO_SCTP;
1436     cmsg->cmsg_type = SCTP_PRINFO;
1437     cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_prinfo));
1438     prinfo = (struct sctp_prinfo *)CMSG_DATA(cmsg);
1439     memset(prinfo, 0, sizeof(struct sctp_prinfo));
1440     prinfo->pr_policy = pinfo->pr_policy;
1441     prinfo->pr_value = pinfo->pr_value;
1442     msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_prinfo));
1443 #  else
1444     cmsg = (struct cmsghdr *)cmsgbuf;
1445     cmsg->cmsg_level = IPPROTO_SCTP;
1446     cmsg->cmsg_type = SCTP_SNDRCV;
1447     cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
1448     sndrcvinfo = (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
1449     memset(sndrcvinfo, 0, sizeof(struct sctp_sndrcvinfo));
1450     sndrcvinfo->sinfo_stream = sinfo->snd_sid;
1451     sndrcvinfo->sinfo_flags = sinfo->snd_flags;
1452 #   ifdef __FreeBSD__
1453     sndrcvinfo->sinfo_flags |= pinfo->pr_policy;
1454 #   endif
1455     sndrcvinfo->sinfo_ppid = sinfo->snd_ppid;
1456     sndrcvinfo->sinfo_context = sinfo->snd_context;
1457     sndrcvinfo->sinfo_timetolive = pinfo->pr_value;
1458     msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_sndrcvinfo));
1459 #  endif
1460
1461     ret = sendmsg(b->num, &msg, 0);
1462
1463     BIO_clear_retry_flags(b);
1464     if (ret <= 0) {
1465         if (BIO_dgram_should_retry(ret)) {
1466             BIO_set_retry_write(b);
1467             data->_errno = get_last_socket_error();
1468         }
1469     }
1470     return (ret);
1471 }
1472
1473 static long dgram_sctp_ctrl(BIO *b, int cmd, long num, void *ptr)
1474 {
1475     long ret = 1;
1476     bio_dgram_sctp_data *data = NULL;
1477     socklen_t sockopt_len = 0;
1478     struct sctp_authkeyid authkeyid;
1479     struct sctp_authkey *authkey = NULL;
1480
1481     data = (bio_dgram_sctp_data *) b->ptr;
1482
1483     switch (cmd) {
1484     case BIO_CTRL_DGRAM_QUERY_MTU:
1485         /*
1486          * Set to maximum (2^14) and ignore user input to enable transport
1487          * protocol fragmentation. Returns always 2^14.
1488          */
1489         data->mtu = 16384;
1490         ret = data->mtu;
1491         break;
1492     case BIO_CTRL_DGRAM_SET_MTU:
1493         /*
1494          * Set to maximum (2^14) and ignore input to enable transport
1495          * protocol fragmentation. Returns always 2^14.
1496          */
1497         data->mtu = 16384;
1498         ret = data->mtu;
1499         break;
1500     case BIO_CTRL_DGRAM_SET_CONNECTED:
1501     case BIO_CTRL_DGRAM_CONNECT:
1502         /* Returns always -1. */
1503         ret = -1;
1504         break;
1505     case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
1506         /*
1507          * SCTP doesn't need the DTLS timer Returns always 1.
1508          */
1509         break;
1510     case BIO_CTRL_DGRAM_GET_MTU_OVERHEAD:
1511         /*
1512          * We allow transport protocol fragmentation so this is irrelevant
1513          */
1514         ret = 0;
1515         break;
1516     case BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE:
1517         if (num > 0)
1518             data->in_handshake = 1;
1519         else
1520             data->in_handshake = 0;
1521
1522         ret =
1523             setsockopt(b->num, IPPROTO_SCTP, SCTP_NODELAY,
1524                        &data->in_handshake, sizeof(int));
1525         break;
1526     case BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY:
1527         /*
1528          * New shared key for SCTP AUTH. Returns 0 on success, -1 otherwise.
1529          */
1530
1531         /* Get active key */
1532         sockopt_len = sizeof(struct sctp_authkeyid);
1533         ret =
1534             getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY, &authkeyid,
1535                        &sockopt_len);
1536         if (ret < 0)
1537             break;
1538
1539         /* Add new key */
1540         sockopt_len = sizeof(struct sctp_authkey) + 64 * sizeof(uint8_t);
1541         authkey = OPENSSL_malloc(sockopt_len);
1542         if (authkey == NULL) {
1543             ret = -1;
1544             break;
1545         }
1546         memset(authkey, 0x00, sockopt_len);
1547         authkey->sca_keynumber = authkeyid.scact_keynumber + 1;
1548 #  ifndef __FreeBSD__
1549         /*
1550          * This field is missing in FreeBSD 8.2 and earlier, and FreeBSD 8.3
1551          * and higher work without it.
1552          */
1553         authkey->sca_keylength = 64;
1554 #  endif
1555         memcpy(&authkey->sca_key[0], ptr, 64 * sizeof(uint8_t));
1556
1557         ret =
1558             setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_KEY, authkey,
1559                        sockopt_len);
1560         OPENSSL_free(authkey);
1561         authkey = NULL;
1562         if (ret < 0)
1563             break;
1564
1565         /* Reset active key */
1566         ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY,
1567                          &authkeyid, sizeof(struct sctp_authkeyid));
1568         if (ret < 0)
1569             break;
1570
1571         break;
1572     case BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY:
1573         /* Returns 0 on success, -1 otherwise. */
1574
1575         /* Get active key */
1576         sockopt_len = sizeof(struct sctp_authkeyid);
1577         ret =
1578             getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY, &authkeyid,
1579                        &sockopt_len);
1580         if (ret < 0)
1581             break;
1582
1583         /* Set active key */
1584         authkeyid.scact_keynumber = authkeyid.scact_keynumber + 1;
1585         ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY,
1586                          &authkeyid, sizeof(struct sctp_authkeyid));
1587         if (ret < 0)
1588             break;
1589
1590         /*
1591          * CCS has been sent, so remember that and fall through to check if
1592          * we need to deactivate an old key
1593          */
1594         data->ccs_sent = 1;
1595
1596     case BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD:
1597         /* Returns 0 on success, -1 otherwise. */
1598
1599         /*
1600          * Has this command really been called or is this just a
1601          * fall-through?
1602          */
1603         if (cmd == BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD)
1604             data->ccs_rcvd = 1;
1605
1606         /*
1607          * CSS has been both, received and sent, so deactivate an old key
1608          */
1609         if (data->ccs_rcvd == 1 && data->ccs_sent == 1) {
1610             /* Get active key */
1611             sockopt_len = sizeof(struct sctp_authkeyid);
1612             ret =
1613                 getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY,
1614                            &authkeyid, &sockopt_len);
1615             if (ret < 0)
1616                 break;
1617
1618             /*
1619              * Deactivate key or delete second last key if
1620              * SCTP_AUTHENTICATION_EVENT is not available.
1621              */
1622             authkeyid.scact_keynumber = authkeyid.scact_keynumber - 1;
1623 #  ifdef SCTP_AUTH_DEACTIVATE_KEY
1624             sockopt_len = sizeof(struct sctp_authkeyid);
1625             ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DEACTIVATE_KEY,
1626                              &authkeyid, sockopt_len);
1627             if (ret < 0)
1628                 break;
1629 #  endif
1630 #  ifndef SCTP_AUTHENTICATION_EVENT
1631             if (authkeyid.scact_keynumber > 0) {
1632                 authkeyid.scact_keynumber = authkeyid.scact_keynumber - 1;
1633                 ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DELETE_KEY,
1634                                  &authkeyid, sizeof(struct sctp_authkeyid));
1635                 if (ret < 0)
1636                     break;
1637             }
1638 #  endif
1639
1640             data->ccs_rcvd = 0;
1641             data->ccs_sent = 0;
1642         }
1643         break;
1644     case BIO_CTRL_DGRAM_SCTP_GET_SNDINFO:
1645         /* Returns the size of the copied struct. */
1646         if (num > (long)sizeof(struct bio_dgram_sctp_sndinfo))
1647             num = sizeof(struct bio_dgram_sctp_sndinfo);
1648
1649         memcpy(ptr, &(data->sndinfo), num);
1650         ret = num;
1651         break;
1652     case BIO_CTRL_DGRAM_SCTP_SET_SNDINFO:
1653         /* Returns the size of the copied struct. */
1654         if (num > (long)sizeof(struct bio_dgram_sctp_sndinfo))
1655             num = sizeof(struct bio_dgram_sctp_sndinfo);
1656
1657         memcpy(&(data->sndinfo), ptr, num);
1658         break;
1659     case BIO_CTRL_DGRAM_SCTP_GET_RCVINFO:
1660         /* Returns the size of the copied struct. */
1661         if (num > (long)sizeof(struct bio_dgram_sctp_rcvinfo))
1662             num = sizeof(struct bio_dgram_sctp_rcvinfo);
1663
1664         memcpy(ptr, &data->rcvinfo, num);
1665
1666         ret = num;
1667         break;
1668     case BIO_CTRL_DGRAM_SCTP_SET_RCVINFO:
1669         /* Returns the size of the copied struct. */
1670         if (num > (long)sizeof(struct bio_dgram_sctp_rcvinfo))
1671             num = sizeof(struct bio_dgram_sctp_rcvinfo);
1672
1673         memcpy(&(data->rcvinfo), ptr, num);
1674         break;
1675     case BIO_CTRL_DGRAM_SCTP_GET_PRINFO:
1676         /* Returns the size of the copied struct. */
1677         if (num > (long)sizeof(struct bio_dgram_sctp_prinfo))
1678             num = sizeof(struct bio_dgram_sctp_prinfo);
1679
1680         memcpy(ptr, &(data->prinfo), num);
1681         ret = num;
1682         break;
1683     case BIO_CTRL_DGRAM_SCTP_SET_PRINFO:
1684         /* Returns the size of the copied struct. */
1685         if (num > (long)sizeof(struct bio_dgram_sctp_prinfo))
1686             num = sizeof(struct bio_dgram_sctp_prinfo);
1687
1688         memcpy(&(data->prinfo), ptr, num);
1689         break;
1690     case BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN:
1691         /* Returns always 1. */
1692         if (num > 0)
1693             data->save_shutdown = 1;
1694         else
1695             data->save_shutdown = 0;
1696         break;
1697
1698     default:
1699         /*
1700          * Pass to default ctrl function to process SCTP unspecific commands
1701          */
1702         ret = dgram_ctrl(b, cmd, num, ptr);
1703         break;
1704     }
1705     return (ret);
1706 }
1707
1708 int BIO_dgram_sctp_notification_cb(BIO *b,
1709                                    void (*handle_notifications) (BIO *bio,
1710                                                                  void
1711                                                                  *context,
1712                                                                  void *buf),
1713                                    void *context)
1714 {
1715     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
1716
1717     if (handle_notifications != NULL) {
1718         data->handle_notifications = handle_notifications;
1719         data->notification_context = context;
1720     } else
1721         return -1;
1722
1723     return 0;
1724 }
1725
1726 int BIO_dgram_sctp_wait_for_dry(BIO *b)
1727 {
1728     int is_dry = 0;
1729     int n, sockflags, ret;
1730     union sctp_notification snp;
1731     struct msghdr msg;
1732     struct iovec iov;
1733 #  ifdef SCTP_EVENT
1734     struct sctp_event event;
1735 #  else
1736     struct sctp_event_subscribe event;
1737     socklen_t eventsize;
1738 #  endif
1739     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
1740
1741     /* set sender dry event */
1742 #  ifdef SCTP_EVENT
1743     memset(&event, 0, sizeof(struct sctp_event));
1744     event.se_assoc_id = 0;
1745     event.se_type = SCTP_SENDER_DRY_EVENT;
1746     event.se_on = 1;
1747     ret =
1748         setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event,
1749                    sizeof(struct sctp_event));
1750 #  else
1751     eventsize = sizeof(struct sctp_event_subscribe);
1752     ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, &eventsize);
1753     if (ret < 0)
1754         return -1;
1755
1756     event.sctp_sender_dry_event = 1;
1757
1758     ret =
1759         setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
1760                    sizeof(struct sctp_event_subscribe));
1761 #  endif
1762     if (ret < 0)
1763         return -1;
1764
1765     /* peek for notification */
1766     memset(&snp, 0x00, sizeof(union sctp_notification));
1767     iov.iov_base = (char *)&snp;
1768     iov.iov_len = sizeof(union sctp_notification);
1769     msg.msg_name = NULL;
1770     msg.msg_namelen = 0;
1771     msg.msg_iov = &iov;
1772     msg.msg_iovlen = 1;
1773     msg.msg_control = NULL;
1774     msg.msg_controllen = 0;
1775     msg.msg_flags = 0;
1776
1777     n = recvmsg(b->num, &msg, MSG_PEEK);
1778     if (n <= 0) {
1779         if ((n < 0) && (get_last_socket_error() != EAGAIN)
1780             && (get_last_socket_error() != EWOULDBLOCK))
1781             return -1;
1782         else
1783             return 0;
1784     }
1785
1786     /* if we find a notification, process it and try again if necessary */
1787     while (msg.msg_flags & MSG_NOTIFICATION) {
1788         memset(&snp, 0x00, sizeof(union sctp_notification));
1789         iov.iov_base = (char *)&snp;
1790         iov.iov_len = sizeof(union sctp_notification);
1791         msg.msg_name = NULL;
1792         msg.msg_namelen = 0;
1793         msg.msg_iov = &iov;
1794         msg.msg_iovlen = 1;
1795         msg.msg_control = NULL;
1796         msg.msg_controllen = 0;
1797         msg.msg_flags = 0;
1798
1799         n = recvmsg(b->num, &msg, 0);
1800         if (n <= 0) {
1801             if ((n < 0) && (get_last_socket_error() != EAGAIN)
1802                 && (get_last_socket_error() != EWOULDBLOCK))
1803                 return -1;
1804             else
1805                 return is_dry;
1806         }
1807
1808         if (snp.sn_header.sn_type == SCTP_SENDER_DRY_EVENT) {
1809             is_dry = 1;
1810
1811             /* disable sender dry event */
1812 #  ifdef SCTP_EVENT
1813             memset(&event, 0, sizeof(struct sctp_event));
1814             event.se_assoc_id = 0;
1815             event.se_type = SCTP_SENDER_DRY_EVENT;
1816             event.se_on = 0;
1817             ret =
1818                 setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event,
1819                            sizeof(struct sctp_event));
1820 #  else
1821             eventsize = (socklen_t) sizeof(struct sctp_event_subscribe);
1822             ret =
1823                 getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
1824                            &eventsize);
1825             if (ret < 0)
1826                 return -1;
1827
1828             event.sctp_sender_dry_event = 0;
1829
1830             ret =
1831                 setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event,
1832                            sizeof(struct sctp_event_subscribe));
1833 #  endif
1834             if (ret < 0)
1835                 return -1;
1836         }
1837 #  ifdef SCTP_AUTHENTICATION_EVENT
1838         if (snp.sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
1839             dgram_sctp_handle_auth_free_key_event(b, &snp);
1840 #  endif
1841
1842         if (data->handle_notifications != NULL)
1843             data->handle_notifications(b, data->notification_context,
1844                                        (void *)&snp);
1845
1846         /* found notification, peek again */
1847         memset(&snp, 0x00, sizeof(union sctp_notification));
1848         iov.iov_base = (char *)&snp;
1849         iov.iov_len = sizeof(union sctp_notification);
1850         msg.msg_name = NULL;
1851         msg.msg_namelen = 0;
1852         msg.msg_iov = &iov;
1853         msg.msg_iovlen = 1;
1854         msg.msg_control = NULL;
1855         msg.msg_controllen = 0;
1856         msg.msg_flags = 0;
1857
1858         /* if we have seen the dry already, don't wait */
1859         if (is_dry) {
1860             sockflags = fcntl(b->num, F_GETFL, 0);
1861             fcntl(b->num, F_SETFL, O_NONBLOCK);
1862         }
1863
1864         n = recvmsg(b->num, &msg, MSG_PEEK);
1865
1866         if (is_dry) {
1867             fcntl(b->num, F_SETFL, sockflags);
1868         }
1869
1870         if (n <= 0) {
1871             if ((n < 0) && (get_last_socket_error() != EAGAIN)
1872                 && (get_last_socket_error() != EWOULDBLOCK))
1873                 return -1;
1874             else
1875                 return is_dry;
1876         }
1877     }
1878
1879     /* read anything else */
1880     return is_dry;
1881 }
1882
1883 int BIO_dgram_sctp_msg_waiting(BIO *b)
1884 {
1885     int n, sockflags;
1886     union sctp_notification snp;
1887     struct msghdr msg;
1888     struct iovec iov;
1889     bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
1890
1891     /* Check if there are any messages waiting to be read */
1892     do {
1893         memset(&snp, 0x00, sizeof(union sctp_notification));
1894         iov.iov_base = (char *)&snp;
1895         iov.iov_len = sizeof(union sctp_notification);
1896         msg.msg_name = NULL;
1897         msg.msg_namelen = 0;
1898         msg.msg_iov = &iov;
1899         msg.msg_iovlen = 1;
1900         msg.msg_control = NULL;
1901         msg.msg_controllen = 0;
1902         msg.msg_flags = 0;
1903
1904         sockflags = fcntl(b->num, F_GETFL, 0);
1905         fcntl(b->num, F_SETFL, O_NONBLOCK);
1906         n = recvmsg(b->num, &msg, MSG_PEEK);
1907         fcntl(b->num, F_SETFL, sockflags);
1908
1909         /* if notification, process and try again */
1910         if (n > 0 && (msg.msg_flags & MSG_NOTIFICATION)) {
1911 #  ifdef SCTP_AUTHENTICATION_EVENT
1912             if (snp.sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
1913                 dgram_sctp_handle_auth_free_key_event(b, &snp);
1914 #  endif
1915
1916             memset(&snp, 0x00, sizeof(union sctp_notification));
1917             iov.iov_base = (char *)&snp;
1918             iov.iov_len = sizeof(union sctp_notification);
1919             msg.msg_name = NULL;
1920             msg.msg_namelen = 0;
1921             msg.msg_iov = &iov;
1922             msg.msg_iovlen = 1;
1923             msg.msg_control = NULL;
1924             msg.msg_controllen = 0;
1925             msg.msg_flags = 0;
1926             n = recvmsg(b->num, &msg, 0);
1927
1928             if (data->handle_notifications != NULL)
1929                 data->handle_notifications(b, data->notification_context,
1930                                            (void *)&snp);
1931         }
1932
1933     } while (n > 0 && (msg.msg_flags & MSG_NOTIFICATION));
1934
1935     /* Return 1 if there is a message to be read, return 0 otherwise. */
1936     if (n > 0)
1937         return 1;
1938     else
1939         return 0;
1940 }
1941
1942 static int dgram_sctp_puts(BIO *bp, const char *str)
1943 {
1944     int n, ret;
1945
1946     n = strlen(str);
1947     ret = dgram_sctp_write(bp, str, n);
1948     return (ret);
1949 }
1950 # endif
1951
1952 static int BIO_dgram_should_retry(int i)
1953 {
1954     int err;
1955
1956     if ((i == 0) || (i == -1)) {
1957         err = get_last_socket_error();
1958
1959 # if defined(OPENSSL_SYS_WINDOWS)
1960         /*
1961          * If the socket return value (i) is -1 and err is unexpectedly 0 at
1962          * this point, the error code was overwritten by another system call
1963          * before this error handling is called.
1964          */
1965 # endif
1966
1967         return (BIO_dgram_non_fatal_error(err));
1968     }
1969     return (0);
1970 }
1971
1972 int BIO_dgram_non_fatal_error(int err)
1973 {
1974     switch (err) {
1975 # if defined(OPENSSL_SYS_WINDOWS)
1976 #  if defined(WSAEWOULDBLOCK)
1977     case WSAEWOULDBLOCK:
1978 #  endif
1979 # endif
1980
1981 # ifdef EWOULDBLOCK
1982 #  ifdef WSAEWOULDBLOCK
1983 #   if WSAEWOULDBLOCK != EWOULDBLOCK
1984     case EWOULDBLOCK:
1985 #   endif
1986 #  else
1987     case EWOULDBLOCK:
1988 #  endif
1989 # endif
1990
1991 # ifdef EINTR
1992     case EINTR:
1993 # endif
1994
1995 # ifdef EAGAIN
1996 #  if EWOULDBLOCK != EAGAIN
1997     case EAGAIN:
1998 #  endif
1999 # endif
2000
2001 # ifdef EPROTO
2002     case EPROTO:
2003 # endif
2004
2005 # ifdef EINPROGRESS
2006     case EINPROGRESS:
2007 # endif
2008
2009 # ifdef EALREADY
2010     case EALREADY:
2011 # endif
2012
2013         return (1);
2014         /* break; */
2015     default:
2016         break;
2017     }
2018     return (0);
2019 }
2020
2021 static void get_current_time(struct timeval *t)
2022 {
2023 # if defined(_WIN32)
2024     SYSTEMTIME st;
2025     union {
2026         unsigned __int64 ul;
2027         FILETIME ft;
2028     } now;
2029
2030     GetSystemTime(&st);
2031     SystemTimeToFileTime(&st, &now.ft);
2032 #  ifdef  __MINGW32__
2033     now.ul -= 116444736000000000ULL;
2034 #  else
2035     now.ul -= 116444736000000000UI64; /* re-bias to 1/1/1970 */
2036 #  endif
2037     t->tv_sec = (long)(now.ul / 10000000);
2038     t->tv_usec = ((int)(now.ul % 10000000)) / 10;
2039 # elif defined(OPENSSL_SYS_VMS)
2040     struct timeb tb;
2041     ftime(&tb);
2042     t->tv_sec = (long)tb.time;
2043     t->tv_usec = (long)tb.millitm * 1000;
2044 # else
2045     gettimeofday(t, NULL);
2046 # endif
2047 }
2048
2049 #endif