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