s_socket.c 16 KB

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