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