s_socket.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. /*
  2. * apps/s_socket.c - socket-related functions used by s_client and s_server
  3. */
  4. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  5. * All rights reserved.
  6. *
  7. * This package is an SSL implementation written
  8. * by Eric Young (eay@cryptsoft.com).
  9. * The implementation was written so as to conform with Netscapes SSL.
  10. *
  11. * This library is free for commercial and non-commercial use as long as
  12. * the following conditions are aheared to. The following conditions
  13. * apply to all code found in this distribution, be it the RC4, RSA,
  14. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  15. * included with this distribution is covered by the same copyright terms
  16. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  17. *
  18. * Copyright remains Eric Young's, and as such any Copyright notices in
  19. * the code are not to be removed.
  20. * If this package is used in a product, Eric Young should be given attribution
  21. * as the author of the parts of the library used.
  22. * This can be in the form of a textual message at program startup or
  23. * in documentation (online or textual) provided with the package.
  24. *
  25. * Redistribution and use in source and binary forms, with or without
  26. * modification, are permitted provided that the following conditions
  27. * are met:
  28. * 1. Redistributions of source code must retain the copyright
  29. * notice, this list of conditions and the following disclaimer.
  30. * 2. Redistributions in binary form must reproduce the above copyright
  31. * notice, this list of conditions and the following disclaimer in the
  32. * documentation and/or other materials provided with the distribution.
  33. * 3. All advertising materials mentioning features or use of this software
  34. * must display the following acknowledgement:
  35. * "This product includes cryptographic software written by
  36. * Eric Young (eay@cryptsoft.com)"
  37. * The word 'cryptographic' can be left out if the rouines from the library
  38. * being used are not cryptographic related :-).
  39. * 4. If you include any Windows specific code (or a derivative thereof) from
  40. * the apps directory (application code) you must include an acknowledgement:
  41. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  42. *
  43. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  44. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  45. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  46. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  47. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  48. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  49. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  50. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  51. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  52. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  53. * SUCH DAMAGE.
  54. *
  55. * The licence and distribution terms for any publically available version or
  56. * derivative of this code cannot be changed. i.e. this code cannot simply be
  57. * copied and put under another distribution licence
  58. * [including the GNU Public Licence.]
  59. */
  60. #include <stdio.h>
  61. #include <stdlib.h>
  62. #include <string.h>
  63. #include <errno.h>
  64. #include <signal.h>
  65. #ifdef FLAT_INC
  66. # include "e_os2.h"
  67. #else
  68. # include "../e_os2.h"
  69. #endif
  70. /*
  71. * With IPv6, it looks like Digital has mixed up the proper order of
  72. * recursive header file inclusion, resulting in the compiler complaining
  73. * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
  74. * needed to have fileno() declared correctly... So let's define u_int
  75. */
  76. #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
  77. # define __U_INT
  78. typedef unsigned int u_int;
  79. #endif
  80. #define USE_SOCKETS
  81. #define NON_MAIN
  82. #include "apps.h"
  83. #undef USE_SOCKETS
  84. #undef NON_MAIN
  85. #include "s_apps.h"
  86. #include <openssl/ssl.h>
  87. #ifdef FLAT_INC
  88. # include "e_os.h"
  89. #else
  90. # include "../e_os.h"
  91. #endif
  92. #ifndef OPENSSL_NO_SOCK
  93. # if defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_BSDSOCK)
  94. # include "netdb.h"
  95. # endif
  96. static struct hostent *GetHostByName(char *name);
  97. # if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
  98. static void ssl_sock_cleanup(void);
  99. # endif
  100. static int ssl_sock_init(void);
  101. static int init_client_ip(int *sock, unsigned char ip[4], int port, int type);
  102. static int init_server(int *sock, int port, int type);
  103. static int init_server_long(int *sock, int port, char *ip, int type);
  104. static int do_accept(int acc_sock, int *sock, char **host);
  105. static int host_ip(char *str, unsigned char ip[4]);
  106. # ifdef OPENSSL_SYS_WIN16
  107. # define SOCKET_PROTOCOL 0 /* more microsoft stupidity */
  108. # else
  109. # define SOCKET_PROTOCOL IPPROTO_TCP
  110. # endif
  111. # if defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
  112. static int wsa_init_done = 0;
  113. # endif
  114. # ifdef OPENSSL_SYS_WINDOWS
  115. static struct WSAData wsa_state;
  116. static int wsa_init_done = 0;
  117. # ifdef OPENSSL_SYS_WIN16
  118. static HWND topWnd = 0;
  119. static FARPROC lpTopWndProc = NULL;
  120. static FARPROC lpTopHookProc = NULL;
  121. extern HINSTANCE _hInstance; /* nice global CRT provides */
  122. static LONG FAR PASCAL topHookProc(HWND hwnd, UINT message, WPARAM wParam,
  123. LPARAM lParam)
  124. {
  125. if (hwnd == topWnd) {
  126. switch (message) {
  127. case WM_DESTROY:
  128. case WM_CLOSE:
  129. SetWindowLong(topWnd, GWL_WNDPROC, (LONG) lpTopWndProc);
  130. ssl_sock_cleanup();
  131. break;
  132. }
  133. }
  134. return CallWindowProc(lpTopWndProc, hwnd, message, wParam, lParam);
  135. }
  136. static BOOL CALLBACK enumproc(HWND hwnd, LPARAM lParam)
  137. {
  138. topWnd = hwnd;
  139. return (FALSE);
  140. }
  141. # endif /* OPENSSL_SYS_WIN32 */
  142. # endif /* OPENSSL_SYS_WINDOWS */
  143. # ifdef OPENSSL_SYS_WINDOWS
  144. static void ssl_sock_cleanup(void)
  145. {
  146. if (wsa_init_done) {
  147. wsa_init_done = 0;
  148. # ifndef OPENSSL_SYS_WINCE
  149. WSACancelBlockingCall();
  150. # endif
  151. WSACleanup();
  152. }
  153. }
  154. # elif defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
  155. static void sock_cleanup(void)
  156. {
  157. if (wsa_init_done) {
  158. wsa_init_done = 0;
  159. WSACleanup();
  160. }
  161. }
  162. # endif
  163. static int ssl_sock_init(void)
  164. {
  165. # ifdef WATT32
  166. extern int _watt_do_exit;
  167. _watt_do_exit = 0;
  168. if (sock_init())
  169. return (0);
  170. # elif defined(OPENSSL_SYS_WINDOWS)
  171. if (!wsa_init_done) {
  172. int err;
  173. # ifdef SIGINT
  174. signal(SIGINT, (void (*)(int))ssl_sock_cleanup);
  175. # endif
  176. wsa_init_done = 1;
  177. memset(&wsa_state, 0, sizeof(wsa_state));
  178. if (WSAStartup(0x0101, &wsa_state) != 0) {
  179. err = WSAGetLastError();
  180. BIO_printf(bio_err, "unable to start WINSOCK, error code=%d\n",
  181. err);
  182. return (0);
  183. }
  184. # ifdef OPENSSL_SYS_WIN16
  185. EnumTaskWindows(GetCurrentTask(), enumproc, 0L);
  186. lpTopWndProc = (FARPROC) GetWindowLong(topWnd, GWL_WNDPROC);
  187. lpTopHookProc = MakeProcInstance((FARPROC) topHookProc, _hInstance);
  188. SetWindowLong(topWnd, GWL_WNDPROC, (LONG) lpTopHookProc);
  189. # endif /* OPENSSL_SYS_WIN16 */
  190. }
  191. # elif defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
  192. WORD wVerReq;
  193. WSADATA wsaData;
  194. int err;
  195. if (!wsa_init_done) {
  196. # ifdef SIGINT
  197. signal(SIGINT, (void (*)(int))sock_cleanup);
  198. # endif
  199. wsa_init_done = 1;
  200. wVerReq = MAKEWORD(2, 0);
  201. err = WSAStartup(wVerReq, &wsaData);
  202. if (err != 0) {
  203. BIO_printf(bio_err, "unable to start WINSOCK2, error code=%d\n",
  204. err);
  205. return (0);
  206. }
  207. }
  208. # endif /* OPENSSL_SYS_WINDOWS */
  209. return (1);
  210. }
  211. int init_client(int *sock, char *host, int port, int type)
  212. {
  213. unsigned char ip[4];
  214. memset(ip, '\0', sizeof(ip));
  215. if (!host_ip(host, &(ip[0])))
  216. return 0;
  217. return init_client_ip(sock, ip, port, type);
  218. }
  219. static int init_client_ip(int *sock, unsigned char ip[4], int port, int type)
  220. {
  221. unsigned long addr;
  222. struct sockaddr_in them;
  223. int s, i;
  224. if (!ssl_sock_init())
  225. 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) | ((unsigned long)ip[3]);
  233. them.sin_addr.s_addr = htonl(addr);
  234. if (type == SOCK_STREAM)
  235. s = socket(AF_INET, SOCK_STREAM, SOCKET_PROTOCOL);
  236. else /* ( type == SOCK_DGRAM) */
  237. s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  238. if (s == INVALID_SOCKET) {
  239. perror("socket");
  240. return (0);
  241. }
  242. # if defined(SO_KEEPALIVE) && !defined(OPENSSL_SYS_MPE)
  243. if (type == SOCK_STREAM) {
  244. i = 0;
  245. i = setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char *)&i, sizeof(i));
  246. if (i < 0) {
  247. closesocket(s);
  248. perror("keepalive");
  249. return (0);
  250. }
  251. }
  252. # endif
  253. if (connect(s, (struct sockaddr *)&them, sizeof(them)) == -1) {
  254. closesocket(s);
  255. perror("connect");
  256. return (0);
  257. }
  258. *sock = s;
  259. return (1);
  260. }
  261. int do_server(int port, int type, int *ret,
  262. int (*cb) (char *hostname, int s, int stype,
  263. unsigned char *context), unsigned char *context,
  264. int naccept)
  265. {
  266. int sock;
  267. char *name = NULL;
  268. int accept_socket = 0;
  269. int i;
  270. if (!init_server(&accept_socket, port, type))
  271. return (0);
  272. if (ret != NULL) {
  273. *ret = accept_socket;
  274. /* return(1); */
  275. }
  276. for (;;) {
  277. if (type == SOCK_STREAM) {
  278. if (do_accept(accept_socket, &sock, &name) == 0) {
  279. SHUTDOWN(accept_socket);
  280. return (0);
  281. }
  282. } else
  283. sock = accept_socket;
  284. i = (*cb) (name, sock, type, context);
  285. if (name != NULL)
  286. OPENSSL_free(name);
  287. if (type == SOCK_STREAM)
  288. SHUTDOWN2(sock);
  289. if (naccept != -1)
  290. naccept--;
  291. if (i < 0 || naccept == 0) {
  292. SHUTDOWN2(accept_socket);
  293. return (i);
  294. }
  295. }
  296. }
  297. static int init_server_long(int *sock, int port, char *ip, int type)
  298. {
  299. int ret = 0;
  300. struct sockaddr_in server;
  301. int s = -1;
  302. if (!ssl_sock_init())
  303. return (0);
  304. memset((char *)&server, 0, sizeof(server));
  305. server.sin_family = AF_INET;
  306. server.sin_port = htons((unsigned short)port);
  307. if (ip == NULL)
  308. server.sin_addr.s_addr = INADDR_ANY;
  309. else
  310. /* Added for T3E, address-of fails on bit field (beckman@acl.lanl.gov) */
  311. # ifndef BIT_FIELD_LIMITS
  312. memcpy(&server.sin_addr.s_addr, ip, 4);
  313. # else
  314. memcpy(&server.sin_addr, ip, 4);
  315. # endif
  316. if (type == SOCK_STREAM)
  317. s = socket(AF_INET, SOCK_STREAM, SOCKET_PROTOCOL);
  318. else /* type == SOCK_DGRAM */
  319. s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  320. if (s == INVALID_SOCKET)
  321. goto err;
  322. # if defined SOL_SOCKET && defined SO_REUSEADDR
  323. {
  324. int j = 1;
  325. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void *)&j, sizeof(j));
  326. }
  327. # endif
  328. if (bind(s, (struct sockaddr *)&server, sizeof(server)) == -1) {
  329. # ifndef OPENSSL_SYS_WINDOWS
  330. perror("bind");
  331. # endif
  332. goto err;
  333. }
  334. /* Make it 128 for linux */
  335. if (type == SOCK_STREAM && listen(s, 128) == -1)
  336. goto err;
  337. *sock = s;
  338. ret = 1;
  339. err:
  340. if ((ret == 0) && (s != -1)) {
  341. SHUTDOWN(s);
  342. }
  343. return (ret);
  344. }
  345. static int init_server(int *sock, int port, int type)
  346. {
  347. return (init_server_long(sock, port, NULL, type));
  348. }
  349. static int do_accept(int acc_sock, int *sock, char **host)
  350. {
  351. int ret;
  352. struct hostent *h1, *h2;
  353. static struct sockaddr_in from;
  354. int len;
  355. /* struct linger ling; */
  356. if (!ssl_sock_init())
  357. return (0);
  358. # ifndef OPENSSL_SYS_WINDOWS
  359. redoit:
  360. # endif
  361. memset((char *)&from, 0, sizeof(from));
  362. len = sizeof(from);
  363. /*
  364. * Note: under VMS with SOCKETSHR the fourth parameter is currently of
  365. * type (int *) whereas under other systems it is (void *) if you don't
  366. * have a cast it will choke the compiler: if you do have a cast then you
  367. * can either go for (int *) or (void *).
  368. */
  369. ret = accept(acc_sock, (struct sockaddr *)&from, (void *)&len);
  370. if (ret == INVALID_SOCKET) {
  371. # if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
  372. int i;
  373. i = WSAGetLastError();
  374. BIO_printf(bio_err, "accept error %d\n", i);
  375. # else
  376. if (errno == EINTR) {
  377. /*
  378. * check_timeout();
  379. */
  380. goto redoit;
  381. }
  382. fprintf(stderr, "errno=%d ", errno);
  383. perror("accept");
  384. # endif
  385. return (0);
  386. }
  387. /*-
  388. ling.l_onoff=1;
  389. ling.l_linger=0;
  390. i=setsockopt(ret,SOL_SOCKET,SO_LINGER,(char *)&ling,sizeof(ling));
  391. if (i < 0) { perror("linger"); return(0); }
  392. i=0;
  393. i=setsockopt(ret,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i));
  394. if (i < 0) { perror("keepalive"); return(0); }
  395. */
  396. if (host == NULL)
  397. goto end;
  398. # ifndef BIT_FIELD_LIMITS
  399. /* I should use WSAAsyncGetHostByName() under windows */
  400. h1 = gethostbyaddr((char *)&from.sin_addr.s_addr,
  401. sizeof(from.sin_addr.s_addr), AF_INET);
  402. # else
  403. h1 = gethostbyaddr((char *)&from.sin_addr,
  404. sizeof(struct in_addr), AF_INET);
  405. # endif
  406. if (h1 == NULL) {
  407. BIO_printf(bio_err, "bad gethostbyaddr\n");
  408. *host = NULL;
  409. /* return(0); */
  410. } else {
  411. if ((*host = (char *)OPENSSL_malloc(strlen(h1->h_name) + 1)) == NULL) {
  412. perror("OPENSSL_malloc");
  413. closesocket(ret);
  414. return (0);
  415. }
  416. BUF_strlcpy(*host, h1->h_name, strlen(h1->h_name) + 1);
  417. h2 = GetHostByName(*host);
  418. if (h2 == NULL) {
  419. BIO_printf(bio_err, "gethostbyname failure\n");
  420. closesocket(ret);
  421. return (0);
  422. }
  423. if (h2->h_addrtype != AF_INET) {
  424. BIO_printf(bio_err, "gethostbyname addr is not AF_INET\n");
  425. closesocket(ret);
  426. return (0);
  427. }
  428. }
  429. end:
  430. *sock = ret;
  431. return (1);
  432. }
  433. int extract_host_port(char *str, char **host_ptr, unsigned char *ip,
  434. short *port_ptr)
  435. {
  436. char *h, *p;
  437. h = str;
  438. p = strchr(str, ':');
  439. if (p == NULL) {
  440. BIO_printf(bio_err, "no port defined\n");
  441. return (0);
  442. }
  443. *(p++) = '\0';
  444. if ((ip != NULL) && !host_ip(str, ip))
  445. goto err;
  446. if (host_ptr != NULL)
  447. *host_ptr = h;
  448. if (!extract_port(p, port_ptr))
  449. goto err;
  450. return (1);
  451. err:
  452. return (0);
  453. }
  454. static int host_ip(char *str, unsigned char ip[4])
  455. {
  456. unsigned int in[4];
  457. int i;
  458. if (sscanf(str, "%u.%u.%u.%u", &(in[0]), &(in[1]), &(in[2]), &(in[3])) ==
  459. 4) {
  460. for (i = 0; i < 4; i++)
  461. if (in[i] > 255) {
  462. BIO_printf(bio_err, "invalid IP address\n");
  463. goto err;
  464. }
  465. ip[0] = in[0];
  466. ip[1] = in[1];
  467. ip[2] = in[2];
  468. ip[3] = in[3];
  469. } else { /* do a gethostbyname */
  470. struct hostent *he;
  471. if (!ssl_sock_init())
  472. return (0);
  473. he = GetHostByName(str);
  474. if (he == NULL) {
  475. BIO_printf(bio_err, "gethostbyname failure\n");
  476. goto err;
  477. }
  478. /* cast to short because of win16 winsock definition */
  479. if ((short)he->h_addrtype != AF_INET) {
  480. BIO_printf(bio_err, "gethostbyname addr is not AF_INET\n");
  481. return (0);
  482. }
  483. ip[0] = he->h_addr_list[0][0];
  484. ip[1] = he->h_addr_list[0][1];
  485. ip[2] = he->h_addr_list[0][2];
  486. ip[3] = he->h_addr_list[0][3];
  487. }
  488. return (1);
  489. err:
  490. return (0);
  491. }
  492. int extract_port(char *str, short *port_ptr)
  493. {
  494. int i;
  495. struct servent *s;
  496. i = atoi(str);
  497. if (i != 0)
  498. *port_ptr = (unsigned short)i;
  499. else {
  500. s = getservbyname(str, "tcp");
  501. if (s == NULL) {
  502. BIO_printf(bio_err, "getservbyname failure for %s\n", str);
  503. return (0);
  504. }
  505. *port_ptr = ntohs((unsigned short)s->s_port);
  506. }
  507. return (1);
  508. }
  509. # define GHBN_NUM 4
  510. static struct ghbn_cache_st {
  511. char name[128];
  512. struct hostent ent;
  513. unsigned long order;
  514. } ghbn_cache[GHBN_NUM];
  515. static unsigned long ghbn_hits = 0L;
  516. static unsigned long ghbn_miss = 0L;
  517. static struct hostent *GetHostByName(char *name)
  518. {
  519. struct hostent *ret;
  520. int i, lowi = 0;
  521. unsigned long low = (unsigned long)-1;
  522. for (i = 0; i < GHBN_NUM; i++) {
  523. if (low > ghbn_cache[i].order) {
  524. low = ghbn_cache[i].order;
  525. lowi = i;
  526. }
  527. if (ghbn_cache[i].order > 0) {
  528. if (strncmp(name, ghbn_cache[i].name, 128) == 0)
  529. break;
  530. }
  531. }
  532. if (i == GHBN_NUM) { /* no hit */
  533. ghbn_miss++;
  534. ret = gethostbyname(name);
  535. if (ret == NULL)
  536. return (NULL);
  537. /* else add to cache */
  538. if (strlen(name) < sizeof(ghbn_cache[0].name)) {
  539. strcpy(ghbn_cache[lowi].name, name);
  540. memcpy((char *)&(ghbn_cache[lowi].ent), ret,
  541. sizeof(struct hostent));
  542. ghbn_cache[lowi].order = ghbn_miss + ghbn_hits;
  543. }
  544. return (ret);
  545. } else {
  546. ghbn_hits++;
  547. ret = &(ghbn_cache[i].ent);
  548. ghbn_cache[i].order = ghbn_miss + ghbn_hits;
  549. return (ret);
  550. }
  551. }
  552. #endif