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