b_sock.c 28 KB

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