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