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