1 /* crypto/bio/b_sock.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to. The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * "This product includes cryptographic software written by
34 * Eric Young (eay@cryptsoft.com)"
35 * The word 'cryptographic' can be left out if the rouines from the library
36 * being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 * the apps directory (application code) you must include an acknowledgement:
39 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed. i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
64 #include <openssl/bio.h>
65 #if defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_BSDSOCK)
69 #ifndef OPENSSL_NO_SOCK
71 #include <openssl/dso.h>
73 #define SOCKET_PROTOCOL IPPROTO_TCP
76 #define MAX_LISTEN SO_MAXCONN
77 #elif defined(SOMAXCONN)
78 #define MAX_LISTEN SOMAXCONN
83 #if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
84 static int wsa_init_done=0;
88 static unsigned long BIO_ghbn_hits=0L;
89 static unsigned long BIO_ghbn_miss=0L;
92 static struct ghbn_cache_st
97 } ghbn_cache[GHBN_NUM];
100 static int get_ip(const char *str,unsigned char *ip);
102 static void ghbn_free(struct hostent *a);
103 static struct hostent *ghbn_dup(struct hostent *a);
105 int BIO_get_host_ip(const char *str, unsigned char *ip)
115 BIOerr(BIO_F_BIO_GET_HOST_IP,BIO_R_INVALID_IP_ADDRESS);
119 /* At this point, we have something that is most probably correct
120 in some way, so let's init the socket. */
121 if (BIO_sock_init() != 1)
122 return 0; /* don't generate another error code here */
124 /* If the string actually contained an IP address, we need not do
126 if (i > 0) return(1);
128 /* do a gethostbyname */
129 CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
131 he=BIO_gethostbyname(str);
134 BIOerr(BIO_F_BIO_GET_HOST_IP,BIO_R_BAD_HOSTNAME_LOOKUP);
138 /* cast to short because of win16 winsock definition */
139 if ((short)he->h_addrtype != AF_INET)
141 BIOerr(BIO_F_BIO_GET_HOST_IP,BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET);
145 ip[i]=he->h_addr_list[0][i];
150 CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME);
153 ERR_add_error_data(2,"host=",str);
160 int BIO_get_port(const char *str, unsigned short *port_ptr)
167 BIOerr(BIO_F_BIO_GET_PORT,BIO_R_NO_PORT_DEFINED);
172 *port_ptr=(unsigned short)i;
175 CRYPTO_w_lock(CRYPTO_LOCK_GETSERVBYNAME);
176 /* Note: under VMS with SOCKETSHR, it seems like the first
177 * parameter is 'char *', instead of 'const char *'
185 *port_ptr=ntohs((unsigned short)s->s_port);
186 CRYPTO_w_unlock(CRYPTO_LOCK_GETSERVBYNAME);
189 if (strcmp(str,"http") == 0)
191 else if (strcmp(str,"telnet") == 0)
193 else if (strcmp(str,"socks") == 0)
195 else if (strcmp(str,"https") == 0)
197 else if (strcmp(str,"ssl") == 0)
199 else if (strcmp(str,"ftp") == 0)
201 else if (strcmp(str,"gopher") == 0)
204 else if (strcmp(str,"wais") == 0)
209 SYSerr(SYS_F_GETSERVBYNAME,get_last_socket_error());
210 ERR_add_error_data(3,"service='",str,"'");
218 int BIO_sock_error(int sock)
224 /* Note: under Windows the third parameter is of type (char *)
225 * whereas under other systems it is (void *) if you don't have
226 * a cast it will choke the compiler: if you do have a cast then
227 * you can either go for (char *) or (void *).
229 i=getsockopt(sock,SOL_SOCKET,SO_ERROR,(void *)&j,(void *)&size);
237 long BIO_ghbn_ctrl(int cmd, int iarg, char *parg)
244 case BIO_GHBN_CTRL_HITS:
245 return(BIO_ghbn_hits);
247 case BIO_GHBN_CTRL_MISSES:
248 return(BIO_ghbn_miss);
250 case BIO_GHBN_CTRL_CACHE_SIZE:
253 case BIO_GHBN_CTRL_GET_ENTRY:
254 if ((iarg >= 0) && (iarg <GHBN_NUM) &&
255 (ghbn_cache[iarg].order > 0))
258 if (p == NULL) return(0);
259 *p=ghbn_cache[iarg].name;
260 ghbn_cache[iarg].name[128]='\0';
265 case BIO_GHBN_CTRL_FLUSH:
266 for (i=0; i<GHBN_NUM; i++)
267 ghbn_cache[i].order=0;
277 static struct hostent *ghbn_dup(struct hostent *a)
283 ret=(struct hostent *)OPENSSL_malloc(sizeof(struct hostent));
284 if (ret == NULL) return(NULL);
285 memset(ret,0,sizeof(struct hostent));
287 for (i=0; a->h_aliases[i] != NULL; i++)
290 ret->h_aliases = (char **)OPENSSL_malloc(i*sizeof(char *));
291 if (ret->h_aliases == NULL)
293 memset(ret->h_aliases, 0, i*sizeof(char *));
295 for (i=0; a->h_addr_list[i] != NULL; i++)
298 ret->h_addr_list=(char **)OPENSSL_malloc(i*sizeof(char *));
299 if (ret->h_addr_list == NULL)
301 memset(ret->h_addr_list, 0, i*sizeof(char *));
303 j=strlen(a->h_name)+1;
304 if ((ret->h_name=OPENSSL_malloc(j)) == NULL) goto err;
305 memcpy((char *)ret->h_name,a->h_name,j);
306 for (i=0; a->h_aliases[i] != NULL; i++)
308 j=strlen(a->h_aliases[i])+1;
309 if ((ret->h_aliases[i]=OPENSSL_malloc(j)) == NULL) goto err;
310 memcpy(ret->h_aliases[i],a->h_aliases[i],j);
312 ret->h_length=a->h_length;
313 ret->h_addrtype=a->h_addrtype;
314 for (i=0; a->h_addr_list[i] != NULL; i++)
316 if ((ret->h_addr_list[i]=OPENSSL_malloc(a->h_length)) == NULL)
318 memcpy(ret->h_addr_list[i],a->h_addr_list[i],a->h_length);
331 static void ghbn_free(struct hostent *a)
338 if (a->h_aliases != NULL)
340 for (i=0; a->h_aliases[i] != NULL; i++)
341 OPENSSL_free(a->h_aliases[i]);
342 OPENSSL_free(a->h_aliases);
344 if (a->h_addr_list != NULL)
346 for (i=0; a->h_addr_list[i] != NULL; i++)
347 OPENSSL_free(a->h_addr_list[i]);
348 OPENSSL_free(a->h_addr_list);
350 if (a->h_name != NULL) OPENSSL_free(a->h_name);
356 struct hostent *BIO_gethostbyname(const char *name)
359 /* Caching gethostbyname() results forever is wrong,
360 * so we have to let the true gethostbyname() worry about this */
361 return gethostbyname(name);
365 unsigned long low= (unsigned long)-1;
369 /* It doesn't make sense to use locking here: The function interface
370 * is not thread-safe, because threads can never be sure when
371 * some other thread destroys the data they were given a pointer to.
373 CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
378 for (i=0; i<GHBN_NUM; i++)
380 if (low > ghbn_cache[i].order)
382 low=ghbn_cache[i].order;
385 if (ghbn_cache[i].order > 0)
387 if (strncmp(name,ghbn_cache[i].name,128) == 0)
395 if (i == GHBN_NUM) /* no hit*/
398 /* Note: under VMS with SOCKETSHR, it seems like the first
399 * parameter is 'char *', instead of 'const char *'
402 # ifndef CONST_STRICT
409 if (j > 128) /* too big to cache */
412 /* If we were trying to make this function thread-safe (which
413 * is bound to fail), we'd have to give up in this case
414 * (or allocate more memory). */
420 /* else add to cache */
421 if (ghbn_cache[lowi].ent != NULL)
422 ghbn_free(ghbn_cache[lowi].ent); /* XXX not thread-safe */
423 ghbn_cache[lowi].name[0] = '\0';
425 if((ret=ghbn_cache[lowi].ent=ghbn_dup(ret)) == NULL)
427 BIOerr(BIO_F_BIO_GETHOSTBYNAME,ERR_R_MALLOC_FAILURE);
430 strncpy(ghbn_cache[lowi].name,name,128);
431 ghbn_cache[lowi].order=BIO_ghbn_miss+BIO_ghbn_hits;
436 ret= ghbn_cache[i].ent;
437 ghbn_cache[i].order=BIO_ghbn_miss+BIO_ghbn_hits;
441 CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME);
448 int BIO_sock_init(void)
450 #ifdef OPENSSL_SYS_WINDOWS
451 static struct WSAData wsa_state;
458 signal(SIGINT,(void (*)(int))BIO_sock_cleanup);
461 memset(&wsa_state,0,sizeof(wsa_state));
462 /* Not making wsa_state available to the rest of the
463 * code is formally wrong. But the structures we use
464 * are [beleived to be] invariable among Winsock DLLs,
465 * while API availability is [expected to be] probed
466 * at run-time with DSO_global_lookup. */
467 if (WSAStartup(0x0202,&wsa_state)!=0)
469 err=WSAGetLastError();
470 SYSerr(SYS_F_WSASTARTUP,err);
471 BIOerr(BIO_F_BIO_SOCK_INIT,BIO_R_WSASTARTUP);
475 #endif /* OPENSSL_SYS_WINDOWS */
477 extern int _watt_do_exit;
478 _watt_do_exit = 0; /* don't make sock_init() call exit() */
483 #if defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
492 signal(SIGINT,(void (*)(int))BIO_sock_cleanup);
496 wVerReq = MAKEWORD( 2, 0 );
497 err = WSAStartup(wVerReq,&wsaData);
500 SYSerr(SYS_F_WSASTARTUP,err);
501 BIOerr(BIO_F_BIO_SOCK_INIT,BIO_R_WSASTARTUP);
510 void BIO_sock_cleanup(void)
512 #ifdef OPENSSL_SYS_WINDOWS
516 #ifndef OPENSSL_SYS_WINCE
517 WSACancelBlockingCall();
521 #elif defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
530 #if !defined(OPENSSL_SYS_VMS) || __VMS_VER >= 70000000
532 int BIO_socket_ioctl(int fd, long type, void *arg)
537 i=ioctlsocket(fd,type,(char *)arg);
539 i=ioctlsocket(fd,type,arg);
540 #endif /* __DJGPP__ */
542 SYSerr(SYS_F_IOCTLSOCKET,get_last_socket_error());
545 #endif /* __VMS_VER */
547 /* The reason I have implemented this instead of using sscanf is because
548 * Visual C 1.52c gives an unresolved external when linking a DLL :-( */
549 static int get_ip(const char *str, unsigned char ip[4])
554 tmp[0]=tmp[1]=tmp[2]=tmp[3]=0;
559 if ((c >= '0') && (c <= '9'))
562 tmp[num]=tmp[num]*10+c-'0';
563 if (tmp[num] > 255) return(0);
568 if (num == 3) return(0);
572 else if (c == '\0' && (num == 3) && ok)
584 int BIO_get_accept_socket(char *host, int bind_mode)
587 struct sockaddr server,client;
588 struct sockaddr_in *sa_in;
589 int s=INVALID_SOCKET,cs;
597 if (BIO_sock_init() != 1) return(INVALID_SOCKET);
599 if ((str=BUF_strdup(host)) == NULL) return(INVALID_SOCKET);
615 if (p) *p++='\0'; /* points at last ':', '::port' is special [see below] */
620 static union { void *p;
621 int (*f)(const char *,const char *,
622 const struct addrinfo *,
624 } p_getaddrinfo = {NULL};
625 static union { void *p;
626 void (*f)(struct addrinfo *);
627 } p_freeaddrinfo = {NULL};
628 struct addrinfo *res,hint;
630 if (p_getaddrinfo.p==NULL)
632 if ((p_getaddrinfo.p=DSO_global_lookup("getaddrinfo"))==NULL ||
633 (p_freeaddrinfo.p=DSO_global_lookup("freeaddrinfo"))==NULL)
634 p_getaddrinfo.p=(void*)-1;
636 if (p_getaddrinfo.p==(void *)-1) break;
638 /* '::port' enforces IPv6 wildcard listener. Some OSes,
639 * e.g. Solaris, default to IPv6 without any hint. Also
640 * note that commonly IPv6 wildchard socket can service
641 * IPv4 connections just as well... */
642 memset(&hint,0,sizeof(hint));
647 if (h[1]=='\0') h=NULL;
649 hint.ai_family = AF_INET6;
654 else if (h[0]=='*' && h[1]=='\0')
658 if ((*p_getaddrinfo.f)(h,p,&hint,&res)) break;
659 server = *res->ai_addr;
660 (*p_freeaddrinfo.f)(res);
665 if (!BIO_get_port(p,&port)) goto err;
667 memset((char *)&server,0,sizeof(server));
668 sa_in = (struct sockaddr_in *)&server;
669 sa_in->sin_family=AF_INET;
670 sa_in->sin_port=htons(port);
672 if (h == NULL || strcmp(h,"*") == 0)
673 sa_in->sin_addr.s_addr=INADDR_ANY;
676 if (!BIO_get_host_ip(h,&(ip[0]))) goto err;
678 ((unsigned long)ip[0]<<24L)|
679 ((unsigned long)ip[1]<<16L)|
680 ((unsigned long)ip[2]<< 8L)|
681 ((unsigned long)ip[3]);
682 sa_in->sin_addr.s_addr=htonl(l);
686 s=socket(server.sa_family,SOCK_STREAM,SOCKET_PROTOCOL);
687 if (s == INVALID_SOCKET)
689 SYSerr(SYS_F_SOCKET,get_last_socket_error());
690 ERR_add_error_data(3,"port='",host,"'");
691 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,BIO_R_UNABLE_TO_CREATE_SOCKET);
696 if (bind_mode == BIO_BIND_REUSEADDR)
700 ret=setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&i,sizeof(i));
701 bind_mode=BIO_BIND_NORMAL;
704 if (bind(s,&server,sizeof(server)) == -1)
707 err_num=get_last_socket_error();
708 if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
709 (err_num == EADDRINUSE))
712 if (h == NULL || strcmp(h,"*") == 0)
715 if (client.sa_family == AF_INET6)
717 struct sockaddr_in6 *sin6 =
718 (struct sockaddr_in6 *)&client;
719 memset(&sin6->sin6_addr,0,sizeof(sin6->sin6_addr));
720 sin6->sin6_addr.s6_addr[15]=1;
724 if (client.sa_family == AF_INET)
726 struct sockaddr_in *sin6 =
727 (struct sockaddr_in *)&client;
728 sin6->sin_addr.s_addr=htonl(0x7F000001);
732 cs=socket(client.sa_family,SOCK_STREAM,SOCKET_PROTOCOL);
733 if (cs != INVALID_SOCKET)
736 ii=connect(cs,(struct sockaddr *)&client,
739 if (ii == INVALID_SOCKET)
741 bind_mode=BIO_BIND_REUSEADDR;
750 SYSerr(SYS_F_BIND,err_num);
751 ERR_add_error_data(3,"port='",host,"'");
752 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,BIO_R_UNABLE_TO_BIND_SOCKET);
755 if (listen(s,MAX_LISTEN) == -1)
757 SYSerr(SYS_F_BIND,get_last_socket_error());
758 ERR_add_error_data(3,"port='",host,"'");
759 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,BIO_R_UNABLE_TO_LISTEN_SOCKET);
764 if (str != NULL) OPENSSL_free(str);
765 if ((ret == 0) && (s != INVALID_SOCKET))
773 int BIO_accept(int sock, char **addr)
775 int ret=INVALID_SOCKET;
776 struct sockaddr from;
777 struct sockaddr_in *sa_in;
783 memset(&from,0,sizeof(from));
785 /* Note: under VMS with SOCKETSHR the fourth parameter is currently
786 * of type (int *) whereas under other systems it is (void *) if
787 * you don't have a cast it will choke the compiler: if you do
788 * have a cast then you can either go for (int *) or (void *).
790 ret=accept(sock,&from,(void *)&len);
791 if (ret == INVALID_SOCKET)
793 if(BIO_sock_should_retry(ret)) return -2;
794 SYSerr(SYS_F_ACCEPT,get_last_socket_error());
795 BIOerr(BIO_F_BIO_ACCEPT,BIO_R_ACCEPT_ERROR);
799 if (addr == NULL) goto end;
802 # ifdef OPENSSL_SYS_VMS
803 # define SOCKLEN_T size_t
805 # define SOCKLEN_T socklen_t
808 char h[NI_MAXHOST],s[NI_MAXSERV];
810 static union { void *p;
811 int (*f)(const struct sockaddr *,SOCKLEN_T,
812 char *,size_t,char *,size_t,int);
813 } p_getnameinfo = {NULL};
815 if (p_getnameinfo.p==NULL)
817 if ((p_getnameinfo.p=DSO_global_lookup("getnameinfo"))==NULL)
818 p_getnameinfo.p=(void*)-1;
820 if (p_getnameinfo.p==(void *)-1) break;
822 if ((*p_getnameinfo.f)(&from,sizeof(from),h,sizeof(h),s,sizeof(s),
823 NI_NUMERICHOST|NI_NUMERICSERV)) break;
824 nl = strlen(h)+strlen(s)+2; if (len<24) len=24;
826 if (p) { *p = '\0'; p = OPENSSL_realloc(p,nl); }
827 else { p = OPENSSL_malloc(nl); }
830 BIOerr(BIO_F_BIO_ACCEPT,ERR_R_MALLOC_FAILURE);
834 BIO_snprintf(*addr,nl,"%s:%s",h,s);
838 if (from.sa_family != AF_INET) goto end;
839 sa_in = (struct sockaddr_in *)&from;
840 l=ntohl(sa_in->sin_addr.s_addr);
841 port=ntohs(sa_in->sin_port);
844 if ((p=OPENSSL_malloc(24)) == NULL)
846 BIOerr(BIO_F_BIO_ACCEPT,ERR_R_MALLOC_FAILURE);
851 BIO_snprintf(*addr,24,"%d.%d.%d.%d:%d",
852 (unsigned char)(l>>24L)&0xff,
853 (unsigned char)(l>>16L)&0xff,
854 (unsigned char)(l>> 8L)&0xff,
855 (unsigned char)(l )&0xff,
861 int BIO_set_tcp_ndelay(int s, int on)
864 #if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP))
875 ret=setsockopt(s,opt,TCP_NODELAY,(char *)&on,sizeof(on));
881 int BIO_socket_nbio(int s, int mode)
888 ret=BIO_socket_ioctl(s,FIONBIO,&l);