s_socket.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. /* apps/s_socket.c - socket-related functions used by s_client and s_server */
  2. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  3. * All rights reserved.
  4. *
  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.
  8. *
  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).
  15. *
  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.
  22. *
  23. * Redistribution and use in source and binary forms, with or without
  24. * modification, are permitted provided that the following conditions
  25. * are met:
  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)"
  40. *
  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
  51. * SUCH DAMAGE.
  52. *
  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.]
  57. */
  58. #include <stdio.h>
  59. #include <stdlib.h>
  60. #include <string.h>
  61. #include <errno.h>
  62. #include <signal.h>
  63. /* With IPv6, it looks like Digital has mixed up the proper order of
  64. recursive header file inclusion, resulting in the compiler complaining
  65. that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which
  66. is needed to have fileno() declared correctly... So let's define u_int */
  67. #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
  68. #define __U_INT
  69. typedef unsigned int u_int;
  70. #endif
  71. #define USE_SOCKETS
  72. #define NON_MAIN
  73. #include "apps.h"
  74. #undef USE_SOCKETS
  75. #undef NON_MAIN
  76. #include "s_apps.h"
  77. #include <openssl/ssl.h>
  78. #ifdef FLAT_INC
  79. #include "e_os.h"
  80. #else
  81. #include "../e_os.h"
  82. #endif
  83. #ifndef OPENSSL_NO_SOCK
  84. #if defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_BSDSOCK)
  85. #include "netdb.h"
  86. #endif
  87. static struct hostent *GetHostByName(char *name);
  88. #if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
  89. static void ssl_sock_cleanup(void);
  90. #endif
  91. static int ssl_sock_init(void);
  92. static int init_client_ip(int *sock, const unsigned char ip[4], int port,
  93. int type);
  94. static int init_server(int *sock, int port, int type);
  95. static int init_server_long(int *sock, int port,char *ip, int type);
  96. static int do_accept(int acc_sock, int *sock, char **host);
  97. static int host_ip(char *str, unsigned char ip[4]);
  98. #ifdef OPENSSL_SYS_WIN16
  99. #define SOCKET_PROTOCOL 0 /* more microsoft stupidity */
  100. #else
  101. #define SOCKET_PROTOCOL IPPROTO_TCP
  102. #endif
  103. #if defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
  104. static int wsa_init_done=0;
  105. #endif
  106. #ifdef OPENSSL_SYS_WINDOWS
  107. static struct WSAData wsa_state;
  108. static int wsa_init_done=0;
  109. #ifdef OPENSSL_SYS_WIN16
  110. static HWND topWnd=0;
  111. static FARPROC lpTopWndProc=NULL;
  112. static FARPROC lpTopHookProc=NULL;
  113. extern HINSTANCE _hInstance; /* nice global CRT provides */
  114. static LONG FAR PASCAL topHookProc(HWND hwnd, UINT message, WPARAM wParam,
  115. LPARAM lParam)
  116. {
  117. if (hwnd == topWnd)
  118. {
  119. switch(message)
  120. {
  121. case WM_DESTROY:
  122. case WM_CLOSE:
  123. SetWindowLong(topWnd,GWL_WNDPROC,(LONG)lpTopWndProc);
  124. ssl_sock_cleanup();
  125. break;
  126. }
  127. }
  128. return CallWindowProc(lpTopWndProc,hwnd,message,wParam,lParam);
  129. }
  130. static BOOL CALLBACK enumproc(HWND hwnd,LPARAM lParam)
  131. {
  132. topWnd=hwnd;
  133. return(FALSE);
  134. }
  135. #endif /* OPENSSL_SYS_WIN32 */
  136. #endif /* OPENSSL_SYS_WINDOWS */
  137. #ifdef OPENSSL_SYS_WINDOWS
  138. static void ssl_sock_cleanup(void)
  139. {
  140. if (wsa_init_done)
  141. {
  142. wsa_init_done=0;
  143. #ifndef OPENSSL_SYS_WINCE
  144. WSACancelBlockingCall();
  145. #endif
  146. WSACleanup();
  147. }
  148. }
  149. #elif defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
  150. static void sock_cleanup(void)
  151. {
  152. if (wsa_init_done)
  153. {
  154. wsa_init_done=0;
  155. WSACleanup();
  156. }
  157. }
  158. #endif
  159. static int ssl_sock_init(void)
  160. {
  161. #ifdef WATT32
  162. extern int _watt_do_exit;
  163. _watt_do_exit = 0;
  164. if (sock_init())
  165. return (0);
  166. #elif defined(OPENSSL_SYS_WINDOWS)
  167. if (!wsa_init_done)
  168. {
  169. int err;
  170. #ifdef SIGINT
  171. signal(SIGINT,(void (*)(int))ssl_sock_cleanup);
  172. #endif
  173. wsa_init_done=1;
  174. memset(&wsa_state,0,sizeof(wsa_state));
  175. if (WSAStartup(0x0101,&wsa_state)!=0)
  176. {
  177. err=WSAGetLastError();
  178. BIO_printf(bio_err,"unable to start WINSOCK, error code=%d\n",err);
  179. return(0);
  180. }
  181. #ifdef OPENSSL_SYS_WIN16
  182. EnumTaskWindows(GetCurrentTask(),enumproc,0L);
  183. lpTopWndProc=(FARPROC)GetWindowLong(topWnd,GWL_WNDPROC);
  184. lpTopHookProc=MakeProcInstance((FARPROC)topHookProc,_hInstance);
  185. SetWindowLong(topWnd,GWL_WNDPROC,(LONG)lpTopHookProc);
  186. #endif /* OPENSSL_SYS_WIN16 */
  187. }
  188. #elif defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
  189. WORD wVerReq;
  190. WSADATA wsaData;
  191. int err;
  192. if (!wsa_init_done)
  193. {
  194. # ifdef SIGINT
  195. signal(SIGINT,(void (*)(int))sock_cleanup);
  196. # endif
  197. wsa_init_done=1;
  198. wVerReq = MAKEWORD( 2, 0 );
  199. err = WSAStartup(wVerReq,&wsaData);
  200. if (err != 0)
  201. {
  202. BIO_printf(bio_err,"unable to start WINSOCK2, error code=%d\n",err);
  203. return(0);
  204. }
  205. }
  206. #endif /* OPENSSL_SYS_WINDOWS */
  207. return(1);
  208. }
  209. int init_client(int *sock, char *host, int port, int type)
  210. {
  211. unsigned char ip[4];
  212. ip[0] = ip[1] = ip[2] = ip[3] = 0;
  213. if (!host_ip(host,&(ip[0])))
  214. {
  215. return(0);
  216. }
  217. return(init_client_ip(sock,ip,port,type));
  218. }
  219. static int init_client_ip(int *sock, const unsigned char ip[4], int port,
  220. int type)
  221. {
  222. unsigned long addr;
  223. struct sockaddr_in them;
  224. int s,i;
  225. if (!ssl_sock_init()) return(0);
  226. memset((char *)&them,0,sizeof(them));
  227. them.sin_family=AF_INET;
  228. them.sin_port=htons((unsigned short)port);
  229. addr=(unsigned long)
  230. ((unsigned long)ip[0]<<24L)|
  231. ((unsigned long)ip[1]<<16L)|
  232. ((unsigned long)ip[2]<< 8L)|
  233. ((unsigned long)ip[3]);
  234. them.sin_addr.s_addr=htonl(addr);
  235. if (type == SOCK_STREAM)
  236. s=socket(AF_INET,SOCK_STREAM,SOCKET_PROTOCOL);
  237. else /* ( type == SOCK_DGRAM) */
  238. s=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
  239. if (s == INVALID_SOCKET) { perror("socket"); return(0); }
  240. #if defined(SO_KEEPALIVE) && !defined(OPENSSL_SYS_MPE)
  241. if (type == SOCK_STREAM)
  242. {
  243. i=0;
  244. i=setsockopt(s,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i));
  245. if (i < 0) { perror("keepalive"); return(0); }
  246. }
  247. #endif
  248. if (connect(s,(struct sockaddr *)&them,sizeof(them)) == -1)
  249. { closesocket(s); perror("connect"); return(0); }
  250. *sock=s;
  251. return(1);
  252. }
  253. int do_server(int port, int type, int *ret, int (*cb)(char *hostname, int s, unsigned char *context), unsigned char *context)
  254. {
  255. int sock;
  256. char *name = NULL;
  257. int accept_socket = 0;
  258. int i;
  259. if (!init_server(&accept_socket,port,type)) return(0);
  260. if (ret != NULL)
  261. {
  262. *ret=accept_socket;
  263. /* return(1);*/
  264. }
  265. for (;;)
  266. {
  267. if (type==SOCK_STREAM)
  268. {
  269. if (do_accept(accept_socket,&sock,&name) == 0)
  270. {
  271. SHUTDOWN(accept_socket);
  272. return(0);
  273. }
  274. }
  275. else
  276. sock = accept_socket;
  277. i=(*cb)(name,sock, context);
  278. if (name != NULL) OPENSSL_free(name);
  279. if (type==SOCK_STREAM)
  280. SHUTDOWN2(sock);
  281. if (i < 0)
  282. {
  283. SHUTDOWN2(accept_socket);
  284. return(i);
  285. }
  286. }
  287. }
  288. static int init_server_long(int *sock, int port, char *ip, int type)
  289. {
  290. int ret=0;
  291. struct sockaddr_in server;
  292. int s= -1;
  293. if (!ssl_sock_init()) return(0);
  294. memset((char *)&server,0,sizeof(server));
  295. server.sin_family=AF_INET;
  296. server.sin_port=htons((unsigned short)port);
  297. if (ip == NULL)
  298. server.sin_addr.s_addr=INADDR_ANY;
  299. else
  300. /* Added for T3E, address-of fails on bit field (beckman@acl.lanl.gov) */
  301. #ifndef BIT_FIELD_LIMITS
  302. memcpy(&server.sin_addr.s_addr,ip,4);
  303. #else
  304. memcpy(&server.sin_addr,ip,4);
  305. #endif
  306. if (type == SOCK_STREAM)
  307. s=socket(AF_INET,SOCK_STREAM,SOCKET_PROTOCOL);
  308. else /* type == SOCK_DGRAM */
  309. s=socket(AF_INET, SOCK_DGRAM,IPPROTO_UDP);
  310. if (s == INVALID_SOCKET) goto err;
  311. #if defined SOL_SOCKET && defined SO_REUSEADDR
  312. {
  313. int j = 1;
  314. setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
  315. (void *) &j, sizeof j);
  316. }
  317. #endif
  318. if (bind(s,(struct sockaddr *)&server,sizeof(server)) == -1)
  319. {
  320. #ifndef OPENSSL_SYS_WINDOWS
  321. perror("bind");
  322. #endif
  323. goto err;
  324. }
  325. /* Make it 128 for linux */
  326. if (type==SOCK_STREAM && listen(s,128) == -1) goto err;
  327. *sock=s;
  328. ret=1;
  329. err:
  330. if ((ret == 0) && (s != -1))
  331. {
  332. SHUTDOWN(s);
  333. }
  334. return(ret);
  335. }
  336. static int init_server(int *sock, int port, int type)
  337. {
  338. return(init_server_long(sock, port, NULL, type));
  339. }
  340. static int do_accept(int acc_sock, int *sock, char **host)
  341. {
  342. int ret;
  343. struct hostent *h1,*h2;
  344. static struct sockaddr_in from;
  345. int len;
  346. /* struct linger ling; */
  347. if (!ssl_sock_init()) return(0);
  348. #ifndef OPENSSL_SYS_WINDOWS
  349. redoit:
  350. #endif
  351. memset((char *)&from,0,sizeof(from));
  352. len=sizeof(from);
  353. /* Note: under VMS with SOCKETSHR the fourth parameter is currently
  354. * of type (int *) whereas under other systems it is (void *) if
  355. * you don't have a cast it will choke the compiler: if you do
  356. * have a cast then you can either go for (int *) or (void *).
  357. */
  358. ret=accept(acc_sock,(struct sockaddr *)&from,(void *)&len);
  359. if (ret == INVALID_SOCKET)
  360. {
  361. #if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
  362. int i;
  363. i=WSAGetLastError();
  364. BIO_printf(bio_err,"accept error %d\n",i);
  365. #else
  366. if (errno == EINTR)
  367. {
  368. /*check_timeout(); */
  369. goto redoit;
  370. }
  371. fprintf(stderr,"errno=%d ",errno);
  372. perror("accept");
  373. #endif
  374. return(0);
  375. }
  376. /*
  377. ling.l_onoff=1;
  378. ling.l_linger=0;
  379. i=setsockopt(ret,SOL_SOCKET,SO_LINGER,(char *)&ling,sizeof(ling));
  380. if (i < 0) { perror("linger"); return(0); }
  381. i=0;
  382. i=setsockopt(ret,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i));
  383. if (i < 0) { perror("keepalive"); return(0); }
  384. */
  385. if (host == NULL) goto end;
  386. #ifndef BIT_FIELD_LIMITS
  387. /* I should use WSAAsyncGetHostByName() under windows */
  388. h1=gethostbyaddr((char *)&from.sin_addr.s_addr,
  389. sizeof(from.sin_addr.s_addr),AF_INET);
  390. #else
  391. h1=gethostbyaddr((char *)&from.sin_addr,
  392. sizeof(struct in_addr),AF_INET);
  393. #endif
  394. if (h1 == NULL)
  395. {
  396. BIO_printf(bio_err,"bad gethostbyaddr\n");
  397. *host=NULL;
  398. /* return(0); */
  399. }
  400. else
  401. {
  402. if ((*host=(char *)OPENSSL_malloc(strlen(h1->h_name)+1)) == NULL)
  403. {
  404. perror("OPENSSL_malloc");
  405. return(0);
  406. }
  407. BUF_strlcpy(*host,h1->h_name,strlen(h1->h_name)+1);
  408. h2=GetHostByName(*host);
  409. if (h2 == NULL)
  410. {
  411. BIO_printf(bio_err,"gethostbyname failure\n");
  412. return(0);
  413. }
  414. if (h2->h_addrtype != AF_INET)
  415. {
  416. BIO_printf(bio_err,"gethostbyname addr is not AF_INET\n");
  417. return(0);
  418. }
  419. }
  420. end:
  421. *sock=ret;
  422. return(1);
  423. }
  424. int extract_host_port(char *str, char **host_ptr, unsigned char *ip,
  425. short *port_ptr)
  426. {
  427. char *h,*p;
  428. h=str;
  429. p=strchr(str,':');
  430. if (p == NULL)
  431. {
  432. BIO_printf(bio_err,"no port defined\n");
  433. return(0);
  434. }
  435. *(p++)='\0';
  436. if ((ip != NULL) && !host_ip(str,ip))
  437. goto err;
  438. if (host_ptr != NULL) *host_ptr=h;
  439. if (!extract_port(p,port_ptr))
  440. goto err;
  441. return(1);
  442. err:
  443. return(0);
  444. }
  445. static int host_ip(char *str, unsigned char ip[4])
  446. {
  447. unsigned int in[4];
  448. int i;
  449. if (sscanf(str,"%u.%u.%u.%u",&(in[0]),&(in[1]),&(in[2]),&(in[3])) == 4)
  450. {
  451. for (i=0; i<4; i++)
  452. if (in[i] > 255)
  453. {
  454. BIO_printf(bio_err,"invalid IP address\n");
  455. goto err;
  456. }
  457. ip[0]=in[0];
  458. ip[1]=in[1];
  459. ip[2]=in[2];
  460. ip[3]=in[3];
  461. }
  462. else
  463. { /* do a gethostbyname */
  464. struct hostent *he;
  465. if (!ssl_sock_init()) return(0);
  466. he=GetHostByName(str);
  467. if (he == NULL)
  468. {
  469. BIO_printf(bio_err,"gethostbyname failure\n");
  470. goto err;
  471. }
  472. /* cast to short because of win16 winsock definition */
  473. if ((short)he->h_addrtype != AF_INET)
  474. {
  475. BIO_printf(bio_err,"gethostbyname addr is not AF_INET\n");
  476. return(0);
  477. }
  478. ip[0]=he->h_addr_list[0][0];
  479. ip[1]=he->h_addr_list[0][1];
  480. ip[2]=he->h_addr_list[0][2];
  481. ip[3]=he->h_addr_list[0][3];
  482. }
  483. return(1);
  484. err:
  485. return(0);
  486. }
  487. int extract_port(char *str, short *port_ptr)
  488. {
  489. int i;
  490. struct servent *s;
  491. i=atoi(str);
  492. if (i != 0)
  493. *port_ptr=(unsigned short)i;
  494. else
  495. {
  496. s=getservbyname(str,"tcp");
  497. if (s == NULL)
  498. {
  499. BIO_printf(bio_err,"getservbyname failure for %s\n",str);
  500. return(0);
  501. }
  502. *port_ptr=ntohs((unsigned short)s->s_port);
  503. }
  504. return(1);
  505. }
  506. #define GHBN_NUM 4
  507. static struct ghbn_cache_st
  508. {
  509. char name[128];
  510. struct hostent ent;
  511. unsigned long order;
  512. } ghbn_cache[GHBN_NUM];
  513. static unsigned long ghbn_hits=0L;
  514. static unsigned long ghbn_miss=0L;
  515. static struct hostent *GetHostByName(char *name)
  516. {
  517. struct hostent *ret;
  518. int i,lowi=0;
  519. unsigned long low= (unsigned long)-1;
  520. for (i=0; i<GHBN_NUM; i++)
  521. {
  522. if (low > ghbn_cache[i].order)
  523. {
  524. low=ghbn_cache[i].order;
  525. lowi=i;
  526. }
  527. if (ghbn_cache[i].order > 0)
  528. {
  529. if (strncmp(name,ghbn_cache[i].name,128) == 0)
  530. break;
  531. }
  532. }
  533. if (i == GHBN_NUM) /* no hit*/
  534. {
  535. ghbn_miss++;
  536. ret=gethostbyname(name);
  537. if (ret == NULL) return(NULL);
  538. /* else add to cache */
  539. if(strlen(name) < sizeof ghbn_cache[0].name)
  540. {
  541. strcpy(ghbn_cache[lowi].name,name);
  542. memcpy((char *)&(ghbn_cache[lowi].ent),ret,sizeof(struct hostent));
  543. ghbn_cache[lowi].order=ghbn_miss+ghbn_hits;
  544. }
  545. return(ret);
  546. }
  547. else
  548. {
  549. ghbn_hits++;
  550. ret= &(ghbn_cache[i].ent);
  551. ghbn_cache[i].order=ghbn_miss+ghbn_hits;
  552. return(ret);
  553. }
  554. }
  555. #endif