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