b_sock.c 29 KB

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