s_socket.c 16 KB

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