s_socket.c 16 KB

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