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