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