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