s_socket.c 16 KB

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