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