Update from 1.0.0-stable.
[openssl.git] / crypto / bio / bss_dgram.c
1 /* crypto/bio/bio_dgram.c */
2 /* 
3  * DTLS implementation written by Nagendra Modadugu
4  * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.  
5  */
6 /* ====================================================================
7  * Copyright (c) 1999-2005 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer. 
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    openssl-core@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59
60 #ifndef OPENSSL_NO_DGRAM
61
62 #include <stdio.h>
63 #include <errno.h>
64 #define USE_SOCKETS
65 #include "cryptlib.h"
66
67 #include <openssl/bio.h>
68
69 #if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VMS)
70 #include <sys/timeb.h>
71 #endif
72
73 #define IP_MTU      14 /* linux is lame */
74
75 #ifdef WATT32
76 #define sock_write SockWrite  /* Watt-32 uses same names */
77 #define sock_read  SockRead
78 #define sock_puts  SockPuts
79 #endif
80
81 static int dgram_write(BIO *h, const char *buf, int num);
82 static int dgram_read(BIO *h, char *buf, int size);
83 static int dgram_puts(BIO *h, const char *str);
84 static long dgram_ctrl(BIO *h, int cmd, long arg1, void *arg2);
85 static int dgram_new(BIO *h);
86 static int dgram_free(BIO *data);
87 static int dgram_clear(BIO *bio);
88
89 static int BIO_dgram_should_retry(int s);
90
91 static void get_current_time(struct timeval *t);
92
93 static BIO_METHOD methods_dgramp=
94         {
95         BIO_TYPE_DGRAM,
96         "datagram socket",
97         dgram_write,
98         dgram_read,
99         dgram_puts,
100         NULL, /* dgram_gets, */
101         dgram_ctrl,
102         dgram_new,
103         dgram_free,
104         NULL,
105         };
106
107 typedef struct bio_dgram_data_st
108         {
109         struct sockaddr peer;
110         unsigned int connected;
111         unsigned int _errno;
112         unsigned int mtu;
113         struct timeval next_timeout;
114         struct timeval socket_timeout;
115         } bio_dgram_data;
116
117 BIO_METHOD *BIO_s_datagram(void)
118         {
119         return(&methods_dgramp);
120         }
121
122 BIO *BIO_new_dgram(int fd, int close_flag)
123         {
124         BIO *ret;
125
126         ret=BIO_new(BIO_s_datagram());
127         if (ret == NULL) return(NULL);
128         BIO_set_fd(ret,fd,close_flag);
129         return(ret);
130         }
131
132 static int dgram_new(BIO *bi)
133         {
134         bio_dgram_data *data = NULL;
135
136         bi->init=0;
137         bi->num=0;
138         data = OPENSSL_malloc(sizeof(bio_dgram_data));
139         if (data == NULL)
140                 return 0;
141         memset(data, 0x00, sizeof(bio_dgram_data));
142     bi->ptr = data;
143
144         bi->flags=0;
145         return(1);
146         }
147
148 static int dgram_free(BIO *a)
149         {
150         bio_dgram_data *data;
151
152         if (a == NULL) return(0);
153         if ( ! dgram_clear(a))
154                 return 0;
155
156         data = (bio_dgram_data *)a->ptr;
157         if(data != NULL) OPENSSL_free(data);
158
159         return(1);
160         }
161
162 static int dgram_clear(BIO *a)
163         {
164         if (a == NULL) return(0);
165         if (a->shutdown)
166                 {
167                 if (a->init)
168                         {
169                         SHUTDOWN2(a->num);
170                         }
171                 a->init=0;
172                 a->flags=0;
173                 }
174         return(1);
175         }
176
177 static void dgram_adjust_rcv_timeout(BIO *b)
178         {
179 #if defined(SO_RCVTIMEO)
180         bio_dgram_data *data = (bio_dgram_data *)b->ptr;
181         int sz = sizeof(int);
182
183         /* Is a timer active? */
184         if (data->next_timeout.tv_sec > 0 || data->next_timeout.tv_usec > 0)
185                 {
186                 struct timeval timenow, timeleft;
187
188                 /* Read current socket timeout */
189 #ifdef OPENSSL_SYS_WINDOWS
190                 int timeout;
191                 if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
192                                            (void*)&timeout, &sz) < 0)
193                         { perror("getsockopt"); }
194                 else
195                         {
196                         data->socket_timeout.tv_sec = timeout / 1000;
197                         data->socket_timeout.tv_usec = (timeout % 1000) * 1000;
198                         }
199 #else
200                 if ( getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, 
201                                                 &(data->socket_timeout), (void *)&sz) < 0)
202                         { perror("getsockopt"); }
203 #endif
204
205                 /* Get current time */
206                 get_current_time(&timenow);
207
208                 /* Calculate time left until timer expires */
209                 memcpy(&timeleft, &(data->next_timeout), sizeof(struct timeval));
210                 timeleft.tv_sec -= timenow.tv_sec;
211                 timeleft.tv_usec -= timenow.tv_usec;
212                 if (timeleft.tv_usec < 0)
213                         {
214                         timeleft.tv_sec--;
215                         timeleft.tv_usec += 1000000;
216                         }
217
218                 /* Adjust socket timeout if next handhake message timer
219                  * will expire earlier.
220                  */
221                 if (data->socket_timeout.tv_sec < timeleft.tv_sec ||
222                         (data->socket_timeout.tv_sec == timeleft.tv_sec &&
223                          data->socket_timeout.tv_usec <= timeleft.tv_usec))
224                         {
225 #ifdef OPENSSL_SYS_WINDOWS
226                         timeout = timeleft.tv_sec * 1000 + timeleft.tv_usec / 1000;
227                         if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
228                                                    (void*)&timeout, sizeof(timeout)) < 0)
229                                 { perror("setsockopt"); }
230 #else
231                         if ( setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, &timeleft,
232                                                         sizeof(struct timeval)) < 0)
233                                 { perror("setsockopt"); }
234 #endif
235                         }
236                 }
237 #endif
238         }
239
240 static void dgram_reset_rcv_timeout(BIO *b)
241         {
242 #if defined(SO_RCVTIMEO)
243         bio_dgram_data *data = (bio_dgram_data *)b->ptr;
244 #ifdef OPENSSL_SYS_WINDOWS
245         int timeout = data->socket_timeout.tv_sec * 1000 +
246                                   data->socket_timeout.tv_usec / 1000;
247         if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
248                                    (void*)&timeout, sizeof(timeout)) < 0)
249                 { perror("setsockopt"); }
250 #else
251         if ( setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, &(data->socket_timeout),
252                                         sizeof(struct timeval)) < 0)
253                 { perror("setsockopt"); }
254 #endif
255 #endif
256         }
257
258 static int dgram_read(BIO *b, char *out, int outl)
259         {
260         int ret=0;
261         bio_dgram_data *data = (bio_dgram_data *)b->ptr;
262
263         struct sockaddr peer;
264         int peerlen = sizeof(peer);
265
266         if (out != NULL)
267                 {
268                 clear_socket_error();
269                 memset(&peer, 0x00, peerlen);
270                 /* Last arg in recvfrom is signed on some platforms and
271                  * unsigned on others. It is of type socklen_t on some
272                  * but this is not universal. Cast to (void *) to avoid
273                  * compiler warnings.
274                  */
275                 dgram_adjust_rcv_timeout(b);
276                 ret=recvfrom(b->num,out,outl,0,&peer,(void *)&peerlen);
277                 dgram_reset_rcv_timeout(b);
278
279                 if ( ! data->connected  && ret > 0)
280                         BIO_ctrl(b, BIO_CTRL_DGRAM_CONNECT, 0, &peer);
281
282                 BIO_clear_retry_flags(b);
283                 if (ret <= 0)
284                         {
285                         if (BIO_dgram_should_retry(ret))
286                                 {
287                                 BIO_set_retry_read(b);
288                                 data->_errno = get_last_socket_error();
289                                 }
290                         memset(&(data->hstimeout), 0, sizeof(struct timeval));
291                         }
292                 }
293         return(ret);
294         }
295
296 static int dgram_write(BIO *b, const char *in, int inl)
297         {
298         int ret;
299         bio_dgram_data *data = (bio_dgram_data *)b->ptr;
300         clear_socket_error();
301
302     if ( data->connected )
303         ret=writesocket(b->num,in,inl);
304     else
305 #if defined(NETWARE_CLIB) && defined(NETWARE_BSDSOCK)
306         ret=sendto(b->num, (char *)in, inl, 0, &data->peer, sizeof(data->peer));
307 #else
308         ret=sendto(b->num, in, inl, 0, &data->peer, sizeof(data->peer));
309 #endif
310
311         BIO_clear_retry_flags(b);
312         if (ret <= 0)
313                 {
314                 if (BIO_sock_should_retry(ret))
315                         {
316                         BIO_set_retry_write(b);  
317                         data->_errno = get_last_socket_error();
318
319 #if 0 /* higher layers are responsible for querying MTU, if necessary */
320                         if ( data->_errno == EMSGSIZE)
321                                 /* retrieve the new MTU */
322                                 BIO_ctrl(b, BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
323 #endif
324                         }
325                 }
326         return(ret);
327         }
328
329 static long dgram_ctrl(BIO *b, int cmd, long num, void *ptr)
330         {
331         long ret=1;
332         int *ip;
333         struct sockaddr *to = NULL;
334         bio_dgram_data *data = NULL;
335         long sockopt_val = 0;
336         unsigned int sockopt_len = 0;
337
338         data = (bio_dgram_data *)b->ptr;
339
340         switch (cmd)
341                 {
342         case BIO_CTRL_RESET:
343                 num=0;
344         case BIO_C_FILE_SEEK:
345                 ret=0;
346                 break;
347         case BIO_C_FILE_TELL:
348         case BIO_CTRL_INFO:
349                 ret=0;
350                 break;
351         case BIO_C_SET_FD:
352                 dgram_clear(b);
353                 b->num= *((int *)ptr);
354                 b->shutdown=(int)num;
355                 b->init=1;
356                 break;
357         case BIO_C_GET_FD:
358                 if (b->init)
359                         {
360                         ip=(int *)ptr;
361                         if (ip != NULL) *ip=b->num;
362                         ret=b->num;
363                         }
364                 else
365                         ret= -1;
366                 break;
367         case BIO_CTRL_GET_CLOSE:
368                 ret=b->shutdown;
369                 break;
370         case BIO_CTRL_SET_CLOSE:
371                 b->shutdown=(int)num;
372                 break;
373         case BIO_CTRL_PENDING:
374         case BIO_CTRL_WPENDING:
375                 ret=0;
376                 break;
377         case BIO_CTRL_DUP:
378         case BIO_CTRL_FLUSH:
379                 ret=1;
380                 break;
381         case BIO_CTRL_DGRAM_CONNECT:
382                 to = (struct sockaddr *)ptr;
383 #if 0
384                 if (connect(b->num, to, sizeof(struct sockaddr)) < 0)
385                         { perror("connect"); ret = 0; }
386                 else
387                         {
388 #endif
389                         memcpy(&(data->peer),to, sizeof(struct sockaddr));
390 #if 0
391                         }
392 #endif
393                 break;
394                 /* (Linux)kernel sets DF bit on outgoing IP packets */
395 #ifdef IP_MTU_DISCOVER
396         case BIO_CTRL_DGRAM_MTU_DISCOVER:
397                 sockopt_val = IP_PMTUDISC_DO;
398                 if ((ret = setsockopt(b->num, IPPROTO_IP, IP_MTU_DISCOVER,
399                         &sockopt_val, sizeof(sockopt_val))) < 0)
400                         perror("setsockopt");
401                 break;
402 #endif
403         case BIO_CTRL_DGRAM_QUERY_MTU:
404          sockopt_len = sizeof(sockopt_val);
405                 if ((ret = getsockopt(b->num, IPPROTO_IP, IP_MTU, (void *)&sockopt_val,
406                         &sockopt_len)) < 0 || sockopt_val < 0)
407                         { ret = 0; }
408                 else
409                         {
410                         data->mtu = sockopt_val;
411                         ret = data->mtu;
412                         }
413                 break;
414         case BIO_CTRL_DGRAM_GET_MTU:
415                 return data->mtu;
416                 break;
417         case BIO_CTRL_DGRAM_SET_MTU:
418                 data->mtu = num;
419                 ret = num;
420                 break;
421         case BIO_CTRL_DGRAM_SET_CONNECTED:
422                 to = (struct sockaddr *)ptr;
423
424                 if ( to != NULL)
425                         {
426                         data->connected = 1;
427                         memcpy(&(data->peer),to, sizeof(struct sockaddr));
428                         }
429                 else
430                         {
431                         data->connected = 0;
432                         memset(&(data->peer), 0x00, sizeof(struct sockaddr));
433                         }
434                 break;
435     case BIO_CTRL_DGRAM_SET_PEER:
436         to = (struct sockaddr *) ptr;
437
438         memcpy(&(data->peer), to, sizeof(struct sockaddr));
439         break;
440         case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
441                 memcpy(&(data->next_timeout), ptr, sizeof(struct timeval));             
442                 break;
443 #if defined(SO_RCVTIMEO)
444         case BIO_CTRL_DGRAM_SET_RECV_TIMEOUT:
445 #ifdef OPENSSL_SYS_WINDOWS
446                 {
447                 struct timeval *tv = (struct timeval *)ptr;
448                 int timeout = tv->tv_sec * 1000 + tv->tv_usec/1000;
449                 if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
450                         (void*)&timeout, sizeof(timeout)) < 0)
451                         { perror("setsockopt"); ret = -1; }
452                 }
453 #else
454                 if ( setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, ptr,
455                         sizeof(struct timeval)) < 0)
456                         { perror("setsockopt"); ret = -1; }
457 #endif
458                 break;
459         case BIO_CTRL_DGRAM_GET_RECV_TIMEOUT:
460 #ifdef OPENSSL_SYS_WINDOWS
461                 {
462                 int timeout, sz = sizeof(timeout);
463                 struct timeval *tv = (struct timeval *)ptr;
464                 if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
465                         (void*)&timeout, &sz) < 0)
466                         { perror("getsockopt"); ret = -1; }
467                 else
468                         {
469                         tv->tv_sec = timeout / 1000;
470                         tv->tv_usec = (timeout % 1000) * 1000;
471                         ret = sizeof(*tv);
472                         }
473                 }
474 #else
475                 if ( getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, 
476                         ptr, (void *)&ret) < 0)
477                         { perror("getsockopt"); ret = -1; }
478 #endif
479                 break;
480 #endif
481 #if defined(SO_SNDTIMEO)
482         case BIO_CTRL_DGRAM_SET_SEND_TIMEOUT:
483 #ifdef OPENSSL_SYS_WINDOWS
484                 {
485                 struct timeval *tv = (struct timeval *)ptr;
486                 int timeout = tv->tv_sec * 1000 + tv->tv_usec/1000;
487                 if (setsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
488                         (void*)&timeout, sizeof(timeout)) < 0)
489                         { perror("setsockopt"); ret = -1; }
490                 }
491 #else
492                 if ( setsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO, ptr,
493                         sizeof(struct timeval)) < 0)
494                         { perror("setsockopt"); ret = -1; }
495 #endif
496                 break;
497         case BIO_CTRL_DGRAM_GET_SEND_TIMEOUT:
498 #ifdef OPENSSL_SYS_WINDOWS
499                 {
500                 int timeout, sz = sizeof(timeout);
501                 struct timeval *tv = (struct timeval *)ptr;
502                 if (getsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
503                         (void*)&timeout, &sz) < 0)
504                         { perror("getsockopt"); ret = -1; }
505                 else
506                         {
507                         tv->tv_sec = timeout / 1000;
508                         tv->tv_usec = (timeout % 1000) * 1000;
509                         ret = sizeof(*tv);
510                         }
511                 }
512 #else
513                 if ( getsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO, 
514                         ptr, (void *)&ret) < 0)
515                         { perror("getsockopt"); ret = -1; }
516 #endif
517                 break;
518 #endif
519         case BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP:
520                 /* fall-through */
521         case BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP:
522 #ifdef OPENSSL_SYS_WINDOWS
523                 if ( data->_errno == WSAETIMEDOUT)
524 #else
525                 if ( data->_errno == EAGAIN)
526 #endif
527                         {
528                         ret = 1;
529                         data->_errno = 0;
530                         }
531                 else
532                         ret = 0;
533                 break;
534 #ifdef EMSGSIZE
535         case BIO_CTRL_DGRAM_MTU_EXCEEDED:
536                 if ( data->_errno == EMSGSIZE)
537                         {
538                         ret = 1;
539                         data->_errno = 0;
540                         }
541                 else
542                         ret = 0;
543                 break;
544 #endif
545         default:
546                 ret=0;
547                 break;
548                 }
549         return(ret);
550         }
551
552 static int dgram_puts(BIO *bp, const char *str)
553         {
554         int n,ret;
555
556         n=strlen(str);
557         ret=dgram_write(bp,str,n);
558         return(ret);
559         }
560
561 static int BIO_dgram_should_retry(int i)
562         {
563         int err;
564
565         if ((i == 0) || (i == -1))
566                 {
567                 err=get_last_socket_error();
568
569 #if defined(OPENSSL_SYS_WINDOWS) && 0 /* more microsoft stupidity? perhaps not? Ben 4/1/99 */
570                 if ((i == -1) && (err == 0))
571                         return(1);
572 #endif
573
574                 return(BIO_dgram_non_fatal_error(err));
575                 }
576         return(0);
577         }
578
579 int BIO_dgram_non_fatal_error(int err)
580         {
581         switch (err)
582                 {
583 #if defined(OPENSSL_SYS_WINDOWS)
584 # if defined(WSAEWOULDBLOCK)
585         case WSAEWOULDBLOCK:
586 # endif
587
588 # if 0 /* This appears to always be an error */
589 #  if defined(WSAENOTCONN)
590         case WSAENOTCONN:
591 #  endif
592 # endif
593 #endif
594
595 #ifdef EWOULDBLOCK
596 # ifdef WSAEWOULDBLOCK
597 #  if WSAEWOULDBLOCK != EWOULDBLOCK
598         case EWOULDBLOCK:
599 #  endif
600 # else
601         case EWOULDBLOCK:
602 # endif
603 #endif
604
605 #if defined(ENOTCONN)
606         case ENOTCONN:
607 #endif
608
609 #ifdef EINTR
610         case EINTR:
611 #endif
612
613 #ifdef EAGAIN
614 #if EWOULDBLOCK != EAGAIN
615         case EAGAIN:
616 # endif
617 #endif
618
619 #ifdef EPROTO
620         case EPROTO:
621 #endif
622
623 #ifdef EINPROGRESS
624         case EINPROGRESS:
625 #endif
626
627 #ifdef EALREADY
628         case EALREADY:
629 #endif
630
631 /* DF bit set, and packet larger than MTU */
632 #ifdef EMSGSIZE
633         case EMSGSIZE:
634 #endif
635
636                 return(1);
637                 /* break; */
638         default:
639                 break;
640                 }
641         return(0);
642         }
643 #endif
644
645 static void get_current_time(struct timeval *t)
646         {
647 #ifdef OPENSSL_SYS_WIN32
648         struct _timeb tb;
649         _ftime(&tb);
650         t->tv_sec = (long)tb.time;
651         t->tv_usec = (long)tb.millitm * 1000;
652 #elif defined(OPENSSL_SYS_VMS)
653         struct timeb tb;
654         ftime(&tb);
655         t->tv_sec = (long)tb.time;
656         t->tv_usec = (long)tb.millitm * 1000;
657 #else
658         gettimeofday(t, NULL);
659 #endif
660         }