s_socket.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. short p = 0;
  215. if (!host_ip(host, &(ip[0]))) {
  216. return (0);
  217. }
  218. if (p != 0)
  219. port = p;
  220. return (init_client_ip(sock, ip, port, type));
  221. }
  222. static int init_client_ip(int *sock, unsigned char ip[4], int port, int type)
  223. {
  224. unsigned long addr;
  225. struct sockaddr_in them;
  226. int s, i;
  227. if (!ssl_sock_init())
  228. return (0);
  229. memset((char *)&them, 0, sizeof(them));
  230. them.sin_family = AF_INET;
  231. them.sin_port = htons((unsigned short)port);
  232. addr = (unsigned long)
  233. ((unsigned long)ip[0] << 24L) |
  234. ((unsigned long)ip[1] << 16L) |
  235. ((unsigned long)ip[2] << 8L) | ((unsigned long)ip[3]);
  236. them.sin_addr.s_addr = htonl(addr);
  237. if (type == SOCK_STREAM)
  238. s = socket(AF_INET, SOCK_STREAM, SOCKET_PROTOCOL);
  239. else /* ( type == SOCK_DGRAM) */
  240. s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  241. if (s == INVALID_SOCKET) {
  242. perror("socket");
  243. return (0);
  244. }
  245. # ifndef OPENSSL_SYS_MPE
  246. if (type == SOCK_STREAM) {
  247. i = 0;
  248. i = setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char *)&i, sizeof(i));
  249. if (i < 0) {
  250. perror("keepalive");
  251. return (0);
  252. }
  253. }
  254. # endif
  255. if (connect(s, (struct sockaddr *)&them, sizeof(them)) == -1) {
  256. close(s);
  257. perror("connect");
  258. return (0);
  259. }
  260. *sock = s;
  261. return (1);
  262. }
  263. int do_server(int port, int type, int *ret,
  264. int (*cb) (char *hostname, int s, unsigned char *context),
  265. unsigned char *context)
  266. {
  267. int sock;
  268. char *name = NULL;
  269. int accept_socket;
  270. int i;
  271. if (!init_server(&accept_socket, port, type))
  272. return (0);
  273. if (ret != NULL) {
  274. *ret = accept_socket;
  275. /* return(1); */
  276. }
  277. for (;;) {
  278. if (type == SOCK_STREAM) {
  279. if (do_accept(accept_socket, &sock, &name) == 0) {
  280. SHUTDOWN(accept_socket);
  281. return (0);
  282. }
  283. } else
  284. sock = accept_socket;
  285. i = (*cb) (name, sock, context);
  286. if (name != NULL)
  287. OPENSSL_free(name);
  288. if (type == SOCK_STREAM)
  289. SHUTDOWN2(sock);
  290. if (i < 0) {
  291. SHUTDOWN2(accept_socket);
  292. return (i);
  293. }
  294. }
  295. }
  296. static int init_server_long(int *sock, int port, char *ip, int type)
  297. {
  298. int ret = 0;
  299. struct sockaddr_in server;
  300. int s = -1;
  301. if (!ssl_sock_init())
  302. return (0);
  303. memset((char *)&server, 0, sizeof(server));
  304. server.sin_family = AF_INET;
  305. server.sin_port = htons((unsigned short)port);
  306. if (ip == NULL)
  307. server.sin_addr.s_addr = INADDR_ANY;
  308. else
  309. /* Added for T3E, address-of fails on bit field (beckman@acl.lanl.gov) */
  310. # ifndef BIT_FIELD_LIMITS
  311. memcpy(&server.sin_addr.s_addr, ip, 4);
  312. # else
  313. memcpy(&server.sin_addr, ip, 4);
  314. # endif
  315. if (type == SOCK_STREAM)
  316. s = socket(AF_INET, SOCK_STREAM, SOCKET_PROTOCOL);
  317. else /* type == SOCK_DGRAM */
  318. s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  319. if (s == INVALID_SOCKET)
  320. goto err;
  321. # if defined SOL_SOCKET && defined SO_REUSEADDR
  322. {
  323. int j = 1;
  324. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void *)&j, sizeof j);
  325. }
  326. # endif
  327. if (bind(s, (struct sockaddr *)&server, sizeof(server)) == -1) {
  328. # ifndef OPENSSL_SYS_WINDOWS
  329. perror("bind");
  330. # endif
  331. goto err;
  332. }
  333. /* Make it 128 for linux */
  334. if (type == SOCK_STREAM && listen(s, 128) == -1)
  335. goto err;
  336. *sock = s;
  337. ret = 1;
  338. err:
  339. if ((ret == 0) && (s != -1)) {
  340. SHUTDOWN(s);
  341. }
  342. return (ret);
  343. }
  344. static int init_server(int *sock, int port, int type)
  345. {
  346. return (init_server_long(sock, port, NULL, type));
  347. }
  348. static int do_accept(int acc_sock, int *sock, char **host)
  349. {
  350. int ret;
  351. struct hostent *h1, *h2;
  352. static struct sockaddr_in from;
  353. int len;
  354. /* struct linger ling; */
  355. if (!ssl_sock_init())
  356. return (0);
  357. # ifndef OPENSSL_SYS_WINDOWS
  358. redoit:
  359. # endif
  360. memset((char *)&from, 0, sizeof(from));
  361. len = sizeof(from);
  362. /*
  363. * Note: under VMS with SOCKETSHR the fourth parameter is currently of
  364. * type (int *) whereas under other systems it is (void *) if you don't
  365. * have a cast it will choke the compiler: if you do have a cast then you
  366. * can either go for (int *) or (void *).
  367. */
  368. ret = accept(acc_sock, (struct sockaddr *)&from, (void *)&len);
  369. if (ret == INVALID_SOCKET) {
  370. # if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
  371. int i;
  372. i = WSAGetLastError();
  373. BIO_printf(bio_err, "accept error %d\n", i);
  374. # else
  375. if (errno == EINTR) {
  376. /*
  377. * check_timeout();
  378. */
  379. goto redoit;
  380. }
  381. fprintf(stderr, "errno=%d ", errno);
  382. perror("accept");
  383. # endif
  384. return (0);
  385. }
  386. /*-
  387. ling.l_onoff=1;
  388. ling.l_linger=0;
  389. i=setsockopt(ret,SOL_SOCKET,SO_LINGER,(char *)&ling,sizeof(ling));
  390. if (i < 0) { perror("linger"); return(0); }
  391. i=0;
  392. i=setsockopt(ret,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i));
  393. if (i < 0) { perror("keepalive"); return(0); }
  394. */
  395. if (host == NULL)
  396. goto end;
  397. # ifndef BIT_FIELD_LIMITS
  398. /* I should use WSAAsyncGetHostByName() under windows */
  399. h1 = gethostbyaddr((char *)&from.sin_addr.s_addr,
  400. sizeof(from.sin_addr.s_addr), AF_INET);
  401. # else
  402. h1 = gethostbyaddr((char *)&from.sin_addr,
  403. sizeof(struct in_addr), AF_INET);
  404. # endif
  405. if (h1 == NULL) {
  406. BIO_printf(bio_err, "bad gethostbyaddr\n");
  407. *host = NULL;
  408. /* return(0); */
  409. } else {
  410. if ((*host = (char *)OPENSSL_malloc(strlen(h1->h_name) + 1)) == NULL) {
  411. perror("OPENSSL_malloc");
  412. return (0);
  413. }
  414. BUF_strlcpy(*host, h1->h_name, strlen(h1->h_name) + 1);
  415. h2 = GetHostByName(*host);
  416. if (h2 == NULL) {
  417. BIO_printf(bio_err, "gethostbyname failure\n");
  418. return (0);
  419. }
  420. if (h2->h_addrtype != AF_INET) {
  421. BIO_printf(bio_err, "gethostbyname addr is not AF_INET\n");
  422. return (0);
  423. }
  424. }
  425. end:
  426. *sock = ret;
  427. return (1);
  428. }
  429. int extract_host_port(char *str, char **host_ptr, unsigned char *ip,
  430. short *port_ptr)
  431. {
  432. char *h, *p;
  433. h = str;
  434. p = strchr(str, ':');
  435. if (p == NULL) {
  436. BIO_printf(bio_err, "no port defined\n");
  437. return (0);
  438. }
  439. *(p++) = '\0';
  440. if ((ip != NULL) && !host_ip(str, ip))
  441. goto err;
  442. if (host_ptr != NULL)
  443. *host_ptr = h;
  444. if (!extract_port(p, port_ptr))
  445. goto err;
  446. return (1);
  447. err:
  448. return (0);
  449. }
  450. static int host_ip(char *str, unsigned char ip[4])
  451. {
  452. unsigned int in[4];
  453. int i;
  454. if (sscanf(str, "%u.%u.%u.%u", &(in[0]), &(in[1]), &(in[2]), &(in[3])) ==
  455. 4) {
  456. for (i = 0; i < 4; i++)
  457. if (in[i] > 255) {
  458. BIO_printf(bio_err, "invalid IP address\n");
  459. goto err;
  460. }
  461. ip[0] = in[0];
  462. ip[1] = in[1];
  463. ip[2] = in[2];
  464. ip[3] = in[3];
  465. } else { /* do a gethostbyname */
  466. struct hostent *he;
  467. if (!ssl_sock_init())
  468. return (0);
  469. he = GetHostByName(str);
  470. if (he == NULL) {
  471. BIO_printf(bio_err, "gethostbyname failure\n");
  472. goto err;
  473. }
  474. /* cast to short because of win16 winsock definition */
  475. if ((short)he->h_addrtype != AF_INET) {
  476. BIO_printf(bio_err, "gethostbyname addr is not AF_INET\n");
  477. return (0);
  478. }
  479. ip[0] = he->h_addr_list[0][0];
  480. ip[1] = he->h_addr_list[0][1];
  481. ip[2] = he->h_addr_list[0][2];
  482. ip[3] = he->h_addr_list[0][3];
  483. }
  484. return (1);
  485. err:
  486. return (0);
  487. }
  488. int extract_port(char *str, short *port_ptr)
  489. {
  490. int i;
  491. struct servent *s;
  492. i = atoi(str);
  493. if (i != 0)
  494. *port_ptr = (unsigned short)i;
  495. else {
  496. s = getservbyname(str, "tcp");
  497. if (s == NULL) {
  498. BIO_printf(bio_err, "getservbyname failure for %s\n", str);
  499. return (0);
  500. }
  501. *port_ptr = ntohs((unsigned short)s->s_port);
  502. }
  503. return (1);
  504. }
  505. # define GHBN_NUM 4
  506. static struct ghbn_cache_st {
  507. char name[128];
  508. struct hostent ent;
  509. unsigned long order;
  510. } ghbn_cache[GHBN_NUM];
  511. static unsigned long ghbn_hits = 0L;
  512. static unsigned long ghbn_miss = 0L;
  513. static struct hostent *GetHostByName(char *name)
  514. {
  515. struct hostent *ret;
  516. int i, lowi = 0;
  517. unsigned long low = (unsigned long)-1;
  518. for (i = 0; i < GHBN_NUM; i++) {
  519. if (low > ghbn_cache[i].order) {
  520. low = ghbn_cache[i].order;
  521. lowi = i;
  522. }
  523. if (ghbn_cache[i].order > 0) {
  524. if (strncmp(name, ghbn_cache[i].name, 128) == 0)
  525. break;
  526. }
  527. }
  528. if (i == GHBN_NUM) { /* no hit */
  529. ghbn_miss++;
  530. ret = gethostbyname(name);
  531. if (ret == NULL)
  532. return (NULL);
  533. /* else add to cache */
  534. if (strlen(name) < sizeof ghbn_cache[0].name) {
  535. strcpy(ghbn_cache[lowi].name, name);
  536. memcpy((char *)&(ghbn_cache[lowi].ent), ret,
  537. sizeof(struct hostent));
  538. ghbn_cache[lowi].order = ghbn_miss + ghbn_hits;
  539. }
  540. return (ret);
  541. } else {
  542. ghbn_hits++;
  543. ret = &(ghbn_cache[i].ent);
  544. ghbn_cache[i].order = ghbn_miss + ghbn_hits;
  545. return (ret);
  546. }
  547. }
  548. #endif