s_socket.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. /*
  2. * Copyright 1995-2025 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. /* socket-related functions used by s_client and s_server */
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <errno.h>
  14. #include <signal.h>
  15. #include <openssl/opensslconf.h>
  16. /*
  17. * With IPv6, it looks like Digital has mixed up the proper order of
  18. * recursive header file inclusion, resulting in the compiler complaining
  19. * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
  20. * needed to have fileno() declared correctly... So let's define u_int
  21. */
  22. #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
  23. # define __U_INT
  24. typedef unsigned int u_int;
  25. #endif
  26. #ifdef _WIN32
  27. # include <process.h>
  28. /* MSVC renamed some POSIX functions to have an underscore prefix. */
  29. # ifdef _MSC_VER
  30. # define getpid _getpid
  31. # endif
  32. #endif
  33. #ifndef OPENSSL_NO_SOCK
  34. # include "apps.h"
  35. # include "s_apps.h"
  36. # include "internal/sockets.h"
  37. # if defined(__TANDEM)
  38. # if defined(OPENSSL_TANDEM_FLOSS)
  39. # include <floss.h(floss_read)>
  40. # endif
  41. # endif
  42. # include <openssl/bio.h>
  43. # include <openssl/err.h>
  44. /* Keep track of our peer's address for the cookie callback */
  45. BIO_ADDR *ourpeer = NULL;
  46. /*
  47. * init_client - helper routine to set up socket communication
  48. * @sock: pointer to storage of resulting socket.
  49. * @host: the hostname or path (for AF_UNIX) to connect to.
  50. * @port: the port to connect to (ignored for AF_UNIX).
  51. * @bindhost: source host or path (for AF_UNIX).
  52. * @bindport: source port (ignored for AF_UNIX).
  53. * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
  54. * AF_UNSPEC
  55. * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
  56. * @protocol: socket protocol, e.g. IPPROTO_TCP or IPPROTO_UDP (or 0 for any)
  57. * @tfo: flag to enable TCP Fast Open
  58. * @doconn: whether we should call BIO_connect() on the socket
  59. * @ba_ret: BIO_ADDR for the remote peer, to be freed by caller
  60. *
  61. * This will create a socket and use it to connect to a host:port, or if
  62. * family == AF_UNIX, to the path found in host.
  63. *
  64. * If the host has more than one address, it will try them one by one until
  65. * a successful connection is established. The resulting socket will be
  66. * found in *sock on success, it will be given INVALID_SOCKET otherwise.
  67. *
  68. * Returns 1 on success, 0 on failure.
  69. */
  70. int init_client(int *sock, const char *host, const char *port,
  71. const char *bindhost, const char *bindport,
  72. int family, int type, int protocol, int tfo, int doconn,
  73. BIO_ADDR **ba_ret)
  74. {
  75. BIO_ADDRINFO *res = NULL;
  76. BIO_ADDRINFO *bindaddr = NULL;
  77. const BIO_ADDRINFO *ai = NULL;
  78. const BIO_ADDRINFO *bi = NULL;
  79. int found = 0;
  80. int ret;
  81. int options = 0;
  82. if (BIO_sock_init() != 1)
  83. return 0;
  84. ret = BIO_lookup_ex(host, port, BIO_LOOKUP_CLIENT, family, type, protocol,
  85. &res);
  86. if (ret == 0) {
  87. ERR_print_errors(bio_err);
  88. return 0;
  89. }
  90. if (bindhost != NULL || bindport != NULL) {
  91. ret = BIO_lookup_ex(bindhost, bindport, BIO_LOOKUP_CLIENT,
  92. family, type, protocol, &bindaddr);
  93. if (ret == 0) {
  94. ERR_print_errors (bio_err);
  95. goto out;
  96. }
  97. }
  98. ret = 0;
  99. for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
  100. /* Admittedly, these checks are quite paranoid, we should not get
  101. * anything in the BIO_ADDRINFO chain that we haven't
  102. * asked for. */
  103. OPENSSL_assert((family == AF_UNSPEC
  104. || family == BIO_ADDRINFO_family(ai))
  105. && (type == 0 || type == BIO_ADDRINFO_socktype(ai))
  106. && (protocol == 0
  107. || protocol == BIO_ADDRINFO_protocol(ai)));
  108. if (bindaddr != NULL) {
  109. for (bi = bindaddr; bi != NULL; bi = BIO_ADDRINFO_next(bi)) {
  110. if (BIO_ADDRINFO_family(bi) == BIO_ADDRINFO_family(ai))
  111. break;
  112. }
  113. if (bi == NULL)
  114. continue;
  115. ++found;
  116. }
  117. *sock = BIO_socket(BIO_ADDRINFO_family(ai), BIO_ADDRINFO_socktype(ai),
  118. BIO_ADDRINFO_protocol(ai), 0);
  119. if (*sock == INVALID_SOCKET) {
  120. /* Maybe the kernel doesn't support the socket family, even if
  121. * BIO_lookup() added it in the returned result...
  122. */
  123. continue;
  124. }
  125. if (bi != NULL) {
  126. if (!BIO_bind(*sock, BIO_ADDRINFO_address(bi),
  127. BIO_SOCK_REUSEADDR)) {
  128. BIO_closesocket(*sock);
  129. *sock = INVALID_SOCKET;
  130. break;
  131. }
  132. }
  133. #ifndef OPENSSL_NO_SCTP
  134. if (protocol == IPPROTO_SCTP) {
  135. /*
  136. * For SCTP we have to set various options on the socket prior to
  137. * connecting. This is done automatically by BIO_new_dgram_sctp().
  138. * We don't actually need the created BIO though so we free it again
  139. * immediately.
  140. */
  141. BIO *tmpbio = BIO_new_dgram_sctp(*sock, BIO_NOCLOSE);
  142. if (tmpbio == NULL) {
  143. ERR_print_errors(bio_err);
  144. return 0;
  145. }
  146. BIO_free(tmpbio);
  147. }
  148. #endif
  149. if (BIO_ADDRINFO_protocol(ai) == IPPROTO_TCP) {
  150. options |= BIO_SOCK_NODELAY;
  151. if (tfo)
  152. options |= BIO_SOCK_TFO;
  153. }
  154. if (doconn && !BIO_connect(*sock, BIO_ADDRINFO_address(ai), options)) {
  155. BIO_closesocket(*sock);
  156. *sock = INVALID_SOCKET;
  157. continue;
  158. }
  159. /* Save the address */
  160. if (tfo || !doconn)
  161. *ba_ret = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));
  162. /* Success, don't try any more addresses */
  163. break;
  164. }
  165. if (*sock == INVALID_SOCKET) {
  166. if (bindaddr != NULL && !found) {
  167. BIO_printf(bio_err, "Can't bind %saddress for %s%s%s\n",
  168. #ifdef AF_INET6
  169. BIO_ADDRINFO_family(res) == AF_INET6 ? "IPv6 " :
  170. #endif
  171. BIO_ADDRINFO_family(res) == AF_INET ? "IPv4 " :
  172. BIO_ADDRINFO_family(res) == AF_UNIX ? "unix " : "",
  173. bindhost != NULL ? bindhost : "",
  174. bindport != NULL ? ":" : "",
  175. bindport != NULL ? bindport : "");
  176. ERR_clear_error();
  177. ret = 0;
  178. }
  179. ERR_print_errors(bio_err);
  180. } else {
  181. char *hostname = NULL;
  182. hostname = BIO_ADDR_hostname_string(BIO_ADDRINFO_address(ai), 1);
  183. if (hostname != NULL) {
  184. BIO_printf(bio_err, "Connecting to %s\n", hostname);
  185. OPENSSL_free(hostname);
  186. }
  187. /* Remove any stale errors from previous connection attempts */
  188. ERR_clear_error();
  189. ret = 1;
  190. }
  191. out:
  192. if (bindaddr != NULL) {
  193. BIO_ADDRINFO_free (bindaddr);
  194. }
  195. BIO_ADDRINFO_free(res);
  196. return ret;
  197. }
  198. void get_sock_info_address(int asock, char **hostname, char **service)
  199. {
  200. union BIO_sock_info_u info;
  201. if (hostname != NULL)
  202. *hostname = NULL;
  203. if (service != NULL)
  204. *service = NULL;
  205. if ((info.addr = BIO_ADDR_new()) != NULL
  206. && BIO_sock_info(asock, BIO_SOCK_INFO_ADDRESS, &info)) {
  207. if (hostname != NULL)
  208. *hostname = BIO_ADDR_hostname_string(info.addr, 1);
  209. if (service != NULL)
  210. *service = BIO_ADDR_service_string(info.addr, 1);
  211. }
  212. BIO_ADDR_free(info.addr);
  213. }
  214. int report_server_accept(BIO *out, int asock, int with_address, int with_pid)
  215. {
  216. int success = 1;
  217. if (BIO_printf(out, "ACCEPT") <= 0)
  218. return 0;
  219. if (with_address) {
  220. char *hostname, *service;
  221. get_sock_info_address(asock, &hostname, &service);
  222. success = hostname != NULL && service != NULL;
  223. if (success)
  224. success = BIO_printf(out,
  225. strchr(hostname, ':') == NULL
  226. ? /* IPv4 */ " %s:%s"
  227. : /* IPv6 */ " [%s]:%s",
  228. hostname, service) > 0;
  229. else
  230. (void)BIO_printf(out, "unknown:error\n");
  231. OPENSSL_free(hostname);
  232. OPENSSL_free(service);
  233. }
  234. if (with_pid)
  235. success *= BIO_printf(out, " PID=%d", getpid()) > 0;
  236. success *= BIO_printf(out, "\n") > 0;
  237. (void)BIO_flush(out);
  238. return success;
  239. }
  240. /*
  241. * do_server - helper routine to perform a server operation
  242. * @accept_sock: pointer to storage of resulting socket.
  243. * @host: the hostname or path (for AF_UNIX) to connect to.
  244. * @port: the port to connect to (ignored for AF_UNIX).
  245. * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
  246. * AF_UNSPEC
  247. * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
  248. * @cb: pointer to a function that receives the accepted socket and
  249. * should perform the communication with the connecting client.
  250. * @context: pointer to memory that's passed verbatim to the cb function.
  251. * @naccept: number of times an incoming connect should be accepted. If -1,
  252. * unlimited number.
  253. *
  254. * This will create a socket and use it to listen to a host:port, or if
  255. * family == AF_UNIX, to the path found in host, then start accepting
  256. * incoming connections and run cb on the resulting socket.
  257. *
  258. * 0 on failure, something other on success.
  259. */
  260. int do_server(int *accept_sock, const char *host, const char *port,
  261. int family, int type, int protocol, do_server_cb cb,
  262. unsigned char *context, int naccept, BIO *bio_s_out,
  263. int tfo)
  264. {
  265. int asock = 0;
  266. int sock;
  267. int i;
  268. BIO_ADDRINFO *res = NULL;
  269. const BIO_ADDRINFO *next;
  270. int sock_family, sock_type, sock_protocol, sock_port;
  271. const BIO_ADDR *sock_address;
  272. int sock_family_fallback = AF_UNSPEC;
  273. const BIO_ADDR *sock_address_fallback = NULL;
  274. int sock_options = BIO_SOCK_REUSEADDR;
  275. int ret = 0;
  276. if (BIO_sock_init() != 1)
  277. return 0;
  278. if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol,
  279. &res)) {
  280. ERR_print_errors(bio_err);
  281. return 0;
  282. }
  283. /* Admittedly, these checks are quite paranoid, we should not get
  284. * anything in the BIO_ADDRINFO chain that we haven't asked for */
  285. OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res))
  286. && (type == 0 || type == BIO_ADDRINFO_socktype(res))
  287. && (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res)));
  288. sock_family = BIO_ADDRINFO_family(res);
  289. sock_type = BIO_ADDRINFO_socktype(res);
  290. sock_protocol = BIO_ADDRINFO_protocol(res);
  291. sock_address = BIO_ADDRINFO_address(res);
  292. next = BIO_ADDRINFO_next(res);
  293. if (tfo && sock_type == SOCK_STREAM)
  294. sock_options |= BIO_SOCK_TFO;
  295. #ifdef AF_INET6
  296. if (sock_family == AF_INET6)
  297. sock_options |= BIO_SOCK_V6_ONLY;
  298. if (next != NULL
  299. && BIO_ADDRINFO_socktype(next) == sock_type
  300. && BIO_ADDRINFO_protocol(next) == sock_protocol) {
  301. if (sock_family == AF_INET
  302. && BIO_ADDRINFO_family(next) == AF_INET6) {
  303. /* In case AF_INET6 is returned but not supported by the
  304. * kernel, retry with the first detected address family */
  305. sock_family_fallback = sock_family;
  306. sock_address_fallback = sock_address;
  307. sock_family = AF_INET6;
  308. sock_address = BIO_ADDRINFO_address(next);
  309. } else if (sock_family == AF_INET6
  310. && BIO_ADDRINFO_family(next) == AF_INET) {
  311. sock_options &= ~BIO_SOCK_V6_ONLY;
  312. }
  313. }
  314. #endif
  315. asock = BIO_socket(sock_family, sock_type, sock_protocol, 0);
  316. if (asock == INVALID_SOCKET && sock_family_fallback != AF_UNSPEC) {
  317. asock = BIO_socket(sock_family_fallback, sock_type, sock_protocol, 0);
  318. sock_address = sock_address_fallback;
  319. }
  320. if (asock == INVALID_SOCKET
  321. || !BIO_listen(asock, sock_address, sock_options)) {
  322. BIO_ADDRINFO_free(res);
  323. ERR_print_errors(bio_err);
  324. if (asock != INVALID_SOCKET)
  325. BIO_closesocket(asock);
  326. goto end;
  327. }
  328. #ifndef OPENSSL_NO_SCTP
  329. if (protocol == IPPROTO_SCTP) {
  330. /*
  331. * For SCTP we have to set various options on the socket prior to
  332. * accepting. This is done automatically by BIO_new_dgram_sctp().
  333. * We don't actually need the created BIO though so we free it again
  334. * immediately.
  335. */
  336. BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE);
  337. if (tmpbio == NULL) {
  338. BIO_closesocket(asock);
  339. ERR_print_errors(bio_err);
  340. goto end;
  341. }
  342. BIO_free(tmpbio);
  343. }
  344. #endif
  345. sock_port = BIO_ADDR_rawport(sock_address);
  346. BIO_ADDRINFO_free(res);
  347. res = NULL;
  348. if (!report_server_accept(bio_s_out, asock, sock_port == 0, 0)) {
  349. BIO_closesocket(asock);
  350. ERR_print_errors(bio_err);
  351. goto end;
  352. }
  353. if (accept_sock != NULL)
  354. *accept_sock = asock;
  355. for (;;) {
  356. char sink[64];
  357. struct timeval timeout;
  358. fd_set readfds;
  359. if (type == SOCK_STREAM) {
  360. BIO_ADDR_free(ourpeer);
  361. ourpeer = BIO_ADDR_new();
  362. if (ourpeer == NULL) {
  363. BIO_closesocket(asock);
  364. ERR_print_errors(bio_err);
  365. goto end;
  366. }
  367. do {
  368. sock = BIO_accept_ex(asock, ourpeer, 0);
  369. } while (sock < 0 && BIO_sock_should_retry(sock));
  370. if (sock < 0) {
  371. ERR_print_errors(bio_err);
  372. BIO_closesocket(asock);
  373. break;
  374. }
  375. if (naccept != -1)
  376. naccept--;
  377. if (naccept == 0)
  378. BIO_closesocket(asock);
  379. BIO_set_tcp_ndelay(sock, 1);
  380. i = (*cb)(sock, type, protocol, context);
  381. /*
  382. * If we ended with an alert being sent, but still with data in the
  383. * network buffer to be read, then calling BIO_closesocket() will
  384. * result in a TCP-RST being sent. On some platforms (notably
  385. * Windows) then this will result in the peer immediately abandoning
  386. * the connection including any buffered alert data before it has
  387. * had a chance to be read. Shutting down the sending side first,
  388. * and then closing the socket sends TCP-FIN first followed by
  389. * TCP-RST. This seems to allow the peer to read the alert data.
  390. */
  391. shutdown(sock, 1); /* SHUT_WR */
  392. /*
  393. * We just said we have nothing else to say, but it doesn't mean
  394. * that the other side has nothing. It's even recommended to
  395. * consume incoming data. [In testing context this ensures that
  396. * alerts are passed on...]
  397. */
  398. timeout.tv_sec = 0;
  399. timeout.tv_usec = 500000; /* some extreme round-trip */
  400. do {
  401. FD_ZERO(&readfds);
  402. openssl_fdset(sock, &readfds);
  403. } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
  404. && readsocket(sock, sink, sizeof(sink)) > 0);
  405. BIO_closesocket(sock);
  406. } else {
  407. if (naccept != -1)
  408. naccept--;
  409. i = (*cb)(asock, type, protocol, context);
  410. }
  411. if (i < 0 || naccept == 0) {
  412. BIO_closesocket(asock);
  413. ret = i;
  414. break;
  415. }
  416. }
  417. end:
  418. # ifdef AF_UNIX
  419. if (family == AF_UNIX)
  420. unlink(host);
  421. # endif
  422. BIO_ADDR_free(ourpeer);
  423. ourpeer = NULL;
  424. return ret;
  425. }
  426. void do_ssl_shutdown(SSL *ssl)
  427. {
  428. int ret;
  429. do {
  430. /* We only do unidirectional shutdown */
  431. ret = SSL_shutdown(ssl);
  432. if (ret < 0) {
  433. switch (SSL_get_error(ssl, ret)) {
  434. case SSL_ERROR_WANT_READ:
  435. case SSL_ERROR_WANT_WRITE:
  436. case SSL_ERROR_WANT_ASYNC:
  437. case SSL_ERROR_WANT_ASYNC_JOB:
  438. /* We just do busy waiting. Nothing clever */
  439. continue;
  440. }
  441. ret = 0;
  442. }
  443. } while (ret < 0);
  444. }
  445. #endif /* OPENSSL_NO_SOCK */