s_socket.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. # 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 (tfo && ba_ret != NULL)
  83. *ba_ret = NULL;
  84. if (BIO_sock_init() != 1)
  85. return 0;
  86. ret = BIO_lookup_ex(host, port, BIO_LOOKUP_CLIENT, family, type, protocol,
  87. &res);
  88. if (ret == 0) {
  89. ERR_print_errors(bio_err);
  90. return 0;
  91. }
  92. if (bindhost != NULL || bindport != NULL) {
  93. ret = BIO_lookup_ex(bindhost, bindport, BIO_LOOKUP_CLIENT,
  94. family, type, protocol, &bindaddr);
  95. if (ret == 0) {
  96. ERR_print_errors (bio_err);
  97. goto out;
  98. }
  99. }
  100. ret = 0;
  101. for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
  102. /* Admittedly, these checks are quite paranoid, we should not get
  103. * anything in the BIO_ADDRINFO chain that we haven't
  104. * asked for. */
  105. OPENSSL_assert((family == AF_UNSPEC
  106. || family == BIO_ADDRINFO_family(ai))
  107. && (type == 0 || type == BIO_ADDRINFO_socktype(ai))
  108. && (protocol == 0
  109. || protocol == BIO_ADDRINFO_protocol(ai)));
  110. if (bindaddr != NULL) {
  111. for (bi = bindaddr; bi != NULL; bi = BIO_ADDRINFO_next(bi)) {
  112. if (BIO_ADDRINFO_family(bi) == BIO_ADDRINFO_family(ai))
  113. break;
  114. }
  115. if (bi == NULL)
  116. continue;
  117. ++found;
  118. }
  119. *sock = BIO_socket(BIO_ADDRINFO_family(ai), BIO_ADDRINFO_socktype(ai),
  120. BIO_ADDRINFO_protocol(ai), 0);
  121. if (*sock == INVALID_SOCKET) {
  122. /* Maybe the kernel doesn't support the socket family, even if
  123. * BIO_lookup() added it in the returned result...
  124. */
  125. continue;
  126. }
  127. if (bi != NULL) {
  128. if (!BIO_bind(*sock, BIO_ADDRINFO_address(bi),
  129. BIO_SOCK_REUSEADDR)) {
  130. BIO_closesocket(*sock);
  131. *sock = INVALID_SOCKET;
  132. break;
  133. }
  134. }
  135. #ifndef OPENSSL_NO_SCTP
  136. if (protocol == IPPROTO_SCTP) {
  137. /*
  138. * For SCTP we have to set various options on the socket prior to
  139. * connecting. This is done automatically by BIO_new_dgram_sctp().
  140. * We don't actually need the created BIO though so we free it again
  141. * immediately.
  142. */
  143. BIO *tmpbio = BIO_new_dgram_sctp(*sock, BIO_NOCLOSE);
  144. if (tmpbio == NULL) {
  145. ERR_print_errors(bio_err);
  146. return 0;
  147. }
  148. BIO_free(tmpbio);
  149. }
  150. #endif
  151. if (BIO_ADDRINFO_protocol(ai) == IPPROTO_TCP) {
  152. options |= BIO_SOCK_NODELAY;
  153. if (tfo)
  154. options |= BIO_SOCK_TFO;
  155. }
  156. if (doconn && !BIO_connect(*sock, BIO_ADDRINFO_address(ai), options)) {
  157. BIO_closesocket(*sock);
  158. *sock = INVALID_SOCKET;
  159. continue;
  160. }
  161. /* Save the address */
  162. if (tfo || !doconn)
  163. *ba_ret = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));
  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. BIO_set_tcp_ndelay(sock, 1);
  378. i = (*cb)(sock, type, protocol, context);
  379. /*
  380. * If we ended with an alert being sent, but still with data in the
  381. * network buffer to be read, then calling BIO_closesocket() will
  382. * result in a TCP-RST being sent. On some platforms (notably
  383. * Windows) then this will result in the peer immediately abandoning
  384. * the connection including any buffered alert data before it has
  385. * had a chance to be read. Shutting down the sending side first,
  386. * and then closing the socket sends TCP-FIN first followed by
  387. * TCP-RST. This seems to allow the peer to read the alert data.
  388. */
  389. shutdown(sock, 1); /* SHUT_WR */
  390. /*
  391. * We just said we have nothing else to say, but it doesn't mean
  392. * that the other side has nothing. It's even recommended to
  393. * consume incoming data. [In testing context this ensures that
  394. * alerts are passed on...]
  395. */
  396. timeout.tv_sec = 0;
  397. timeout.tv_usec = 500000; /* some extreme round-trip */
  398. do {
  399. FD_ZERO(&readfds);
  400. openssl_fdset(sock, &readfds);
  401. } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
  402. && readsocket(sock, sink, sizeof(sink)) > 0);
  403. BIO_closesocket(sock);
  404. } else {
  405. i = (*cb)(asock, type, protocol, context);
  406. }
  407. if (naccept != -1)
  408. naccept--;
  409. if (i < 0 || naccept == 0) {
  410. BIO_closesocket(asock);
  411. ret = i;
  412. break;
  413. }
  414. }
  415. end:
  416. # ifdef AF_UNIX
  417. if (family == AF_UNIX)
  418. unlink(host);
  419. # endif
  420. BIO_ADDR_free(ourpeer);
  421. ourpeer = NULL;
  422. return ret;
  423. }
  424. void do_ssl_shutdown(SSL *ssl)
  425. {
  426. int ret;
  427. do {
  428. /* We only do unidirectional shutdown */
  429. ret = SSL_shutdown(ssl);
  430. if (ret < 0) {
  431. switch (SSL_get_error(ssl, ret)) {
  432. case SSL_ERROR_WANT_READ:
  433. case SSL_ERROR_WANT_WRITE:
  434. case SSL_ERROR_WANT_ASYNC:
  435. case SSL_ERROR_WANT_ASYNC_JOB:
  436. /* We just do busy waiting. Nothing clever */
  437. continue;
  438. }
  439. ret = 0;
  440. }
  441. } while (ret < 0);
  442. }
  443. #endif /* OPENSSL_NO_SOCK */