bf1e39b5c0b4009dd7bb26ffbe3b1a24984cd893
[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         OPENSSL_assert(ret >= 0);
979         auth.sauth_chunk = OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE;
980         ret = setsockopt(fd, IPPROTO_SCTP, SCTP_AUTH_CHUNK, &auth, sizeof(struct sctp_authchunk));
981         OPENSSL_assert(ret >= 0);
982
983         /* Test if activation was successful. When using accept(),
984          * SCTP-AUTH has to be activated for the listening socket
985          * already, otherwise the connected socket won't use it. */
986         sockopt_len = (socklen_t)(sizeof(sctp_assoc_t) + 256 * sizeof(uint8_t));
987         authchunks = OPENSSL_malloc(sockopt_len);
988         memset(authchunks, 0, sockopt_len);
989         ret = getsockopt(fd, IPPROTO_SCTP, SCTP_LOCAL_AUTH_CHUNKS, authchunks, &sockopt_len);
990         OPENSSL_assert(ret >= 0);
991
992         for (p = (unsigned char*) authchunks->gauth_chunks;
993              p < (unsigned char*) authchunks + sockopt_len;
994              p += sizeof(uint8_t))
995                 {
996                 if (*p == OPENSSL_SCTP_DATA_CHUNK_TYPE) auth_data = 1;
997                 if (*p == OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE) auth_forward = 1;
998                 }
999                 
1000         OPENSSL_free(authchunks);
1001
1002         OPENSSL_assert(auth_data);
1003         OPENSSL_assert(auth_forward);
1004
1005 #ifdef SCTP_AUTHENTICATION_EVENT
1006 #ifdef SCTP_EVENT
1007         memset(&event, 0, sizeof(struct sctp_event));
1008         event.se_assoc_id = 0;
1009         event.se_type = SCTP_AUTHENTICATION_EVENT;
1010         event.se_on = 1;
1011         ret = setsockopt(fd, IPPROTO_SCTP, SCTP_EVENT, &event, sizeof(struct sctp_event));
1012         OPENSSL_assert(ret >= 0);
1013 #else
1014         sockopt_len = (socklen_t) sizeof(struct sctp_event_subscribe);
1015         ret = getsockopt(fd, IPPROTO_SCTP, SCTP_EVENTS, &event, &sockopt_len);
1016         OPENSSL_assert(ret >= 0);
1017
1018         event.sctp_authentication_event = 1;
1019
1020         ret = setsockopt(fd, IPPROTO_SCTP, SCTP_EVENTS, &event, sizeof(struct sctp_event_subscribe));
1021         OPENSSL_assert(ret >= 0);
1022 #endif
1023 #endif
1024
1025         /* Disable partial delivery by setting the min size
1026          * larger than the max record size of 2^14 + 2048 + 13
1027          */
1028         ret = setsockopt(fd, IPPROTO_SCTP, SCTP_PARTIAL_DELIVERY_POINT, &optval, sizeof(optval));
1029         OPENSSL_assert(ret >= 0);
1030
1031         return(bio);
1032         }
1033
1034 int BIO_dgram_is_sctp(BIO *bio)
1035         {
1036         return (BIO_method_type(bio) == BIO_TYPE_DGRAM_SCTP);
1037         }
1038
1039 static int dgram_sctp_new(BIO *bi)
1040         {
1041         bio_dgram_sctp_data *data = NULL;
1042
1043         bi->init=0;
1044         bi->num=0;
1045         data = OPENSSL_malloc(sizeof(bio_dgram_sctp_data));
1046         if (data == NULL)
1047                 return 0;
1048         memset(data, 0x00, sizeof(bio_dgram_sctp_data));
1049 #ifdef SCTP_PR_SCTP_NONE
1050         data->prinfo.pr_policy = SCTP_PR_SCTP_NONE;
1051 #endif
1052     bi->ptr = data;
1053
1054         bi->flags=0;
1055         return(1);
1056         }
1057
1058 static int dgram_sctp_free(BIO *a)
1059         {
1060         bio_dgram_sctp_data *data;
1061
1062         if (a == NULL) return(0);
1063         if ( ! dgram_clear(a))
1064                 return 0;
1065
1066         data = (bio_dgram_sctp_data *)a->ptr;
1067         if(data != NULL) OPENSSL_free(data);
1068
1069         return(1);
1070         }
1071
1072 #ifdef SCTP_AUTHENTICATION_EVENT
1073 void dgram_sctp_handle_auth_free_key_event(BIO *b, union sctp_notification *snp)
1074         {
1075         int ret;
1076         struct sctp_authkey_event* authkeyevent = &snp->sn_auth_event;
1077
1078         if (authkeyevent->auth_indication == SCTP_AUTH_FREE_KEY)
1079                 {
1080                 struct sctp_authkeyid authkeyid;
1081
1082                 /* delete key */
1083                 authkeyid.scact_keynumber = authkeyevent->auth_keynumber;
1084                 ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DELETE_KEY,
1085                       &authkeyid, sizeof(struct sctp_authkeyid));
1086                 }
1087         }
1088 #endif
1089
1090 static int dgram_sctp_read(BIO *b, char *out, int outl)
1091         {
1092         int ret = 0, n = 0, i, optval;
1093         socklen_t optlen;
1094         bio_dgram_sctp_data *data = (bio_dgram_sctp_data *)b->ptr;
1095         union sctp_notification *snp;
1096         struct msghdr msg;
1097         struct iovec iov;
1098         struct cmsghdr *cmsg;
1099         char cmsgbuf[512];
1100
1101         if (out != NULL)
1102                 {
1103                 clear_socket_error();
1104
1105                 do
1106                         {
1107                         memset(&data->rcvinfo, 0x00, sizeof(struct bio_dgram_sctp_rcvinfo));
1108                         iov.iov_base = out;
1109                         iov.iov_len = outl;
1110                         msg.msg_name = NULL;
1111                         msg.msg_namelen = 0;
1112                         msg.msg_iov = &iov;
1113                         msg.msg_iovlen = 1;
1114                         msg.msg_control = cmsgbuf;
1115                         msg.msg_controllen = 512;
1116                         msg.msg_flags = 0;
1117                         n = recvmsg(b->num, &msg, 0);
1118
1119                         if (n <= 0)
1120                                 {
1121                                 if (n < 0)
1122                                         ret = n;
1123                                 break;
1124                                 }
1125
1126                         if (msg.msg_controllen > 0)
1127                                 {
1128                                 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg))
1129                                         {
1130                                         if (cmsg->cmsg_level != IPPROTO_SCTP)
1131                                                 continue;
1132 #ifdef SCTP_RCVINFO
1133                                         if (cmsg->cmsg_type == SCTP_RCVINFO)
1134                                                 {
1135                                                 struct sctp_rcvinfo *rcvinfo;
1136
1137                                                 rcvinfo = (struct sctp_rcvinfo *)CMSG_DATA(cmsg);
1138                                                 data->rcvinfo.rcv_sid = rcvinfo->rcv_sid;
1139                                                 data->rcvinfo.rcv_ssn = rcvinfo->rcv_ssn;
1140                                                 data->rcvinfo.rcv_flags = rcvinfo->rcv_flags;
1141                                                 data->rcvinfo.rcv_ppid = rcvinfo->rcv_ppid;
1142                                                 data->rcvinfo.rcv_tsn = rcvinfo->rcv_tsn;
1143                                                 data->rcvinfo.rcv_cumtsn = rcvinfo->rcv_cumtsn;
1144                                                 data->rcvinfo.rcv_context = rcvinfo->rcv_context;
1145                                                 }
1146 #endif
1147 #ifdef SCTP_SNDRCV
1148                                         if (cmsg->cmsg_type == SCTP_SNDRCV)
1149                                                 {
1150                                                 struct sctp_sndrcvinfo *sndrcvinfo;
1151
1152                                                 sndrcvinfo = (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
1153                                                 data->rcvinfo.rcv_sid = sndrcvinfo->sinfo_stream;
1154                                                 data->rcvinfo.rcv_ssn = sndrcvinfo->sinfo_ssn;
1155                                                 data->rcvinfo.rcv_flags = sndrcvinfo->sinfo_flags;
1156                                                 data->rcvinfo.rcv_ppid = sndrcvinfo->sinfo_ppid;
1157                                                 data->rcvinfo.rcv_tsn = sndrcvinfo->sinfo_tsn;
1158                                                 data->rcvinfo.rcv_cumtsn = sndrcvinfo->sinfo_cumtsn;
1159                                                 data->rcvinfo.rcv_context = sndrcvinfo->sinfo_context;
1160                                                 }
1161 #endif
1162                                         }
1163                                 }
1164
1165                         if (msg.msg_flags & MSG_NOTIFICATION)
1166                                 {
1167                                 snp = (union sctp_notification*) out;
1168                                 if (snp->sn_header.sn_type == SCTP_SENDER_DRY_EVENT)
1169                                         {
1170 #ifdef SCTP_EVENT
1171                                         struct sctp_event event;
1172 #else
1173                                         struct sctp_event_subscribe event;
1174                                         socklen_t eventsize;
1175 #endif
1176                                         /* If a message has been delayed until the socket
1177                                          * is dry, it can be sent now.
1178                                          */
1179                                         if (data->saved_message.length > 0)
1180                                                 {
1181                                                 dgram_sctp_write(data->saved_message.bio, data->saved_message.data,
1182                                                                  data->saved_message.length);
1183                                                 OPENSSL_free(data->saved_message.data);
1184                                                 data->saved_message.length = 0;
1185                                                 }
1186
1187                                         /* disable sender dry event */
1188 #ifdef SCTP_EVENT
1189                                         memset(&event, 0, sizeof(struct sctp_event));
1190                                         event.se_assoc_id = 0;
1191                                         event.se_type = SCTP_SENDER_DRY_EVENT;
1192                                         event.se_on = 0;
1193                                         i = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event, sizeof(struct sctp_event));
1194                                         OPENSSL_assert(i >= 0);
1195 #else
1196                                         eventsize = sizeof(struct sctp_event_subscribe);
1197                                         i = getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, &eventsize);
1198                                         OPENSSL_assert(i >= 0);
1199
1200                                         event.sctp_sender_dry_event = 0;
1201
1202                                         i = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, sizeof(struct sctp_event_subscribe));
1203                                         OPENSSL_assert(i >= 0);
1204 #endif
1205                                         }
1206
1207 #ifdef SCTP_AUTHENTICATION_EVENT
1208                                 if (snp->sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
1209                                         dgram_sctp_handle_auth_free_key_event(b, snp);
1210 #endif
1211
1212                                 if (data->handle_notifications != NULL)
1213                                         data->handle_notifications(b, data->notification_context, (void*) out);
1214
1215                                 memset(out, 0, outl);
1216                                 }
1217                         else
1218                                 ret += n;
1219                         }
1220                 while ((msg.msg_flags & MSG_NOTIFICATION) && (msg.msg_flags & MSG_EOR) && (ret < outl));
1221
1222                 if (ret > 0 && !(msg.msg_flags & MSG_EOR))
1223                         {
1224                         /* Partial message read, this should never happen! */
1225
1226                         /* The buffer was too small, this means the peer sent
1227                          * a message that was larger than allowed. */
1228                         if (ret == outl)
1229                                 return -1;
1230
1231                         /* Test if socket buffer can handle max record
1232                          * size (2^14 + 2048 + 13)
1233                          */
1234                         optlen = (socklen_t) sizeof(int);
1235                         ret = getsockopt(b->num, SOL_SOCKET, SO_RCVBUF, &optval, &optlen);
1236                         OPENSSL_assert(ret >= 0);
1237                         OPENSSL_assert(optval >= 18445);
1238
1239                         /* Test if SCTP doesn't partially deliver below
1240                          * max record size (2^14 + 2048 + 13)
1241                          */
1242                         optlen = (socklen_t) sizeof(int);
1243                         ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_PARTIAL_DELIVERY_POINT,
1244                                          &optval, &optlen);
1245                         OPENSSL_assert(ret >= 0);
1246                         OPENSSL_assert(optval >= 18445);
1247
1248                         /* Partially delivered notification??? Probably a bug.... */
1249                         OPENSSL_assert(!(msg.msg_flags & MSG_NOTIFICATION));
1250
1251                         /* Everything seems ok till now, so it's most likely
1252                          * a message dropped by PR-SCTP.
1253                          */
1254                         memset(out, 0, outl);
1255                         BIO_set_retry_read(b);
1256                         return -1;
1257                         }
1258
1259                 BIO_clear_retry_flags(b);
1260                 if (ret < 0)
1261                         {
1262                         if (BIO_dgram_should_retry(ret))
1263                                 {
1264                                 BIO_set_retry_read(b);
1265                                 data->_errno = get_last_socket_error();
1266                                 }
1267                         }
1268
1269                 /* Test if peer uses SCTP-AUTH before continuing */
1270                 if (!data->peer_auth_tested)
1271                         {
1272                         int ii, auth_data = 0, auth_forward = 0;
1273                         unsigned char *p;
1274                         struct sctp_authchunks *authchunks;
1275
1276                         optlen = (socklen_t)(sizeof(sctp_assoc_t) + 256 * sizeof(uint8_t));
1277                         authchunks = OPENSSL_malloc(optlen);
1278                         memset(authchunks, 0, optlen);
1279                         ii = getsockopt(b->num, IPPROTO_SCTP, SCTP_PEER_AUTH_CHUNKS, authchunks, &optlen);
1280                         OPENSSL_assert(ii >= 0);
1281
1282                         for (p = (unsigned char*) authchunks->gauth_chunks;
1283                                  p < (unsigned char*) authchunks + optlen;
1284                                  p += sizeof(uint8_t))
1285                                 {
1286                                 if (*p == OPENSSL_SCTP_DATA_CHUNK_TYPE) auth_data = 1;
1287                                 if (*p == OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE) auth_forward = 1;
1288                                 }
1289
1290                         OPENSSL_free(authchunks);
1291
1292                         if (!auth_data || !auth_forward)
1293                                 {
1294                                 BIOerr(BIO_F_DGRAM_SCTP_READ,BIO_R_CONNECT_ERROR);
1295                                 return -1;
1296                                 }
1297
1298                         data->peer_auth_tested = 1;
1299                         }
1300                 }
1301         return(ret);
1302         }
1303
1304 static int dgram_sctp_write(BIO *b, const char *in, int inl)
1305         {
1306         int ret;
1307         bio_dgram_sctp_data *data = (bio_dgram_sctp_data *)b->ptr;
1308         struct bio_dgram_sctp_sndinfo *sinfo = &(data->sndinfo);
1309         struct bio_dgram_sctp_prinfo *pinfo = &(data->prinfo);
1310         struct bio_dgram_sctp_sndinfo handshake_sinfo;
1311         struct iovec iov[1];
1312         struct msghdr msg;
1313         struct cmsghdr *cmsg;
1314 #if defined(SCTP_SNDINFO) && defined(SCTP_PRINFO)
1315         char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndinfo)) + CMSG_SPACE(sizeof(struct sctp_prinfo))];
1316         struct sctp_sndinfo *sndinfo;
1317         struct sctp_prinfo *prinfo;
1318 #else
1319         char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndrcvinfo))];
1320         struct sctp_sndrcvinfo *sndrcvinfo;
1321 #endif
1322
1323         clear_socket_error();
1324
1325         /* If we're send anything else than application data,
1326          * disable all user parameters and flags.
1327          */
1328         if (in[0] != 23) {
1329                 memset(&handshake_sinfo, 0x00, sizeof(struct bio_dgram_sctp_sndinfo));
1330 #ifdef SCTP_SACK_IMMEDIATELY
1331                 handshake_sinfo.snd_flags = SCTP_SACK_IMMEDIATELY;
1332 #endif
1333                 sinfo = &handshake_sinfo;
1334         }
1335
1336         /* If we have to send a shutdown alert message and the
1337          * socket is not dry yet, we have to save it and send it
1338          * as soon as the socket gets dry.
1339          */
1340         if (data->save_shutdown && !BIO_dgram_sctp_wait_for_dry(b))
1341         {
1342                 data->saved_message.bio = b;
1343                 data->saved_message.length = inl;
1344                 data->saved_message.data = OPENSSL_malloc(inl);
1345                 memcpy(data->saved_message.data, in, inl);
1346                 return inl;
1347         }
1348
1349         iov[0].iov_base = (char *)in;
1350         iov[0].iov_len = inl;
1351         msg.msg_name = NULL;
1352         msg.msg_namelen = 0;
1353         msg.msg_iov = iov;
1354         msg.msg_iovlen = 1;
1355         msg.msg_control = (caddr_t)cmsgbuf;
1356         msg.msg_controllen = 0;
1357         msg.msg_flags = 0;
1358 #if defined(SCTP_SNDINFO) && defined(SCTP_PRINFO)
1359         cmsg = (struct cmsghdr *)cmsgbuf;
1360         cmsg->cmsg_level = IPPROTO_SCTP;
1361         cmsg->cmsg_type = SCTP_SNDINFO;
1362         cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndinfo));
1363         sndinfo = (struct sctp_sndinfo *)CMSG_DATA(cmsg);
1364         memset(sndinfo, 0, sizeof(struct sctp_sndinfo));
1365         sndinfo->snd_sid = sinfo->snd_sid;
1366         sndinfo->snd_flags = sinfo->snd_flags;
1367         sndinfo->snd_ppid = sinfo->snd_ppid;
1368         sndinfo->snd_context = sinfo->snd_context;
1369         msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_sndinfo));
1370
1371         cmsg = (struct cmsghdr *)&cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndinfo))];
1372         cmsg->cmsg_level = IPPROTO_SCTP;
1373         cmsg->cmsg_type = SCTP_PRINFO;
1374         cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_prinfo));
1375         prinfo = (struct sctp_prinfo *)CMSG_DATA(cmsg);
1376         memset(prinfo, 0, sizeof(struct sctp_prinfo));
1377         prinfo->pr_policy = pinfo->pr_policy;
1378         prinfo->pr_value = pinfo->pr_value;
1379         msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_prinfo));
1380 #else
1381         cmsg = (struct cmsghdr *)cmsgbuf;
1382         cmsg->cmsg_level = IPPROTO_SCTP;
1383         cmsg->cmsg_type = SCTP_SNDRCV;
1384         cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
1385         sndrcvinfo = (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
1386         memset(sndrcvinfo, 0, sizeof(struct sctp_sndrcvinfo));
1387         sndrcvinfo->sinfo_stream = sinfo->snd_sid;
1388         sndrcvinfo->sinfo_flags = sinfo->snd_flags;
1389 #ifdef __FreeBSD__
1390         sndrcvinfo->sinfo_flags |= pinfo->pr_policy;
1391 #endif
1392         sndrcvinfo->sinfo_ppid = sinfo->snd_ppid;
1393         sndrcvinfo->sinfo_context = sinfo->snd_context;
1394         sndrcvinfo->sinfo_timetolive = pinfo->pr_value;
1395         msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_sndrcvinfo));
1396 #endif
1397
1398         ret = sendmsg(b->num, &msg, 0);
1399
1400         BIO_clear_retry_flags(b);
1401         if (ret <= 0)
1402                 {
1403                 if (BIO_dgram_should_retry(ret))
1404                         {
1405                         BIO_set_retry_write(b);  
1406                         data->_errno = get_last_socket_error();
1407                         }
1408                 }
1409         return(ret);
1410         }
1411
1412 static long dgram_sctp_ctrl(BIO *b, int cmd, long num, void *ptr)
1413         {
1414         long ret=1;
1415         bio_dgram_sctp_data *data = NULL;
1416         socklen_t sockopt_len = 0;
1417         struct sctp_authkeyid authkeyid;
1418         struct sctp_authkey *authkey = NULL;
1419
1420         data = (bio_dgram_sctp_data *)b->ptr;
1421
1422         switch (cmd)
1423                 {
1424         case BIO_CTRL_DGRAM_QUERY_MTU:
1425                 /* Set to maximum (2^14)
1426                  * and ignore user input to enable transport
1427                  * protocol fragmentation.
1428                  * Returns always 2^14.
1429                  */
1430                 data->mtu = 16384;
1431                 ret = data->mtu;
1432                 break;
1433         case BIO_CTRL_DGRAM_SET_MTU:
1434                 /* Set to maximum (2^14)
1435                  * and ignore input to enable transport
1436                  * protocol fragmentation.
1437                  * Returns always 2^14.
1438                  */
1439                 data->mtu = 16384;
1440                 ret = data->mtu;
1441                 break;
1442         case BIO_CTRL_DGRAM_SET_CONNECTED:
1443         case BIO_CTRL_DGRAM_CONNECT:
1444                 /* Returns always -1. */
1445                 ret = -1;
1446                 break;
1447         case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
1448                 /* SCTP doesn't need the DTLS timer
1449                  * Returns always 1.
1450                  */
1451                 break;
1452         case BIO_CTRL_DGRAM_GET_MTU_OVERHEAD:
1453                 /* We allow transport protocol fragmentation so this is irrelevant */
1454                 ret = 0;
1455                 break;
1456         case BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE:
1457                 if (num > 0)
1458                         data->in_handshake = 1;
1459                 else
1460                         data->in_handshake = 0;
1461
1462                 ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_NODELAY, &data->in_handshake, sizeof(int));
1463                 break;
1464         case BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY:
1465                 /* New shared key for SCTP AUTH.
1466                  * Returns 0 on success, -1 otherwise.
1467                  */
1468
1469                 /* Get active key */
1470                 sockopt_len = sizeof(struct sctp_authkeyid);
1471                 ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY, &authkeyid, &sockopt_len);
1472                 if (ret < 0) break;
1473
1474                 /* Add new key */
1475                 sockopt_len = sizeof(struct sctp_authkey) + 64 * sizeof(uint8_t);
1476                 authkey = OPENSSL_malloc(sockopt_len);
1477                 if (authkey == NULL)
1478                         {
1479                         ret = -1;
1480                         break;
1481                         }
1482                 memset(authkey, 0x00, sockopt_len);
1483                 authkey->sca_keynumber = authkeyid.scact_keynumber + 1;
1484 #ifndef __FreeBSD__
1485                 /* This field is missing in FreeBSD 8.2 and earlier,
1486                  * and FreeBSD 8.3 and higher work without it.
1487                  */
1488                 authkey->sca_keylength = 64;
1489 #endif
1490                 memcpy(&authkey->sca_key[0], ptr, 64 * sizeof(uint8_t));
1491
1492                 ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_KEY, authkey, sockopt_len);
1493                 OPENSSL_free(authkey);
1494                 authkey = NULL;
1495                 if (ret < 0) break;
1496
1497                 /* Reset active key */
1498                 ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY,
1499                       &authkeyid, sizeof(struct sctp_authkeyid));
1500                 if (ret < 0) break;
1501
1502                 break;
1503         case BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY:
1504                 /* Returns 0 on success, -1 otherwise. */
1505
1506                 /* Get active key */
1507                 sockopt_len = sizeof(struct sctp_authkeyid);
1508                 ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY, &authkeyid, &sockopt_len);
1509                 if (ret < 0) break;
1510
1511                 /* Set active key */
1512                 authkeyid.scact_keynumber = authkeyid.scact_keynumber + 1;
1513                 ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY,
1514                       &authkeyid, sizeof(struct sctp_authkeyid));
1515                 if (ret < 0) break;
1516
1517                 /* CCS has been sent, so remember that and fall through
1518                  * to check if we need to deactivate an old key
1519                  */
1520                 data->ccs_sent = 1;
1521
1522         case BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD:
1523                 /* Returns 0 on success, -1 otherwise. */
1524
1525                 /* Has this command really been called or is this just a fall-through? */
1526                 if (cmd == BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD)
1527                         data->ccs_rcvd = 1;
1528
1529                 /* CSS has been both, received and sent, so deactivate an old key */
1530                 if (data->ccs_rcvd == 1 && data->ccs_sent == 1)
1531                         {
1532                         /* Get active key */
1533                         sockopt_len = sizeof(struct sctp_authkeyid);
1534                         ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY, &authkeyid, &sockopt_len);
1535                         if (ret < 0) break;
1536
1537                         /* Deactivate key or delete second last key if
1538                          * SCTP_AUTHENTICATION_EVENT is not available.
1539                          */
1540                         authkeyid.scact_keynumber = authkeyid.scact_keynumber - 1;
1541 #ifdef SCTP_AUTH_DEACTIVATE_KEY
1542                         sockopt_len = sizeof(struct sctp_authkeyid);
1543                         ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DEACTIVATE_KEY,
1544                               &authkeyid, sockopt_len);
1545                         if (ret < 0) break;
1546 #endif
1547 #ifndef SCTP_AUTHENTICATION_EVENT
1548                         if (authkeyid.scact_keynumber > 0)
1549                                 {
1550                                 authkeyid.scact_keynumber = authkeyid.scact_keynumber - 1;
1551                                 ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DELETE_KEY,
1552                                           &authkeyid, sizeof(struct sctp_authkeyid));
1553                                 if (ret < 0) break;
1554                                 }
1555 #endif
1556
1557                         data->ccs_rcvd = 0;
1558                         data->ccs_sent = 0;
1559                         }
1560                 break;
1561         case BIO_CTRL_DGRAM_SCTP_GET_SNDINFO:
1562                 /* Returns the size of the copied struct. */
1563                 if (num > (long) sizeof(struct bio_dgram_sctp_sndinfo))
1564                         num = sizeof(struct bio_dgram_sctp_sndinfo);
1565
1566                 memcpy(ptr, &(data->sndinfo), num);
1567                 ret = num;
1568                 break;
1569         case BIO_CTRL_DGRAM_SCTP_SET_SNDINFO:
1570                 /* Returns the size of the copied struct. */
1571                 if (num > (long) sizeof(struct bio_dgram_sctp_sndinfo))
1572                         num = sizeof(struct bio_dgram_sctp_sndinfo);
1573
1574                 memcpy(&(data->sndinfo), ptr, num);
1575                 break;
1576         case BIO_CTRL_DGRAM_SCTP_GET_RCVINFO:
1577                 /* Returns the size of the copied struct. */
1578                 if (num > (long) sizeof(struct bio_dgram_sctp_rcvinfo))
1579                         num = sizeof(struct bio_dgram_sctp_rcvinfo);
1580
1581                 memcpy(ptr, &data->rcvinfo, num);
1582
1583                 ret = num;
1584                 break;
1585         case BIO_CTRL_DGRAM_SCTP_SET_RCVINFO:
1586                 /* Returns the size of the copied struct. */
1587                 if (num > (long) sizeof(struct bio_dgram_sctp_rcvinfo))
1588                         num = sizeof(struct bio_dgram_sctp_rcvinfo);
1589
1590                 memcpy(&(data->rcvinfo), ptr, num);
1591                 break;
1592         case BIO_CTRL_DGRAM_SCTP_GET_PRINFO:
1593                 /* Returns the size of the copied struct. */
1594                 if (num > (long) sizeof(struct bio_dgram_sctp_prinfo))
1595                         num = sizeof(struct bio_dgram_sctp_prinfo);
1596
1597                 memcpy(ptr, &(data->prinfo), num);
1598                 ret = num;
1599                 break;
1600         case BIO_CTRL_DGRAM_SCTP_SET_PRINFO:
1601                 /* Returns the size of the copied struct. */
1602                 if (num > (long) sizeof(struct bio_dgram_sctp_prinfo))
1603                         num = sizeof(struct bio_dgram_sctp_prinfo);
1604
1605                 memcpy(&(data->prinfo), ptr, num);
1606                 break;
1607         case BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN:
1608                 /* Returns always 1. */
1609                 if (num > 0)
1610                         data->save_shutdown = 1;
1611                 else
1612                         data->save_shutdown = 0;
1613                 break;
1614
1615         default:
1616                 /* Pass to default ctrl function to
1617                  * process SCTP unspecific commands
1618                  */
1619                 ret=dgram_ctrl(b, cmd, num, ptr);
1620                 break;
1621                 }
1622         return(ret);
1623         }
1624
1625 int BIO_dgram_sctp_notification_cb(BIO *b,
1626                                    void (*handle_notifications)(BIO *bio, void *context, void *buf),
1627                                    void *context)
1628         {
1629         bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
1630
1631         if (handle_notifications != NULL)
1632                 {
1633                 data->handle_notifications = handle_notifications;
1634                 data->notification_context = context;
1635                 }
1636         else
1637                 return -1;
1638
1639         return 0;
1640         }
1641
1642 int BIO_dgram_sctp_wait_for_dry(BIO *b)
1643 {
1644         int is_dry = 0;
1645         int n, sockflags, ret;
1646         union sctp_notification snp;
1647         struct msghdr msg;
1648         struct iovec iov;
1649 #ifdef SCTP_EVENT
1650         struct sctp_event event;
1651 #else
1652         struct sctp_event_subscribe event;
1653         socklen_t eventsize;
1654 #endif
1655         bio_dgram_sctp_data *data = (bio_dgram_sctp_data *)b->ptr;
1656
1657         /* set sender dry event */
1658 #ifdef SCTP_EVENT
1659         memset(&event, 0, sizeof(struct sctp_event));
1660         event.se_assoc_id = 0;
1661         event.se_type = SCTP_SENDER_DRY_EVENT;
1662         event.se_on = 1;
1663         ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event, sizeof(struct sctp_event));
1664 #else
1665         eventsize = sizeof(struct sctp_event_subscribe);
1666         ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, &eventsize);
1667         if (ret < 0)
1668                 return -1;
1669         
1670         event.sctp_sender_dry_event = 1;
1671         
1672         ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, sizeof(struct sctp_event_subscribe));
1673 #endif
1674         if (ret < 0)
1675                 return -1;
1676
1677         /* peek for notification */
1678         memset(&snp, 0x00, sizeof(union sctp_notification));
1679         iov.iov_base = (char *)&snp;
1680         iov.iov_len = sizeof(union sctp_notification);
1681         msg.msg_name = NULL;
1682         msg.msg_namelen = 0;
1683         msg.msg_iov = &iov;
1684         msg.msg_iovlen = 1;
1685         msg.msg_control = NULL;
1686         msg.msg_controllen = 0;
1687         msg.msg_flags = 0;
1688
1689         n = recvmsg(b->num, &msg, MSG_PEEK);
1690         if (n <= 0)
1691                 {
1692                 if ((n < 0) && (get_last_socket_error() != EAGAIN) && (get_last_socket_error() != EWOULDBLOCK))
1693                         return -1;
1694                 else
1695                         return 0;
1696                 }
1697
1698         /* if we find a notification, process it and try again if necessary */
1699         while (msg.msg_flags & MSG_NOTIFICATION)
1700                 {
1701                 memset(&snp, 0x00, sizeof(union sctp_notification));
1702                 iov.iov_base = (char *)&snp;
1703                 iov.iov_len = sizeof(union sctp_notification);
1704                 msg.msg_name = NULL;
1705                 msg.msg_namelen = 0;
1706                 msg.msg_iov = &iov;
1707                 msg.msg_iovlen = 1;
1708                 msg.msg_control = NULL;
1709                 msg.msg_controllen = 0;
1710                 msg.msg_flags = 0;
1711
1712                 n = recvmsg(b->num, &msg, 0);
1713                 if (n <= 0)
1714                         {
1715                         if ((n < 0) && (get_last_socket_error() != EAGAIN) && (get_last_socket_error() != EWOULDBLOCK))
1716                                 return -1;
1717                         else
1718                                 return is_dry;
1719                         }
1720                 
1721                 if (snp.sn_header.sn_type == SCTP_SENDER_DRY_EVENT)
1722                         {
1723                         is_dry = 1;
1724
1725                         /* disable sender dry event */
1726 #ifdef SCTP_EVENT
1727                         memset(&event, 0, sizeof(struct sctp_event));
1728                         event.se_assoc_id = 0;
1729                         event.se_type = SCTP_SENDER_DRY_EVENT;
1730                         event.se_on = 0;
1731                         ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event, sizeof(struct sctp_event));
1732 #else
1733                         eventsize = (socklen_t) sizeof(struct sctp_event_subscribe);
1734                         ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, &eventsize);
1735                         if (ret < 0)
1736                                 return -1;
1737
1738                         event.sctp_sender_dry_event = 0;
1739
1740                         ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, sizeof(struct sctp_event_subscribe));
1741 #endif
1742                         if (ret < 0)
1743                                 return -1;
1744                         }
1745
1746 #ifdef SCTP_AUTHENTICATION_EVENT
1747                 if (snp.sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
1748                         dgram_sctp_handle_auth_free_key_event(b, &snp);
1749 #endif
1750
1751                 if (data->handle_notifications != NULL)
1752                         data->handle_notifications(b, data->notification_context, (void*) &snp);
1753
1754                 /* found notification, peek again */
1755                 memset(&snp, 0x00, sizeof(union sctp_notification));
1756                 iov.iov_base = (char *)&snp;
1757                 iov.iov_len = sizeof(union sctp_notification);
1758                 msg.msg_name = NULL;
1759                 msg.msg_namelen = 0;
1760                 msg.msg_iov = &iov;
1761                 msg.msg_iovlen = 1;
1762                 msg.msg_control = NULL;
1763                 msg.msg_controllen = 0;
1764                 msg.msg_flags = 0;
1765
1766                 /* if we have seen the dry already, don't wait */
1767                 if (is_dry)
1768                         {
1769                         sockflags = fcntl(b->num, F_GETFL, 0);
1770                         fcntl(b->num, F_SETFL, O_NONBLOCK);
1771                         }
1772
1773                 n = recvmsg(b->num, &msg, MSG_PEEK);
1774
1775                 if (is_dry)
1776                         {
1777                         fcntl(b->num, F_SETFL, sockflags);
1778                         }
1779
1780                 if (n <= 0)
1781                         {
1782                         if ((n < 0) && (get_last_socket_error() != EAGAIN) && (get_last_socket_error() != EWOULDBLOCK))
1783                                 return -1;
1784                         else
1785                                 return is_dry;
1786                         }
1787                 }
1788
1789         /* read anything else */
1790         return is_dry;
1791 }
1792
1793 int BIO_dgram_sctp_msg_waiting(BIO *b)
1794         {
1795         int n, sockflags;
1796         union sctp_notification snp;
1797         struct msghdr msg;
1798         struct iovec iov;
1799         bio_dgram_sctp_data *data = (bio_dgram_sctp_data *)b->ptr;
1800
1801         /* Check if there are any messages waiting to be read */
1802         do
1803                 {
1804                 memset(&snp, 0x00, sizeof(union sctp_notification));
1805                 iov.iov_base = (char *)&snp;
1806                 iov.iov_len = sizeof(union sctp_notification);
1807                 msg.msg_name = NULL;
1808                 msg.msg_namelen = 0;
1809                 msg.msg_iov = &iov;
1810                 msg.msg_iovlen = 1;
1811                 msg.msg_control = NULL;
1812                 msg.msg_controllen = 0;
1813                 msg.msg_flags = 0;
1814
1815                 sockflags = fcntl(b->num, F_GETFL, 0);
1816                 fcntl(b->num, F_SETFL, O_NONBLOCK);
1817                 n = recvmsg(b->num, &msg, MSG_PEEK);
1818                 fcntl(b->num, F_SETFL, sockflags);
1819
1820                 /* if notification, process and try again */
1821                 if (n > 0 && (msg.msg_flags & MSG_NOTIFICATION))
1822                         {
1823 #ifdef SCTP_AUTHENTICATION_EVENT
1824                         if (snp.sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
1825                                 dgram_sctp_handle_auth_free_key_event(b, &snp);
1826 #endif
1827
1828                         memset(&snp, 0x00, sizeof(union sctp_notification));
1829                         iov.iov_base = (char *)&snp;
1830                         iov.iov_len = sizeof(union sctp_notification);
1831                         msg.msg_name = NULL;
1832                         msg.msg_namelen = 0;
1833                         msg.msg_iov = &iov;
1834                         msg.msg_iovlen = 1;
1835                         msg.msg_control = NULL;
1836                         msg.msg_controllen = 0;
1837                         msg.msg_flags = 0;
1838                         n = recvmsg(b->num, &msg, 0);
1839
1840                         if (data->handle_notifications != NULL)
1841                                 data->handle_notifications(b, data->notification_context, (void*) &snp);
1842                         }
1843
1844                 } while (n > 0 && (msg.msg_flags & MSG_NOTIFICATION));
1845
1846         /* Return 1 if there is a message to be read, return 0 otherwise. */
1847         if (n > 0)
1848                 return 1;
1849         else
1850                 return 0;
1851         }
1852
1853 static int dgram_sctp_puts(BIO *bp, const char *str)
1854         {
1855         int n,ret;
1856
1857         n=strlen(str);
1858         ret=dgram_sctp_write(bp,str,n);
1859         return(ret);
1860         }
1861 #endif
1862
1863 static int BIO_dgram_should_retry(int i)
1864         {
1865         int err;
1866
1867         if ((i == 0) || (i == -1))
1868                 {
1869                 err=get_last_socket_error();
1870
1871 #if defined(OPENSSL_SYS_WINDOWS)
1872         /* If the socket return value (i) is -1
1873          * and err is unexpectedly 0 at this point,
1874          * the error code was overwritten by
1875          * another system call before this error
1876          * handling is called.
1877          */
1878 #endif
1879
1880                 return(BIO_dgram_non_fatal_error(err));
1881                 }
1882         return(0);
1883         }
1884
1885 int BIO_dgram_non_fatal_error(int err)
1886         {
1887         switch (err)
1888                 {
1889 #if defined(OPENSSL_SYS_WINDOWS)
1890 # if defined(WSAEWOULDBLOCK)
1891         case WSAEWOULDBLOCK:
1892 # endif
1893
1894 # if 0 /* This appears to always be an error */
1895 #  if defined(WSAENOTCONN)
1896         case WSAENOTCONN:
1897 #  endif
1898 # endif
1899 #endif
1900
1901 #ifdef EWOULDBLOCK
1902 # ifdef WSAEWOULDBLOCK
1903 #  if WSAEWOULDBLOCK != EWOULDBLOCK
1904         case EWOULDBLOCK:
1905 #  endif
1906 # else
1907         case EWOULDBLOCK:
1908 # endif
1909 #endif
1910
1911 #ifdef EINTR
1912         case EINTR:
1913 #endif
1914
1915 #ifdef EAGAIN
1916 #if EWOULDBLOCK != EAGAIN
1917         case EAGAIN:
1918 # endif
1919 #endif
1920
1921 #ifdef EPROTO
1922         case EPROTO:
1923 #endif
1924
1925 #ifdef EINPROGRESS
1926         case EINPROGRESS:
1927 #endif
1928
1929 #ifdef EALREADY
1930         case EALREADY:
1931 #endif
1932
1933                 return(1);
1934                 /* break; */
1935         default:
1936                 break;
1937                 }
1938         return(0);
1939         }
1940
1941 static void get_current_time(struct timeval *t)
1942         {
1943 #if defined(_WIN32)
1944         SYSTEMTIME st;
1945         union { unsigned __int64 ul; FILETIME ft; } now;
1946
1947         GetSystemTime(&st);
1948         SystemTimeToFileTime(&st,&now.ft);
1949 #ifdef  __MINGW32__
1950         now.ul -= 116444736000000000ULL;
1951 #else
1952         now.ul -= 116444736000000000UI64;       /* re-bias to 1/1/1970 */
1953 #endif
1954         t->tv_sec  = (long)(now.ul/10000000);
1955         t->tv_usec = ((int)(now.ul%10000000))/10;
1956 #elif defined(OPENSSL_SYS_VMS)
1957         struct timeb tb;
1958         ftime(&tb);
1959         t->tv_sec = (long)tb.time;
1960         t->tv_usec = (long)tb.millitm * 1000;
1961 #else
1962         gettimeofday(t, NULL);
1963 #endif
1964         }
1965
1966 #endif