s_socket.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. /*
  2. * Copyright 1995-2026 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. BIO_closesocket(*sock);
  139. *sock = INVALID_SOCKET;
  140. continue;
  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. : "",
  177. bindhost != NULL ? bindhost : "",
  178. bindport != NULL ? ":" : "",
  179. bindport != NULL ? bindport : "");
  180. ERR_clear_error();
  181. ret = 0;
  182. }
  183. ERR_print_errors(bio_err);
  184. } else {
  185. char *hostname = NULL;
  186. hostname = BIO_ADDR_hostname_string(BIO_ADDRINFO_address(ai), 1);
  187. if (hostname != NULL) {
  188. BIO_printf(bio_err, "Connecting to %s\n", hostname);
  189. OPENSSL_free(hostname);
  190. }
  191. /* Remove any stale errors from previous connection attempts */
  192. ERR_clear_error();
  193. ret = 1;
  194. }
  195. out:
  196. if (bindaddr != NULL) {
  197. BIO_ADDRINFO_free(bindaddr);
  198. }
  199. BIO_ADDRINFO_free(res);
  200. return ret;
  201. }
  202. void get_sock_info_address(int asock, char **hostname, char **service)
  203. {
  204. union BIO_sock_info_u info;
  205. if (hostname != NULL)
  206. *hostname = NULL;
  207. if (service != NULL)
  208. *service = NULL;
  209. if ((info.addr = BIO_ADDR_new()) != NULL
  210. && BIO_sock_info(asock, BIO_SOCK_INFO_ADDRESS, &info)) {
  211. if (hostname != NULL)
  212. *hostname = BIO_ADDR_hostname_string(info.addr, 1);
  213. if (service != NULL)
  214. *service = BIO_ADDR_service_string(info.addr, 1);
  215. }
  216. BIO_ADDR_free(info.addr);
  217. }
  218. int report_server_accept(BIO *out, int asock, int with_address, int with_pid)
  219. {
  220. int success = 1;
  221. if (BIO_printf(out, "ACCEPT") <= 0)
  222. return 0;
  223. if (with_address) {
  224. char *hostname, *service;
  225. get_sock_info_address(asock, &hostname, &service);
  226. success = hostname != NULL && service != NULL;
  227. if (success)
  228. success = BIO_printf(out,
  229. strchr(hostname, ':') == NULL
  230. ? /* IPv4 */ " %s:%s"
  231. : /* IPv6 */ " [%s]:%s",
  232. hostname, service)
  233. > 0;
  234. else
  235. (void)BIO_printf(out, "unknown:error\n");
  236. OPENSSL_free(hostname);
  237. OPENSSL_free(service);
  238. }
  239. if (with_pid)
  240. success *= BIO_printf(out, " PID=%d", getpid()) > 0;
  241. success *= BIO_printf(out, "\n") > 0;
  242. (void)BIO_flush(out);
  243. return success;
  244. }
  245. /*
  246. * do_server - helper routine to perform a server operation
  247. * @accept_sock: pointer to storage of resulting socket.
  248. * @host: the hostname or path (for AF_UNIX) to connect to.
  249. * @port: the port to connect to (ignored for AF_UNIX).
  250. * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
  251. * AF_UNSPEC
  252. * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
  253. * @cb: pointer to a function that receives the accepted socket and
  254. * should perform the communication with the connecting client.
  255. * @context: pointer to memory that's passed verbatim to the cb function.
  256. * @naccept: number of times an incoming connect should be accepted. If -1,
  257. * unlimited number.
  258. *
  259. * This will create a socket and use it to listen to a host:port, or if
  260. * family == AF_UNIX, to the path found in host, then start accepting
  261. * incoming connections and run cb on the resulting socket.
  262. *
  263. * 0 on failure, something other on success.
  264. */
  265. int do_server(int *accept_sock, const char *host, const char *port,
  266. int family, int type, int protocol, do_server_cb cb,
  267. unsigned char *context, int naccept, BIO *bio_s_out,
  268. int tfo)
  269. {
  270. int asock = 0;
  271. int sock;
  272. int i;
  273. BIO_ADDRINFO *res = NULL;
  274. const BIO_ADDRINFO *next;
  275. int sock_family, sock_type, sock_protocol, sock_port;
  276. const BIO_ADDR *sock_address;
  277. int sock_family_fallback = AF_UNSPEC;
  278. const BIO_ADDR *sock_address_fallback = NULL;
  279. int sock_options = BIO_SOCK_REUSEADDR;
  280. int ret = 0;
  281. if (BIO_sock_init() != 1)
  282. return 0;
  283. if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol,
  284. &res)) {
  285. ERR_print_errors(bio_err);
  286. return 0;
  287. }
  288. /* Admittedly, these checks are quite paranoid, we should not get
  289. * anything in the BIO_ADDRINFO chain that we haven't asked for */
  290. OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res))
  291. && (type == 0 || type == BIO_ADDRINFO_socktype(res))
  292. && (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res)));
  293. sock_family = BIO_ADDRINFO_family(res);
  294. sock_type = BIO_ADDRINFO_socktype(res);
  295. sock_protocol = BIO_ADDRINFO_protocol(res);
  296. sock_address = BIO_ADDRINFO_address(res);
  297. next = BIO_ADDRINFO_next(res);
  298. if (tfo && sock_type == SOCK_STREAM)
  299. sock_options |= BIO_SOCK_TFO;
  300. #ifdef AF_INET6
  301. if (sock_family == AF_INET6)
  302. sock_options |= BIO_SOCK_V6_ONLY;
  303. if (next != NULL
  304. && BIO_ADDRINFO_socktype(next) == sock_type
  305. && BIO_ADDRINFO_protocol(next) == sock_protocol) {
  306. if (sock_family == AF_INET
  307. && BIO_ADDRINFO_family(next) == AF_INET6) {
  308. /* In case AF_INET6 is returned but not supported by the
  309. * kernel, retry with the first detected address family */
  310. sock_family_fallback = sock_family;
  311. sock_address_fallback = sock_address;
  312. sock_family = AF_INET6;
  313. sock_address = BIO_ADDRINFO_address(next);
  314. } else if (sock_family == AF_INET6
  315. && BIO_ADDRINFO_family(next) == AF_INET) {
  316. sock_options &= ~BIO_SOCK_V6_ONLY;
  317. }
  318. }
  319. #endif
  320. asock = BIO_socket(sock_family, sock_type, sock_protocol, 0);
  321. if (asock == INVALID_SOCKET && sock_family_fallback != AF_UNSPEC) {
  322. asock = BIO_socket(sock_family_fallback, sock_type, sock_protocol, 0);
  323. sock_address = sock_address_fallback;
  324. }
  325. if (asock == INVALID_SOCKET
  326. || !BIO_listen(asock, sock_address, sock_options)) {
  327. BIO_ADDRINFO_free(res);
  328. ERR_print_errors(bio_err);
  329. if (asock != INVALID_SOCKET)
  330. BIO_closesocket(asock);
  331. goto end;
  332. }
  333. #ifndef OPENSSL_NO_SCTP
  334. if (protocol == IPPROTO_SCTP) {
  335. /*
  336. * For SCTP we have to set various options on the socket prior to
  337. * accepting. This is done automatically by BIO_new_dgram_sctp().
  338. * We don't actually need the created BIO though so we free it again
  339. * immediately.
  340. */
  341. BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE);
  342. if (tmpbio == NULL) {
  343. BIO_ADDRINFO_free(res);
  344. BIO_closesocket(asock);
  345. ERR_print_errors(bio_err);
  346. goto end;
  347. }
  348. BIO_free(tmpbio);
  349. }
  350. #endif
  351. sock_port = BIO_ADDR_rawport(sock_address);
  352. BIO_ADDRINFO_free(res);
  353. res = NULL;
  354. if (!report_server_accept(bio_s_out, asock, sock_port == 0, 0)) {
  355. BIO_closesocket(asock);
  356. ERR_print_errors(bio_err);
  357. goto end;
  358. }
  359. if (accept_sock != NULL)
  360. *accept_sock = asock;
  361. for (;;) {
  362. char sink[64];
  363. struct timeval timeout;
  364. fd_set readfds;
  365. if (type == SOCK_STREAM) {
  366. BIO_ADDR_free(ourpeer);
  367. ourpeer = BIO_ADDR_new();
  368. if (ourpeer == NULL) {
  369. BIO_closesocket(asock);
  370. ERR_print_errors(bio_err);
  371. goto end;
  372. }
  373. do {
  374. sock = BIO_accept_ex(asock, ourpeer, 0);
  375. } while (sock < 0 && BIO_sock_should_retry(sock));
  376. if (sock < 0) {
  377. ERR_print_errors(bio_err);
  378. BIO_closesocket(asock);
  379. break;
  380. }
  381. if (naccept != -1)
  382. naccept--;
  383. BIO_set_tcp_ndelay(sock, 1);
  384. i = (*cb)(sock, type, protocol, context);
  385. /*
  386. * If we ended with an alert being sent, but still with data in the
  387. * network buffer to be read, then calling BIO_closesocket() will
  388. * result in a TCP-RST being sent. On some platforms (notably
  389. * Windows) then this will result in the peer immediately abandoning
  390. * the connection including any buffered alert data before it has
  391. * had a chance to be read. Shutting down the sending side first,
  392. * and then closing the socket sends TCP-FIN first followed by
  393. * TCP-RST. This seems to allow the peer to read the alert data.
  394. */
  395. shutdown(sock, 1); /* SHUT_WR */
  396. /*
  397. * We just said we have nothing else to say, but it doesn't mean
  398. * that the other side has nothing. It's even recommended to
  399. * consume incoming data. [In testing context this ensures that
  400. * alerts are passed on...]
  401. */
  402. timeout.tv_sec = 0;
  403. timeout.tv_usec = 500000; /* some extreme round-trip */
  404. do {
  405. FD_ZERO(&readfds);
  406. openssl_fdset(sock, &readfds);
  407. } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
  408. && readsocket(sock, sink, sizeof(sink)) > 0);
  409. BIO_closesocket(sock);
  410. } else {
  411. if (naccept != -1)
  412. naccept--;
  413. i = (*cb)(asock, type, protocol, context);
  414. }
  415. if (i < 0 || naccept == 0) {
  416. BIO_closesocket(asock);
  417. asock = INVALID_SOCKET;
  418. ret = i;
  419. break;
  420. }
  421. }
  422. end:
  423. #ifdef AF_UNIX
  424. if (family == AF_UNIX)
  425. unlink(host);
  426. #endif
  427. BIO_ADDR_free(ourpeer);
  428. ourpeer = NULL;
  429. return ret;
  430. }
  431. void do_ssl_shutdown(SSL *ssl)
  432. {
  433. int ret;
  434. do {
  435. /* We only do unidirectional shutdown */
  436. ret = SSL_shutdown(ssl);
  437. if (ret < 0) {
  438. switch (SSL_get_error(ssl, ret)) {
  439. case SSL_ERROR_WANT_READ:
  440. case SSL_ERROR_WANT_WRITE:
  441. case SSL_ERROR_WANT_ASYNC:
  442. case SSL_ERROR_WANT_ASYNC_JOB:
  443. /* We just do busy waiting. Nothing clever */
  444. continue;
  445. }
  446. ret = 0;
  447. }
  448. } while (ret < 0);
  449. }
  450. #endif /* OPENSSL_NO_SOCK */