b_sock.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. /* crypto/bio/b_sock.c */
  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 <errno.h>
  61. #define USE_SOCKETS
  62. #include "cryptlib.h"
  63. #include <openssl/bio.h>
  64. #if defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_BSDSOCK)
  65. # include <netdb.h>
  66. # if defined(NETWARE_CLIB)
  67. # include <sys/ioctl.h>
  68. NETDB_DEFINE_CONTEXT
  69. # endif
  70. #endif
  71. #ifndef OPENSSL_NO_SOCK
  72. # include <openssl/dso.h>
  73. # define SOCKET_PROTOCOL IPPROTO_TCP
  74. # ifdef SO_MAXCONN
  75. # define MAX_LISTEN SO_MAXCONN
  76. # elif defined(SOMAXCONN)
  77. # define MAX_LISTEN SOMAXCONN
  78. # else
  79. # define MAX_LISTEN 32
  80. # endif
  81. # if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
  82. static int wsa_init_done = 0;
  83. # endif
  84. /*
  85. * WSAAPI specifier is required to make indirect calls to run-time
  86. * linked WinSock 2 functions used in this module, to be specific
  87. * [get|free]addrinfo and getnameinfo. This is because WinSock uses
  88. * uses non-C calling convention, __stdcall vs. __cdecl, on x86
  89. * Windows. On non-WinSock platforms WSAAPI needs to be void.
  90. */
  91. # ifndef WSAAPI
  92. # define WSAAPI
  93. # endif
  94. # if 0
  95. static unsigned long BIO_ghbn_hits = 0L;
  96. static unsigned long BIO_ghbn_miss = 0L;
  97. # define GHBN_NUM 4
  98. static struct ghbn_cache_st {
  99. char name[129];
  100. struct hostent *ent;
  101. unsigned long order;
  102. } ghbn_cache[GHBN_NUM];
  103. # endif
  104. static int get_ip(const char *str, unsigned char *ip);
  105. # if 0
  106. static void ghbn_free(struct hostent *a);
  107. static struct hostent *ghbn_dup(struct hostent *a);
  108. # endif
  109. int BIO_get_host_ip(const char *str, unsigned char *ip)
  110. {
  111. int i;
  112. int err = 1;
  113. int locked = 0;
  114. struct hostent *he;
  115. i = get_ip(str, ip);
  116. if (i < 0) {
  117. BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_INVALID_IP_ADDRESS);
  118. goto err;
  119. }
  120. /*
  121. * At this point, we have something that is most probably correct in some
  122. * way, so let's init the socket.
  123. */
  124. if (BIO_sock_init() != 1)
  125. return 0; /* don't generate another error code here */
  126. /*
  127. * If the string actually contained an IP address, we need not do
  128. * anything more
  129. */
  130. if (i > 0)
  131. return (1);
  132. /* do a gethostbyname */
  133. CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
  134. locked = 1;
  135. he = BIO_gethostbyname(str);
  136. if (he == NULL) {
  137. BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_BAD_HOSTNAME_LOOKUP);
  138. goto err;
  139. }
  140. /* cast to short because of win16 winsock definition */
  141. if ((short)he->h_addrtype != AF_INET) {
  142. BIOerr(BIO_F_BIO_GET_HOST_IP,
  143. BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET);
  144. goto err;
  145. }
  146. for (i = 0; i < 4; i++)
  147. ip[i] = he->h_addr_list[0][i];
  148. err = 0;
  149. err:
  150. if (locked)
  151. CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME);
  152. if (err) {
  153. ERR_add_error_data(2, "host=", str);
  154. return 0;
  155. } else
  156. return 1;
  157. }
  158. int BIO_get_port(const char *str, unsigned short *port_ptr)
  159. {
  160. int i;
  161. struct servent *s;
  162. if (str == NULL) {
  163. BIOerr(BIO_F_BIO_GET_PORT, BIO_R_NO_PORT_DEFINED);
  164. return (0);
  165. }
  166. i = atoi(str);
  167. if (i != 0)
  168. *port_ptr = (unsigned short)i;
  169. else {
  170. CRYPTO_w_lock(CRYPTO_LOCK_GETSERVBYNAME);
  171. /*
  172. * Note: under VMS with SOCKETSHR, it seems like the first parameter
  173. * is 'char *', instead of 'const char *'
  174. */
  175. # ifndef CONST_STRICT
  176. s = getservbyname((char *)str, "tcp");
  177. # else
  178. s = getservbyname(str, "tcp");
  179. # endif
  180. if (s != NULL)
  181. *port_ptr = ntohs((unsigned short)s->s_port);
  182. CRYPTO_w_unlock(CRYPTO_LOCK_GETSERVBYNAME);
  183. if (s == NULL) {
  184. if (strcmp(str, "http") == 0)
  185. *port_ptr = 80;
  186. else if (strcmp(str, "telnet") == 0)
  187. *port_ptr = 23;
  188. else if (strcmp(str, "socks") == 0)
  189. *port_ptr = 1080;
  190. else if (strcmp(str, "https") == 0)
  191. *port_ptr = 443;
  192. else if (strcmp(str, "ssl") == 0)
  193. *port_ptr = 443;
  194. else if (strcmp(str, "ftp") == 0)
  195. *port_ptr = 21;
  196. else if (strcmp(str, "gopher") == 0)
  197. *port_ptr = 70;
  198. # if 0
  199. else if (strcmp(str, "wais") == 0)
  200. *port_ptr = 21;
  201. # endif
  202. else {
  203. SYSerr(SYS_F_GETSERVBYNAME, get_last_socket_error());
  204. ERR_add_error_data(3, "service='", str, "'");
  205. return (0);
  206. }
  207. }
  208. }
  209. return (1);
  210. }
  211. int BIO_sock_error(int sock)
  212. {
  213. int j, i;
  214. int size;
  215. # if defined(OPENSSL_SYS_BEOS_R5)
  216. return 0;
  217. # endif
  218. size = sizeof(int);
  219. /*
  220. * Note: under Windows the third parameter is of type (char *) whereas
  221. * under other systems it is (void *) if you don't have a cast it will
  222. * choke the compiler: if you do have a cast then you can either go for
  223. * (char *) or (void *).
  224. */
  225. i = getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&j, (void *)&size);
  226. if (i < 0)
  227. return (1);
  228. else
  229. return (j);
  230. }
  231. # if 0
  232. long BIO_ghbn_ctrl(int cmd, int iarg, char *parg)
  233. {
  234. int i;
  235. char **p;
  236. switch (cmd) {
  237. case BIO_GHBN_CTRL_HITS:
  238. return (BIO_ghbn_hits);
  239. /* break; */
  240. case BIO_GHBN_CTRL_MISSES:
  241. return (BIO_ghbn_miss);
  242. /* break; */
  243. case BIO_GHBN_CTRL_CACHE_SIZE:
  244. return (GHBN_NUM);
  245. /* break; */
  246. case BIO_GHBN_CTRL_GET_ENTRY:
  247. if ((iarg >= 0) && (iarg < GHBN_NUM) && (ghbn_cache[iarg].order > 0)) {
  248. p = (char **)parg;
  249. if (p == NULL)
  250. return (0);
  251. *p = ghbn_cache[iarg].name;
  252. ghbn_cache[iarg].name[128] = '\0';
  253. return (1);
  254. }
  255. return (0);
  256. /* break; */
  257. case BIO_GHBN_CTRL_FLUSH:
  258. for (i = 0; i < GHBN_NUM; i++)
  259. ghbn_cache[i].order = 0;
  260. break;
  261. default:
  262. return (0);
  263. }
  264. return (1);
  265. }
  266. # endif
  267. # if 0
  268. static struct hostent *ghbn_dup(struct hostent *a)
  269. {
  270. struct hostent *ret;
  271. int i, j;
  272. MemCheck_off();
  273. ret = (struct hostent *)OPENSSL_malloc(sizeof(struct hostent));
  274. if (ret == NULL)
  275. return (NULL);
  276. memset(ret, 0, sizeof(struct hostent));
  277. for (i = 0; a->h_aliases[i] != NULL; i++) ;
  278. i++;
  279. ret->h_aliases = (char **)OPENSSL_malloc(i * sizeof(char *));
  280. if (ret->h_aliases == NULL)
  281. goto err;
  282. memset(ret->h_aliases, 0, i * sizeof(char *));
  283. for (i = 0; a->h_addr_list[i] != NULL; i++) ;
  284. i++;
  285. ret->h_addr_list = (char **)OPENSSL_malloc(i * sizeof(char *));
  286. if (ret->h_addr_list == NULL)
  287. goto err;
  288. memset(ret->h_addr_list, 0, i * sizeof(char *));
  289. j = strlen(a->h_name) + 1;
  290. if ((ret->h_name = OPENSSL_malloc(j)) == NULL)
  291. goto err;
  292. memcpy((char *)ret->h_name, a->h_name, j);
  293. for (i = 0; a->h_aliases[i] != NULL; i++) {
  294. j = strlen(a->h_aliases[i]) + 1;
  295. if ((ret->h_aliases[i] = OPENSSL_malloc(j)) == NULL)
  296. goto err;
  297. memcpy(ret->h_aliases[i], a->h_aliases[i], j);
  298. }
  299. ret->h_length = a->h_length;
  300. ret->h_addrtype = a->h_addrtype;
  301. for (i = 0; a->h_addr_list[i] != NULL; i++) {
  302. if ((ret->h_addr_list[i] = OPENSSL_malloc(a->h_length)) == NULL)
  303. goto err;
  304. memcpy(ret->h_addr_list[i], a->h_addr_list[i], a->h_length);
  305. }
  306. if (0) {
  307. err:
  308. if (ret != NULL)
  309. ghbn_free(ret);
  310. ret = NULL;
  311. }
  312. MemCheck_on();
  313. return (ret);
  314. }
  315. static void ghbn_free(struct hostent *a)
  316. {
  317. int i;
  318. if (a == NULL)
  319. return;
  320. if (a->h_aliases != NULL) {
  321. for (i = 0; a->h_aliases[i] != NULL; i++)
  322. OPENSSL_free(a->h_aliases[i]);
  323. OPENSSL_free(a->h_aliases);
  324. }
  325. if (a->h_addr_list != NULL) {
  326. for (i = 0; a->h_addr_list[i] != NULL; i++)
  327. OPENSSL_free(a->h_addr_list[i]);
  328. OPENSSL_free(a->h_addr_list);
  329. }
  330. if (a->h_name != NULL)
  331. OPENSSL_free(a->h_name);
  332. OPENSSL_free(a);
  333. }
  334. # endif
  335. struct hostent *BIO_gethostbyname(const char *name)
  336. {
  337. # if 1
  338. /*
  339. * Caching gethostbyname() results forever is wrong, so we have to let
  340. * the true gethostbyname() worry about this
  341. */
  342. # if (defined(NETWARE_BSDSOCK) && !defined(__NOVELL_LIBC__))
  343. return gethostbyname((char *)name);
  344. # else
  345. return gethostbyname(name);
  346. # endif
  347. # else
  348. struct hostent *ret;
  349. int i, lowi = 0, j;
  350. unsigned long low = (unsigned long)-1;
  351. # if 0
  352. /*
  353. * It doesn't make sense to use locking here: The function interface is
  354. * not thread-safe, because threads can never be sure when some other
  355. * thread destroys the data they were given a pointer to.
  356. */
  357. CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
  358. # endif
  359. j = strlen(name);
  360. if (j < 128) {
  361. for (i = 0; i < GHBN_NUM; i++) {
  362. if (low > ghbn_cache[i].order) {
  363. low = ghbn_cache[i].order;
  364. lowi = i;
  365. }
  366. if (ghbn_cache[i].order > 0) {
  367. if (strncmp(name, ghbn_cache[i].name, 128) == 0)
  368. break;
  369. }
  370. }
  371. } else
  372. i = GHBN_NUM;
  373. if (i == GHBN_NUM) { /* no hit */
  374. BIO_ghbn_miss++;
  375. /*
  376. * Note: under VMS with SOCKETSHR, it seems like the first parameter
  377. * is 'char *', instead of 'const char *'
  378. */
  379. # ifndef CONST_STRICT
  380. ret = gethostbyname((char *)name);
  381. # else
  382. ret = gethostbyname(name);
  383. # endif
  384. if (ret == NULL)
  385. goto end;
  386. if (j > 128) { /* too big to cache */
  387. # if 0
  388. /*
  389. * If we were trying to make this function thread-safe (which is
  390. * bound to fail), we'd have to give up in this case (or allocate
  391. * more memory).
  392. */
  393. ret = NULL;
  394. # endif
  395. goto end;
  396. }
  397. /* else add to cache */
  398. if (ghbn_cache[lowi].ent != NULL)
  399. ghbn_free(ghbn_cache[lowi].ent); /* XXX not thread-safe */
  400. ghbn_cache[lowi].name[0] = '\0';
  401. if ((ret = ghbn_cache[lowi].ent = ghbn_dup(ret)) == NULL) {
  402. BIOerr(BIO_F_BIO_GETHOSTBYNAME, ERR_R_MALLOC_FAILURE);
  403. goto end;
  404. }
  405. strncpy(ghbn_cache[lowi].name, name, 128);
  406. ghbn_cache[lowi].order = BIO_ghbn_miss + BIO_ghbn_hits;
  407. } else {
  408. BIO_ghbn_hits++;
  409. ret = ghbn_cache[i].ent;
  410. ghbn_cache[i].order = BIO_ghbn_miss + BIO_ghbn_hits;
  411. }
  412. end:
  413. # if 0
  414. CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME);
  415. # endif
  416. return (ret);
  417. # endif
  418. }
  419. int BIO_sock_init(void)
  420. {
  421. # ifdef OPENSSL_SYS_WINDOWS
  422. static struct WSAData wsa_state;
  423. if (!wsa_init_done) {
  424. int err;
  425. wsa_init_done = 1;
  426. memset(&wsa_state, 0, sizeof(wsa_state));
  427. /*
  428. * Not making wsa_state available to the rest of the code is formally
  429. * wrong. But the structures we use are [beleived to be] invariable
  430. * among Winsock DLLs, while API availability is [expected to be]
  431. * probed at run-time with DSO_global_lookup.
  432. */
  433. if (WSAStartup(0x0202, &wsa_state) != 0) {
  434. err = WSAGetLastError();
  435. SYSerr(SYS_F_WSASTARTUP, err);
  436. BIOerr(BIO_F_BIO_SOCK_INIT, BIO_R_WSASTARTUP);
  437. return (-1);
  438. }
  439. }
  440. # endif /* OPENSSL_SYS_WINDOWS */
  441. # ifdef WATT32
  442. extern int _watt_do_exit;
  443. _watt_do_exit = 0; /* don't make sock_init() call exit() */
  444. if (sock_init())
  445. return (-1);
  446. # endif
  447. # if defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
  448. WORD wVerReq;
  449. WSADATA wsaData;
  450. int err;
  451. if (!wsa_init_done) {
  452. wsa_init_done = 1;
  453. wVerReq = MAKEWORD(2, 0);
  454. err = WSAStartup(wVerReq, &wsaData);
  455. if (err != 0) {
  456. SYSerr(SYS_F_WSASTARTUP, err);
  457. BIOerr(BIO_F_BIO_SOCK_INIT, BIO_R_WSASTARTUP);
  458. return (-1);
  459. }
  460. }
  461. # endif
  462. return (1);
  463. }
  464. void BIO_sock_cleanup(void)
  465. {
  466. # ifdef OPENSSL_SYS_WINDOWS
  467. if (wsa_init_done) {
  468. wsa_init_done = 0;
  469. # if 0 /* this call is claimed to be non-present in
  470. * Winsock2 */
  471. WSACancelBlockingCall();
  472. # endif
  473. WSACleanup();
  474. }
  475. # elif defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
  476. if (wsa_init_done) {
  477. wsa_init_done = 0;
  478. WSACleanup();
  479. }
  480. # endif
  481. }
  482. # if !defined(OPENSSL_SYS_VMS) || __VMS_VER >= 70000000
  483. int BIO_socket_ioctl(int fd, long type, void *arg)
  484. {
  485. int i;
  486. # ifdef __DJGPP__
  487. i = ioctlsocket(fd, type, (char *)arg);
  488. # else
  489. # if defined(OPENSSL_SYS_VMS)
  490. /*-
  491. * 2011-02-18 SMS.
  492. * VMS ioctl() can't tolerate a 64-bit "void *arg", but we
  493. * observe that all the consumers pass in an "unsigned long *",
  494. * so we arrange a local copy with a short pointer, and use
  495. * that, instead.
  496. */
  497. # if __INITIAL_POINTER_SIZE == 64
  498. # define ARG arg_32p
  499. # pragma pointer_size save
  500. # pragma pointer_size 32
  501. unsigned long arg_32;
  502. unsigned long *arg_32p;
  503. # pragma pointer_size restore
  504. arg_32p = &arg_32;
  505. arg_32 = *((unsigned long *)arg);
  506. # else /* __INITIAL_POINTER_SIZE == 64 */
  507. # define ARG arg
  508. # endif /* __INITIAL_POINTER_SIZE == 64 [else] */
  509. # else /* defined(OPENSSL_SYS_VMS) */
  510. # define ARG arg
  511. # endif /* defined(OPENSSL_SYS_VMS) [else] */
  512. i = ioctlsocket(fd, type, ARG);
  513. # endif /* __DJGPP__ */
  514. if (i < 0)
  515. SYSerr(SYS_F_IOCTLSOCKET, get_last_socket_error());
  516. return (i);
  517. }
  518. # endif /* __VMS_VER */
  519. /*
  520. * The reason I have implemented this instead of using sscanf is because
  521. * Visual C 1.52c gives an unresolved external when linking a DLL :-(
  522. */
  523. static int get_ip(const char *str, unsigned char ip[4])
  524. {
  525. unsigned int tmp[4];
  526. int num = 0, c, ok = 0;
  527. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  528. for (;;) {
  529. c = *(str++);
  530. if ((c >= '0') && (c <= '9')) {
  531. ok = 1;
  532. tmp[num] = tmp[num] * 10 + c - '0';
  533. if (tmp[num] > 255)
  534. return (0);
  535. } else if (c == '.') {
  536. if (!ok)
  537. return (-1);
  538. if (num == 3)
  539. return (0);
  540. num++;
  541. ok = 0;
  542. } else if (c == '\0' && (num == 3) && ok)
  543. break;
  544. else
  545. return (0);
  546. }
  547. ip[0] = tmp[0];
  548. ip[1] = tmp[1];
  549. ip[2] = tmp[2];
  550. ip[3] = tmp[3];
  551. return (1);
  552. }
  553. int BIO_get_accept_socket(char *host, int bind_mode)
  554. {
  555. int ret = 0;
  556. union {
  557. struct sockaddr sa;
  558. struct sockaddr_in sa_in;
  559. # if OPENSSL_USE_IPV6
  560. struct sockaddr_in6 sa_in6;
  561. # endif
  562. } server, client;
  563. int s = INVALID_SOCKET, cs, addrlen;
  564. unsigned char ip[4];
  565. unsigned short port;
  566. char *str = NULL, *e;
  567. char *h, *p;
  568. unsigned long l;
  569. int err_num;
  570. if (BIO_sock_init() != 1)
  571. return (INVALID_SOCKET);
  572. if ((str = BUF_strdup(host)) == NULL)
  573. return (INVALID_SOCKET);
  574. h = p = NULL;
  575. h = str;
  576. for (e = str; *e; e++) {
  577. if (*e == ':') {
  578. p = e;
  579. } else if (*e == '/') {
  580. *e = '\0';
  581. break;
  582. }
  583. }
  584. if (p)
  585. *p++ = '\0'; /* points at last ':', '::port' is special
  586. * [see below] */
  587. else
  588. p = h, h = NULL;
  589. # ifdef EAI_FAMILY
  590. do {
  591. static union {
  592. void *p;
  593. int (WSAAPI *f) (const char *, const char *,
  594. const struct addrinfo *, struct addrinfo **);
  595. } p_getaddrinfo = {
  596. NULL
  597. };
  598. static union {
  599. void *p;
  600. void (WSAAPI *f) (struct addrinfo *);
  601. } p_freeaddrinfo = {
  602. NULL
  603. };
  604. struct addrinfo *res, hint;
  605. if (p_getaddrinfo.p == NULL) {
  606. if ((p_getaddrinfo.p = DSO_global_lookup("getaddrinfo")) == NULL
  607. || (p_freeaddrinfo.p =
  608. DSO_global_lookup("freeaddrinfo")) == NULL)
  609. p_getaddrinfo.p = (void *)-1;
  610. }
  611. if (p_getaddrinfo.p == (void *)-1)
  612. break;
  613. /*
  614. * '::port' enforces IPv6 wildcard listener. Some OSes, e.g. Solaris,
  615. * default to IPv6 without any hint. Also note that commonly IPv6
  616. * wildchard socket can service IPv4 connections just as well...
  617. */
  618. memset(&hint, 0, sizeof(hint));
  619. hint.ai_flags = AI_PASSIVE;
  620. if (h) {
  621. if (strchr(h, ':')) {
  622. if (h[1] == '\0')
  623. h = NULL;
  624. # if OPENSSL_USE_IPV6
  625. hint.ai_family = AF_INET6;
  626. # else
  627. h = NULL;
  628. # endif
  629. } else if (h[0] == '*' && h[1] == '\0') {
  630. hint.ai_family = AF_INET;
  631. h = NULL;
  632. }
  633. }
  634. if ((*p_getaddrinfo.f) (h, p, &hint, &res))
  635. break;
  636. addrlen = res->ai_addrlen <= sizeof(server) ?
  637. res->ai_addrlen : sizeof(server);
  638. memcpy(&server, res->ai_addr, addrlen);
  639. (*p_freeaddrinfo.f) (res);
  640. goto again;
  641. } while (0);
  642. # endif
  643. if (!BIO_get_port(p, &port))
  644. goto err;
  645. memset((char *)&server, 0, sizeof(server));
  646. server.sa_in.sin_family = AF_INET;
  647. server.sa_in.sin_port = htons(port);
  648. addrlen = sizeof(server.sa_in);
  649. if (h == NULL || strcmp(h, "*") == 0)
  650. server.sa_in.sin_addr.s_addr = INADDR_ANY;
  651. else {
  652. if (!BIO_get_host_ip(h, &(ip[0])))
  653. goto err;
  654. l = (unsigned long)
  655. ((unsigned long)ip[0] << 24L) |
  656. ((unsigned long)ip[1] << 16L) |
  657. ((unsigned long)ip[2] << 8L) | ((unsigned long)ip[3]);
  658. server.sa_in.sin_addr.s_addr = htonl(l);
  659. }
  660. again:
  661. s = socket(server.sa.sa_family, SOCK_STREAM, SOCKET_PROTOCOL);
  662. if (s == INVALID_SOCKET) {
  663. SYSerr(SYS_F_SOCKET, get_last_socket_error());
  664. ERR_add_error_data(3, "port='", host, "'");
  665. BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_CREATE_SOCKET);
  666. goto err;
  667. }
  668. # ifdef SO_REUSEADDR
  669. if (bind_mode == BIO_BIND_REUSEADDR) {
  670. int i = 1;
  671. ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&i, sizeof(i));
  672. bind_mode = BIO_BIND_NORMAL;
  673. }
  674. # endif
  675. if (bind(s, &server.sa, addrlen) == -1) {
  676. # ifdef SO_REUSEADDR
  677. err_num = get_last_socket_error();
  678. if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
  679. # ifdef OPENSSL_SYS_WINDOWS
  680. /*
  681. * Some versions of Windows define EADDRINUSE to a dummy value.
  682. */
  683. (err_num == WSAEADDRINUSE))
  684. # else
  685. (err_num == EADDRINUSE))
  686. # endif
  687. {
  688. client = server;
  689. if (h == NULL || strcmp(h, "*") == 0) {
  690. # if OPENSSL_USE_IPV6
  691. if (client.sa.sa_family == AF_INET6) {
  692. memset(&client.sa_in6.sin6_addr, 0,
  693. sizeof(client.sa_in6.sin6_addr));
  694. client.sa_in6.sin6_addr.s6_addr[15] = 1;
  695. } else
  696. # endif
  697. if (client.sa.sa_family == AF_INET) {
  698. client.sa_in.sin_addr.s_addr = htonl(0x7F000001);
  699. } else
  700. goto err;
  701. }
  702. cs = socket(client.sa.sa_family, SOCK_STREAM, SOCKET_PROTOCOL);
  703. if (cs != INVALID_SOCKET) {
  704. int ii;
  705. ii = connect(cs, &client.sa, addrlen);
  706. closesocket(cs);
  707. if (ii == INVALID_SOCKET) {
  708. bind_mode = BIO_BIND_REUSEADDR;
  709. closesocket(s);
  710. goto again;
  711. }
  712. /* else error */
  713. }
  714. /* else error */
  715. }
  716. # endif
  717. SYSerr(SYS_F_BIND, err_num);
  718. ERR_add_error_data(3, "port='", host, "'");
  719. BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_BIND_SOCKET);
  720. goto err;
  721. }
  722. if (listen(s, MAX_LISTEN) == -1) {
  723. SYSerr(SYS_F_BIND, get_last_socket_error());
  724. ERR_add_error_data(3, "port='", host, "'");
  725. BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_LISTEN_SOCKET);
  726. goto err;
  727. }
  728. ret = 1;
  729. err:
  730. if (str != NULL)
  731. OPENSSL_free(str);
  732. if ((ret == 0) && (s != INVALID_SOCKET)) {
  733. closesocket(s);
  734. s = INVALID_SOCKET;
  735. }
  736. return (s);
  737. }
  738. int BIO_accept(int sock, char **addr)
  739. {
  740. int ret = INVALID_SOCKET;
  741. unsigned long l;
  742. unsigned short port;
  743. char *p;
  744. struct {
  745. /*
  746. * As for following union. Trouble is that there are platforms
  747. * that have socklen_t and there are platforms that don't, on
  748. * some platforms socklen_t is int and on some size_t. So what
  749. * one can do? One can cook #ifdef spaghetti, which is nothing
  750. * but masochistic. Or one can do union between int and size_t.
  751. * One naturally does it primarily for 64-bit platforms where
  752. * sizeof(int) != sizeof(size_t). But would it work? Note that
  753. * if size_t member is initialized to 0, then later int member
  754. * assignment naturally does the job on little-endian platforms
  755. * regardless accept's expectations! What about big-endians?
  756. * If accept expects int*, then it works, and if size_t*, then
  757. * length value would appear as unreasonably large. But this
  758. * won't prevent it from filling in the address structure. The
  759. * trouble of course would be if accept returns more data than
  760. * actual buffer can accomodate and overwrite stack... That's
  761. * where early OPENSSL_assert comes into picture. Besides, the
  762. * only 64-bit big-endian platform found so far that expects
  763. * size_t* is HP-UX, where stack grows towards higher address.
  764. * <appro>
  765. */
  766. union {
  767. size_t s;
  768. int i;
  769. } len;
  770. union {
  771. struct sockaddr sa;
  772. struct sockaddr_in sa_in;
  773. # if OPENSSL_USE_IPV6
  774. struct sockaddr_in6 sa_in6;
  775. # endif
  776. } from;
  777. } sa;
  778. sa.len.s = 0;
  779. sa.len.i = sizeof(sa.from);
  780. memset(&sa.from, 0, sizeof(sa.from));
  781. ret = accept(sock, &sa.from.sa, (void *)&sa.len);
  782. if (sizeof(sa.len.i) != sizeof(sa.len.s) && sa.len.i == 0) {
  783. OPENSSL_assert(sa.len.s <= sizeof(sa.from));
  784. sa.len.i = (int)sa.len.s;
  785. /* use sa.len.i from this point */
  786. }
  787. if (ret == INVALID_SOCKET) {
  788. if (BIO_sock_should_retry(ret))
  789. return -2;
  790. SYSerr(SYS_F_ACCEPT, get_last_socket_error());
  791. BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR);
  792. goto end;
  793. }
  794. if (addr == NULL)
  795. goto end;
  796. # ifdef EAI_FAMILY
  797. do {
  798. char h[NI_MAXHOST], s[NI_MAXSERV];
  799. size_t nl;
  800. static union {
  801. void *p;
  802. int (WSAAPI *f) (const struct sockaddr *, size_t /* socklen_t */ ,
  803. char *, size_t, char *, size_t, int);
  804. } p_getnameinfo = {
  805. NULL
  806. };
  807. /*
  808. * 2nd argument to getnameinfo is specified to be socklen_t.
  809. * Unfortunately there is a number of environments where socklen_t is
  810. * not defined. As it's passed by value, it's safe to pass it as
  811. * size_t... <appro>
  812. */
  813. if (p_getnameinfo.p == NULL) {
  814. if ((p_getnameinfo.p = DSO_global_lookup("getnameinfo")) == NULL)
  815. p_getnameinfo.p = (void *)-1;
  816. }
  817. if (p_getnameinfo.p == (void *)-1)
  818. break;
  819. if ((*p_getnameinfo.f) (&sa.from.sa, sa.len.i, h, sizeof(h), s,
  820. sizeof(s), NI_NUMERICHOST | NI_NUMERICSERV))
  821. break;
  822. nl = strlen(h) + strlen(s) + 2;
  823. p = *addr;
  824. if (p) {
  825. *p = '\0';
  826. p = OPENSSL_realloc(p, nl);
  827. } else {
  828. p = OPENSSL_malloc(nl);
  829. }
  830. if (p == NULL) {
  831. BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
  832. goto end;
  833. }
  834. *addr = p;
  835. BIO_snprintf(*addr, nl, "%s:%s", h, s);
  836. goto end;
  837. } while (0);
  838. # endif
  839. if (sa.from.sa.sa_family != AF_INET)
  840. goto end;
  841. l = ntohl(sa.from.sa_in.sin_addr.s_addr);
  842. port = ntohs(sa.from.sa_in.sin_port);
  843. if (*addr == NULL) {
  844. if ((p = OPENSSL_malloc(24)) == NULL) {
  845. BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
  846. goto end;
  847. }
  848. *addr = p;
  849. }
  850. BIO_snprintf(*addr, 24, "%d.%d.%d.%d:%d",
  851. (unsigned char)(l >> 24L) & 0xff,
  852. (unsigned char)(l >> 16L) & 0xff,
  853. (unsigned char)(l >> 8L) & 0xff,
  854. (unsigned char)(l) & 0xff, port);
  855. end:
  856. return (ret);
  857. }
  858. int BIO_set_tcp_ndelay(int s, int on)
  859. {
  860. int ret = 0;
  861. # if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP))
  862. int opt;
  863. # ifdef SOL_TCP
  864. opt = SOL_TCP;
  865. # else
  866. # ifdef IPPROTO_TCP
  867. opt = IPPROTO_TCP;
  868. # endif
  869. # endif
  870. ret = setsockopt(s, opt, TCP_NODELAY, (char *)&on, sizeof(on));
  871. # endif
  872. return (ret == 0);
  873. }
  874. int BIO_socket_nbio(int s, int mode)
  875. {
  876. int ret = -1;
  877. int l;
  878. l = mode;
  879. # ifdef FIONBIO
  880. ret = BIO_socket_ioctl(s, FIONBIO, &l);
  881. # endif
  882. return (ret == 0);
  883. }
  884. #endif