Update from HEAD.
[oweals/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 #ifdef OPENSSL_SYS_LINUX
74 #define IP_MTU      14 /* linux is lame */
75 #endif
76
77 #ifdef WATT32
78 #define sock_write SockWrite  /* Watt-32 uses same names */
79 #define sock_read  SockRead
80 #define sock_puts  SockPuts
81 #endif
82
83 static int dgram_write(BIO *h, const char *buf, int num);
84 static int dgram_read(BIO *h, char *buf, int size);
85 static int dgram_puts(BIO *h, const char *str);
86 static long dgram_ctrl(BIO *h, int cmd, long arg1, void *arg2);
87 static int dgram_new(BIO *h);
88 static int dgram_free(BIO *data);
89 static int dgram_clear(BIO *bio);
90
91 static int BIO_dgram_should_retry(int s);
92
93 static void get_current_time(struct timeval *t);
94
95 static BIO_METHOD methods_dgramp=
96         {
97         BIO_TYPE_DGRAM,
98         "datagram socket",
99         dgram_write,
100         dgram_read,
101         dgram_puts,
102         NULL, /* dgram_gets, */
103         dgram_ctrl,
104         dgram_new,
105         dgram_free,
106         NULL,
107         };
108
109 typedef struct bio_dgram_data_st
110         {
111         struct sockaddr peer;
112         unsigned int connected;
113         unsigned int _errno;
114         unsigned int mtu;
115         struct timeval hstimeoutdiff;
116         struct timeval hstimeout;
117         } bio_dgram_data;
118
119 BIO_METHOD *BIO_s_datagram(void)
120         {
121         return(&methods_dgramp);
122         }
123
124 BIO *BIO_new_dgram(int fd, int close_flag)
125         {
126         BIO *ret;
127
128         ret=BIO_new(BIO_s_datagram());
129         if (ret == NULL) return(NULL);
130         BIO_set_fd(ret,fd,close_flag);
131         return(ret);
132         }
133
134 static int dgram_new(BIO *bi)
135         {
136         bio_dgram_data *data = NULL;
137
138         bi->init=0;
139         bi->num=0;
140         data = OPENSSL_malloc(sizeof(bio_dgram_data));
141         if (data == NULL)
142                 return 0;
143         memset(data, 0x00, sizeof(bio_dgram_data));
144     bi->ptr = data;
145
146         bi->flags=0;
147         return(1);
148         }
149
150 static int dgram_free(BIO *a)
151         {
152         bio_dgram_data *data;
153
154         if (a == NULL) return(0);
155         if ( ! dgram_clear(a))
156                 return 0;
157
158         data = (bio_dgram_data *)a->ptr;
159         if(data != NULL) OPENSSL_free(data);
160
161         return(1);
162         }
163
164 static int dgram_clear(BIO *a)
165         {
166         if (a == NULL) return(0);
167         if (a->shutdown)
168                 {
169                 if (a->init)
170                         {
171                         SHUTDOWN2(a->num);
172                         }
173                 a->init=0;
174                 a->flags=0;
175                 }
176         return(1);
177         }
178         
179 static int dgram_read(BIO *b, char *out, int outl)
180         {
181         int ret=0;
182         bio_dgram_data *data = (bio_dgram_data *)b->ptr;
183
184         struct sockaddr peer;
185         int peerlen = sizeof(peer);
186
187         if (out != NULL)
188                 {
189                 clear_socket_error();
190                 memset(&peer, 0x00, peerlen);
191                 /* Last arg in recvfrom is signed on some platforms and
192                  * unsigned on others. It is of type socklen_t on some
193                  * but this is not universal. Cast to (void *) to avoid
194                  * compiler warnings.
195                  */
196                 ret=recvfrom(b->num,out,outl,0,&peer,(void *)&peerlen);
197
198                 if ( ! data->connected  && ret > 0)
199                         BIO_ctrl(b, BIO_CTRL_DGRAM_CONNECT, 0, &peer);
200
201                 BIO_clear_retry_flags(b);
202                 if (ret <= 0)
203                         {
204                         if (BIO_dgram_should_retry(ret))
205                                 {
206                                 BIO_set_retry_read(b);
207                                 data->_errno = get_last_socket_error();
208                                 }
209                         memset(&(data->hstimeout), 0, sizeof(struct timeval));
210                         }
211                 else
212                         {
213                         if (data->hstimeout.tv_sec > 0 || data->hstimeout.tv_usec > 0)
214                                 {
215                                 struct timeval curtime;
216                                 get_current_time(&curtime);
217
218                                 if (curtime.tv_sec >= data->hstimeout.tv_sec &&
219                                         curtime.tv_usec >= data->hstimeout.tv_usec)
220                                         {
221                                         data->_errno = EAGAIN;
222                                         ret = -1;
223                                         memset(&(data->hstimeout), 0, sizeof(struct timeval));
224                                         }
225                                 }
226                         }
227                 }
228         return(ret);
229         }
230
231 static int dgram_write(BIO *b, const char *in, int inl)
232         {
233         int ret;
234         bio_dgram_data *data = (bio_dgram_data *)b->ptr;
235         clear_socket_error();
236
237     if ( data->connected )
238         ret=writesocket(b->num,in,inl);
239     else
240 #if defined(NETWARE_CLIB) && defined(NETWARE_BSDSOCK)
241         ret=sendto(b->num, (char *)in, inl, 0, &data->peer, sizeof(data->peer));
242 #else
243         ret=sendto(b->num, in, inl, 0, &data->peer, sizeof(data->peer));
244 #endif
245
246         BIO_clear_retry_flags(b);
247         if (ret <= 0)
248                 {
249                 if (BIO_sock_should_retry(ret))
250                         {
251                         BIO_set_retry_write(b);  
252                         data->_errno = get_last_socket_error();
253
254 #if 0 /* higher layers are responsible for querying MTU, if necessary */
255                         if ( data->_errno == EMSGSIZE)
256                                 /* retrieve the new MTU */
257                                 BIO_ctrl(b, BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
258 #endif
259                         }
260                 }
261         return(ret);
262         }
263
264 static long dgram_ctrl(BIO *b, int cmd, long num, void *ptr)
265         {
266         long ret=1;
267         int *ip;
268         struct sockaddr *to = NULL;
269         bio_dgram_data *data = NULL;
270         long sockopt_val = 0;
271         unsigned int sockopt_len = 0;
272
273         data = (bio_dgram_data *)b->ptr;
274
275         switch (cmd)
276                 {
277         case BIO_CTRL_RESET:
278                 num=0;
279         case BIO_C_FILE_SEEK:
280                 ret=0;
281                 break;
282         case BIO_C_FILE_TELL:
283         case BIO_CTRL_INFO:
284                 ret=0;
285                 break;
286         case BIO_C_SET_FD:
287                 dgram_clear(b);
288                 b->num= *((int *)ptr);
289                 b->shutdown=(int)num;
290                 b->init=1;
291                 break;
292         case BIO_C_GET_FD:
293                 if (b->init)
294                         {
295                         ip=(int *)ptr;
296                         if (ip != NULL) *ip=b->num;
297                         ret=b->num;
298                         }
299                 else
300                         ret= -1;
301                 break;
302         case BIO_CTRL_GET_CLOSE:
303                 ret=b->shutdown;
304                 break;
305         case BIO_CTRL_SET_CLOSE:
306                 b->shutdown=(int)num;
307                 break;
308         case BIO_CTRL_PENDING:
309         case BIO_CTRL_WPENDING:
310                 ret=0;
311                 break;
312         case BIO_CTRL_DUP:
313         case BIO_CTRL_FLUSH:
314                 ret=1;
315                 break;
316         case BIO_CTRL_DGRAM_CONNECT:
317                 to = (struct sockaddr *)ptr;
318 #if 0
319                 if (connect(b->num, to, sizeof(struct sockaddr)) < 0)
320                         { perror("connect"); ret = 0; }
321                 else
322                         {
323 #endif
324                         memcpy(&(data->peer),to, sizeof(struct sockaddr));
325 #if 0
326                         }
327 #endif
328                 break;
329                 /* (Linux)kernel sets DF bit on outgoing IP packets */
330 #ifdef IP_MTU_DISCOVER
331         case BIO_CTRL_DGRAM_MTU_DISCOVER:
332                 sockopt_val = IP_PMTUDISC_DO;
333                 if ((ret = setsockopt(b->num, IPPROTO_IP, IP_MTU_DISCOVER,
334                         &sockopt_val, sizeof(sockopt_val))) < 0)
335                         perror("setsockopt");
336                 break;
337 #endif
338         case BIO_CTRL_DGRAM_QUERY_MTU:
339 #ifdef IP_MTU
340         sockopt_len = sizeof(sockopt_val);
341                 if ((ret = getsockopt(b->num, IPPROTO_IP, IP_MTU, (void *)&sockopt_val,
342                         &sockopt_len)) < 0 || sockopt_val < 0)
343                         { ret = 0; }
344                 else
345                         {
346                         data->mtu = sockopt_val - 20 - 8; /* Subtract IP and UDP header */
347                         ret = data->mtu;
348                         }
349 #else
350                 ret = 0;
351 #endif
352                 break;
353         case BIO_CTRL_DGRAM_GET_MTU:
354                 return data->mtu;
355                 break;
356         case BIO_CTRL_DGRAM_SET_MTU:
357                 data->mtu = num - 20 - 8; /* Subtract IP and UDP header */
358                 ret = data->mtu;
359                 break;
360         case BIO_CTRL_DGRAM_SET_CONNECTED:
361                 to = (struct sockaddr *)ptr;
362
363                 if ( to != NULL)
364                         {
365                         data->connected = 1;
366                         memcpy(&(data->peer),to, sizeof(struct sockaddr));
367                         }
368                 else
369                         {
370                         data->connected = 0;
371                         memset(&(data->peer), 0x00, sizeof(struct sockaddr));
372                         }
373                 break;
374     case BIO_CTRL_DGRAM_SET_PEER:
375         to = (struct sockaddr *) ptr;
376
377         memcpy(&(data->peer), to, sizeof(struct sockaddr));
378         break;
379         case BIO_CTRL_DGRAM_SET_TIMEOUT:
380                 if (num > 0)
381                         {
382                         get_current_time(&data->hstimeout);
383                         data->hstimeout.tv_sec += data->hstimeoutdiff.tv_sec;
384                         data->hstimeout.tv_usec += data->hstimeoutdiff.tv_usec;
385                         if (data->hstimeout.tv_usec >= 1000000)
386                                 {
387                                 data->hstimeout.tv_sec++;
388                                 data->hstimeout.tv_usec -= 1000000;
389                                 }
390                         }
391                 else
392                         {
393                         memset(&(data->hstimeout), 0, sizeof(struct timeval));
394                         }
395                 break;
396 #if defined(SO_RCVTIMEO)
397         case BIO_CTRL_DGRAM_SET_RECV_TIMEOUT:
398 #ifdef OPENSSL_SYS_WINDOWS
399                 {
400                 struct timeval *tv = (struct timeval *)ptr;
401                 int timeout = tv->tv_sec * 1000 + tv->tv_usec/1000;
402                 if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
403                         (void*)&timeout, sizeof(timeout)) < 0)
404                         { perror("setsockopt"); ret = -1; }
405                 }
406 #else
407                 if ( setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, ptr,
408                         sizeof(struct timeval)) < 0)
409                         { perror("setsockopt"); ret = -1; }
410 #endif
411                 memcpy(&(data->hstimeoutdiff), ptr, sizeof(struct timeval));
412                 break;
413         case BIO_CTRL_DGRAM_GET_RECV_TIMEOUT:
414 #ifdef OPENSSL_SYS_WINDOWS
415                 {
416                 int timeout, sz = sizeof(timeout);
417                 struct timeval *tv = (struct timeval *)ptr;
418                 if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
419                         (void*)&timeout, &sz) < 0)
420                         { perror("getsockopt"); ret = -1; }
421                 else
422                         {
423                         tv->tv_sec = timeout / 1000;
424                         tv->tv_usec = (timeout % 1000) * 1000;
425                         ret = sizeof(*tv);
426                         }
427                 }
428 #else
429                 if ( getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, 
430                         ptr, (void *)&ret) < 0)
431                         { perror("getsockopt"); ret = -1; }
432 #endif
433                 break;
434 #endif
435 #if defined(SO_SNDTIMEO)
436         case BIO_CTRL_DGRAM_SET_SEND_TIMEOUT:
437 #ifdef OPENSSL_SYS_WINDOWS
438                 {
439                 struct timeval *tv = (struct timeval *)ptr;
440                 int timeout = tv->tv_sec * 1000 + tv->tv_usec/1000;
441                 if (setsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
442                         (void*)&timeout, sizeof(timeout)) < 0)
443                         { perror("setsockopt"); ret = -1; }
444                 }
445 #else
446                 if ( setsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO, ptr,
447                         sizeof(struct timeval)) < 0)
448                         { perror("setsockopt"); ret = -1; }
449 #endif
450                 break;
451         case BIO_CTRL_DGRAM_GET_SEND_TIMEOUT:
452 #ifdef OPENSSL_SYS_WINDOWS
453                 {
454                 int timeout, sz = sizeof(timeout);
455                 struct timeval *tv = (struct timeval *)ptr;
456                 if (getsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
457                         (void*)&timeout, &sz) < 0)
458                         { perror("getsockopt"); ret = -1; }
459                 else
460                         {
461                         tv->tv_sec = timeout / 1000;
462                         tv->tv_usec = (timeout % 1000) * 1000;
463                         ret = sizeof(*tv);
464                         }
465                 }
466 #else
467                 if ( getsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO, 
468                         ptr, (void *)&ret) < 0)
469                         { perror("getsockopt"); ret = -1; }
470 #endif
471                 break;
472 #endif
473         case BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP:
474                 /* fall-through */
475         case BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP:
476 #ifdef OPENSSL_SYS_WINDOWS
477                 if ( data->_errno == WSAETIMEDOUT)
478 #else
479                 if ( data->_errno == EAGAIN)
480 #endif
481                         {
482                         ret = 1;
483                         data->_errno = 0;
484                         }
485                 else
486                         ret = 0;
487                 break;
488 #ifdef EMSGSIZE
489         case BIO_CTRL_DGRAM_MTU_EXCEEDED:
490                 if ( data->_errno == EMSGSIZE)
491                         {
492                         ret = 1;
493                         data->_errno = 0;
494                         }
495                 else
496                         ret = 0;
497                 break;
498 #endif
499         default:
500                 ret=0;
501                 break;
502                 }
503         return(ret);
504         }
505
506 static int dgram_puts(BIO *bp, const char *str)
507         {
508         int n,ret;
509
510         n=strlen(str);
511         ret=dgram_write(bp,str,n);
512         return(ret);
513         }
514
515 static int BIO_dgram_should_retry(int i)
516         {
517         int err;
518
519         if ((i == 0) || (i == -1))
520                 {
521                 err=get_last_socket_error();
522
523 #if defined(OPENSSL_SYS_WINDOWS) && 0 /* more microsoft stupidity? perhaps not? Ben 4/1/99 */
524                 if ((i == -1) && (err == 0))
525                         return(1);
526 #endif
527
528                 return(BIO_dgram_non_fatal_error(err));
529                 }
530         return(0);
531         }
532
533 int BIO_dgram_non_fatal_error(int err)
534         {
535         switch (err)
536                 {
537 #if defined(OPENSSL_SYS_WINDOWS)
538 # if defined(WSAEWOULDBLOCK)
539         case WSAEWOULDBLOCK:
540 # endif
541
542 # if 0 /* This appears to always be an error */
543 #  if defined(WSAENOTCONN)
544         case WSAENOTCONN:
545 #  endif
546 # endif
547 #endif
548
549 #ifdef EWOULDBLOCK
550 # ifdef WSAEWOULDBLOCK
551 #  if WSAEWOULDBLOCK != EWOULDBLOCK
552         case EWOULDBLOCK:
553 #  endif
554 # else
555         case EWOULDBLOCK:
556 # endif
557 #endif
558
559 #if defined(ENOTCONN)
560         case ENOTCONN:
561 #endif
562
563 #ifdef EINTR
564         case EINTR:
565 #endif
566
567 #ifdef EAGAIN
568 #if EWOULDBLOCK != EAGAIN
569         case EAGAIN:
570 # endif
571 #endif
572
573 #ifdef EPROTO
574         case EPROTO:
575 #endif
576
577 #ifdef EINPROGRESS
578         case EINPROGRESS:
579 #endif
580
581 #ifdef EALREADY
582         case EALREADY:
583 #endif
584
585 /* DF bit set, and packet larger than MTU */
586 #ifdef EMSGSIZE
587         case EMSGSIZE:
588 #endif
589
590                 return(1);
591                 /* break; */
592         default:
593                 break;
594                 }
595         return(0);
596         }
597 #endif
598
599 static void get_current_time(struct timeval *t)
600         {
601 #ifdef OPENSSL_SYS_WIN32
602         struct _timeb tb;
603         _ftime(&tb);
604         t->tv_sec = (long)tb.time;
605         t->tv_usec = (long)tb.millitm * 1000;
606 #elif defined(OPENSSL_SYS_VMS)
607         struct timeb tb;
608         ftime(&tb);
609         t->tv_sec = (long)tb.time;
610         t->tv_usec = (long)tb.millitm * 1000;
611 #else
612         gettimeofday(t, NULL);
613 #endif
614         }