s_socket.c 17 KB

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