s_socket.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /*
  2. * Copyright 1995-2021 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. /*
  28. * With MSVC, certain POSIX functions have been renamed to have an underscore
  29. * prefix.
  30. */
  31. # include <process.h>
  32. # define getpid _getpid
  33. #endif
  34. #ifndef OPENSSL_NO_SOCK
  35. # include "apps.h"
  36. # include "s_apps.h"
  37. # include "internal/sockets.h"
  38. # if defined(__TANDEM)
  39. # if defined(OPENSSL_TANDEM_FLOSS)
  40. # include <floss.h(floss_read)>
  41. # endif
  42. # endif
  43. # include <openssl/bio.h>
  44. # include <openssl/err.h>
  45. /* Keep track of our peer's address for the cookie callback */
  46. BIO_ADDR *ourpeer = NULL;
  47. /*
  48. * init_client - helper routine to set up socket communication
  49. * @sock: pointer to storage of resulting socket.
  50. * @host: the host name or path (for AF_UNIX) to connect to.
  51. * @port: the port to connect to (ignored for AF_UNIX).
  52. * @bindhost: source host or path (for AF_UNIX).
  53. * @bindport: source port (ignored for AF_UNIX).
  54. * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
  55. * AF_UNSPEC
  56. * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
  57. * @protocol: socket protocol, e.g. IPPROTO_TCP or IPPROTO_UDP (or 0 for any)
  58. *
  59. * This will create a socket and use it to connect to a host:port, or if
  60. * family == AF_UNIX, to the path found in host.
  61. *
  62. * If the host has more than one address, it will try them one by one until
  63. * a successful connection is established. The resulting socket will be
  64. * found in *sock on success, it will be given INVALID_SOCKET otherwise.
  65. *
  66. * Returns 1 on success, 0 on failure.
  67. */
  68. int init_client(int *sock, const char *host, const char *port,
  69. const char *bindhost, const char *bindport,
  70. int family, int type, int protocol)
  71. {
  72. BIO_ADDRINFO *res = NULL;
  73. BIO_ADDRINFO *bindaddr = NULL;
  74. const BIO_ADDRINFO *ai = NULL;
  75. const BIO_ADDRINFO *bi = NULL;
  76. int found = 0;
  77. int ret;
  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_connect(*sock, BIO_ADDRINFO_address(ai),
  146. protocol == IPPROTO_TCP ? BIO_SOCK_NODELAY : 0)) {
  147. BIO_closesocket(*sock);
  148. *sock = INVALID_SOCKET;
  149. continue;
  150. }
  151. /* Success, don't try any more addresses */
  152. break;
  153. }
  154. if (*sock == INVALID_SOCKET) {
  155. if (bindaddr != NULL && !found) {
  156. BIO_printf(bio_err, "Can't bind %saddress for %s%s%s\n",
  157. #ifdef AF_INET6
  158. BIO_ADDRINFO_family(res) == AF_INET6 ? "IPv6 " :
  159. #endif
  160. BIO_ADDRINFO_family(res) == AF_INET ? "IPv4 " :
  161. BIO_ADDRINFO_family(res) == AF_UNIX ? "unix " : "",
  162. bindhost != NULL ? bindhost : "",
  163. bindport != NULL ? ":" : "",
  164. bindport != NULL ? bindport : "");
  165. ERR_clear_error();
  166. ret = 0;
  167. }
  168. ERR_print_errors(bio_err);
  169. } else {
  170. /* Remove any stale errors from previous connection attempts */
  171. ERR_clear_error();
  172. ret = 1;
  173. }
  174. out:
  175. if (bindaddr != NULL) {
  176. BIO_ADDRINFO_free (bindaddr);
  177. }
  178. BIO_ADDRINFO_free(res);
  179. return ret;
  180. }
  181. int report_server_accept(BIO *out, int asock, int with_address, int with_pid)
  182. {
  183. int success = 1;
  184. if (BIO_printf(out, "ACCEPT") <= 0)
  185. return 0;
  186. if (with_address) {
  187. union BIO_sock_info_u info;
  188. char *hostname = NULL;
  189. char *service = NULL;
  190. if ((info.addr = BIO_ADDR_new()) != NULL
  191. && BIO_sock_info(asock, BIO_SOCK_INFO_ADDRESS, &info)
  192. && (hostname = BIO_ADDR_hostname_string(info.addr, 1)) != NULL
  193. && (service = BIO_ADDR_service_string(info.addr, 1)) != NULL) {
  194. success = BIO_printf(out,
  195. strchr(hostname, ':') == NULL
  196. ? /* IPv4 */ " %s:%s"
  197. : /* IPv6 */ " [%s]:%s",
  198. hostname, service) > 0;
  199. } else {
  200. (void)BIO_printf(out, "unknown:error\n");
  201. success = 0;
  202. }
  203. OPENSSL_free(hostname);
  204. OPENSSL_free(service);
  205. BIO_ADDR_free(info.addr);
  206. }
  207. if (with_pid)
  208. success = success && BIO_printf(out, " PID=%d", getpid()) > 0;
  209. success = success && BIO_printf(out, "\n") > 0;
  210. (void)BIO_flush(out);
  211. return success;
  212. }
  213. /*
  214. * do_server - helper routine to perform a server operation
  215. * @accept_sock: pointer to storage of resulting socket.
  216. * @host: the host name or path (for AF_UNIX) to connect to.
  217. * @port: the port to connect to (ignored for AF_UNIX).
  218. * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or
  219. * AF_UNSPEC
  220. * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM
  221. * @cb: pointer to a function that receives the accepted socket and
  222. * should perform the communication with the connecting client.
  223. * @context: pointer to memory that's passed verbatim to the cb function.
  224. * @naccept: number of times an incoming connect should be accepted. If -1,
  225. * unlimited number.
  226. *
  227. * This will create a socket and use it to listen to a host:port, or if
  228. * family == AF_UNIX, to the path found in host, then start accepting
  229. * incoming connections and run cb on the resulting socket.
  230. *
  231. * 0 on failure, something other on success.
  232. */
  233. int do_server(int *accept_sock, const char *host, const char *port,
  234. int family, int type, int protocol, do_server_cb cb,
  235. unsigned char *context, int naccept, BIO *bio_s_out)
  236. {
  237. int asock = 0;
  238. int sock;
  239. int i;
  240. BIO_ADDRINFO *res = NULL;
  241. const BIO_ADDRINFO *next;
  242. int sock_family, sock_type, sock_protocol, sock_port;
  243. const BIO_ADDR *sock_address;
  244. int sock_options = BIO_SOCK_REUSEADDR;
  245. int ret = 0;
  246. if (BIO_sock_init() != 1)
  247. return 0;
  248. if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol,
  249. &res)) {
  250. ERR_print_errors(bio_err);
  251. return 0;
  252. }
  253. /* Admittedly, these checks are quite paranoid, we should not get
  254. * anything in the BIO_ADDRINFO chain that we haven't asked for */
  255. OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res))
  256. && (type == 0 || type == BIO_ADDRINFO_socktype(res))
  257. && (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res)));
  258. sock_family = BIO_ADDRINFO_family(res);
  259. sock_type = BIO_ADDRINFO_socktype(res);
  260. sock_protocol = BIO_ADDRINFO_protocol(res);
  261. sock_address = BIO_ADDRINFO_address(res);
  262. next = BIO_ADDRINFO_next(res);
  263. #ifdef AF_INET6
  264. if (sock_family == AF_INET6)
  265. sock_options |= BIO_SOCK_V6_ONLY;
  266. if (next != NULL
  267. && BIO_ADDRINFO_socktype(next) == sock_type
  268. && BIO_ADDRINFO_protocol(next) == sock_protocol) {
  269. if (sock_family == AF_INET
  270. && BIO_ADDRINFO_family(next) == AF_INET6) {
  271. sock_family = AF_INET6;
  272. sock_address = BIO_ADDRINFO_address(next);
  273. } else if (sock_family == AF_INET6
  274. && BIO_ADDRINFO_family(next) == AF_INET) {
  275. sock_options &= ~BIO_SOCK_V6_ONLY;
  276. }
  277. }
  278. #endif
  279. asock = BIO_socket(sock_family, sock_type, sock_protocol, 0);
  280. if (asock == INVALID_SOCKET
  281. || !BIO_listen(asock, sock_address, sock_options)) {
  282. BIO_ADDRINFO_free(res);
  283. ERR_print_errors(bio_err);
  284. if (asock != INVALID_SOCKET)
  285. BIO_closesocket(asock);
  286. goto end;
  287. }
  288. #ifndef OPENSSL_NO_SCTP
  289. if (protocol == IPPROTO_SCTP) {
  290. /*
  291. * For SCTP we have to set various options on the socket prior to
  292. * accepting. This is done automatically by BIO_new_dgram_sctp().
  293. * We don't actually need the created BIO though so we free it again
  294. * immediately.
  295. */
  296. BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE);
  297. if (tmpbio == NULL) {
  298. BIO_closesocket(asock);
  299. ERR_print_errors(bio_err);
  300. goto end;
  301. }
  302. BIO_free(tmpbio);
  303. }
  304. #endif
  305. sock_port = BIO_ADDR_rawport(sock_address);
  306. BIO_ADDRINFO_free(res);
  307. res = NULL;
  308. if (!report_server_accept(bio_s_out, asock, sock_port == 0, 0)) {
  309. BIO_closesocket(asock);
  310. ERR_print_errors(bio_err);
  311. goto end;
  312. }
  313. if (accept_sock != NULL)
  314. *accept_sock = asock;
  315. for (;;) {
  316. char sink[64];
  317. struct timeval timeout;
  318. fd_set readfds;
  319. if (type == SOCK_STREAM) {
  320. BIO_ADDR_free(ourpeer);
  321. ourpeer = BIO_ADDR_new();
  322. if (ourpeer == NULL) {
  323. BIO_closesocket(asock);
  324. ERR_print_errors(bio_err);
  325. goto end;
  326. }
  327. do {
  328. sock = BIO_accept_ex(asock, ourpeer, 0);
  329. } while (sock < 0 && BIO_sock_should_retry(sock));
  330. if (sock < 0) {
  331. ERR_print_errors(bio_err);
  332. BIO_closesocket(asock);
  333. break;
  334. }
  335. BIO_set_tcp_ndelay(sock, 1);
  336. i = (*cb)(sock, type, protocol, context);
  337. /*
  338. * If we ended with an alert being sent, but still with data in the
  339. * network buffer to be read, then calling BIO_closesocket() will
  340. * result in a TCP-RST being sent. On some platforms (notably
  341. * Windows) then this will result in the peer immediately abandoning
  342. * the connection including any buffered alert data before it has
  343. * had a chance to be read. Shutting down the sending side first,
  344. * and then closing the socket sends TCP-FIN first followed by
  345. * TCP-RST. This seems to allow the peer to read the alert data.
  346. */
  347. shutdown(sock, 1); /* SHUT_WR */
  348. /*
  349. * We just said we have nothing else to say, but it doesn't mean
  350. * that the other side has nothing. It's even recommended to
  351. * consume incoming data. [In testing context this ensures that
  352. * alerts are passed on...]
  353. */
  354. timeout.tv_sec = 0;
  355. timeout.tv_usec = 500000; /* some extreme round-trip */
  356. do {
  357. FD_ZERO(&readfds);
  358. openssl_fdset(sock, &readfds);
  359. } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
  360. && readsocket(sock, sink, sizeof(sink)) > 0);
  361. BIO_closesocket(sock);
  362. } else {
  363. i = (*cb)(asock, type, protocol, context);
  364. }
  365. if (naccept != -1)
  366. naccept--;
  367. if (i < 0 || naccept == 0) {
  368. BIO_closesocket(asock);
  369. ret = i;
  370. break;
  371. }
  372. }
  373. end:
  374. # ifdef AF_UNIX
  375. if (family == AF_UNIX)
  376. unlink(host);
  377. # endif
  378. BIO_ADDR_free(ourpeer);
  379. ourpeer = NULL;
  380. return ret;
  381. }
  382. void do_ssl_shutdown(SSL *ssl)
  383. {
  384. int ret;
  385. do {
  386. /* We only do unidirectional shutdown */
  387. ret = SSL_shutdown(ssl);
  388. if (ret < 0) {
  389. switch (SSL_get_error(ssl, ret)) {
  390. case SSL_ERROR_WANT_READ:
  391. case SSL_ERROR_WANT_WRITE:
  392. case SSL_ERROR_WANT_ASYNC:
  393. case SSL_ERROR_WANT_ASYNC_JOB:
  394. /* We just do busy waiting. Nothing clever */
  395. continue;
  396. }
  397. ret = 0;
  398. }
  399. } while (ret < 0);
  400. }
  401. #endif /* OPENSSL_NO_SOCK */