transport_common.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. /* Copyright (c) 2014, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. // Suppress MSVC's STL warnings. It flags |std::copy| calls with a raw output
  15. // pointer, on grounds that MSVC cannot check them. Unfortunately, there is no
  16. // way to suppress the warning just on one line. The warning is flagged inside
  17. // the STL itself, so suppressing at the |std::copy| call does not work.
  18. #define _SCL_SECURE_NO_WARNINGS
  19. #include <openssl/base.h>
  20. #include <string>
  21. #include <vector>
  22. #include <errno.h>
  23. #include <limits.h>
  24. #include <stddef.h>
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <sys/types.h>
  28. #if !defined(OPENSSL_WINDOWS)
  29. #include <arpa/inet.h>
  30. #include <fcntl.h>
  31. #include <netdb.h>
  32. #include <netinet/in.h>
  33. #include <sys/select.h>
  34. #include <sys/socket.h>
  35. #include <unistd.h>
  36. #else
  37. #include <algorithm>
  38. #include <condition_variable>
  39. #include <deque>
  40. #include <memory>
  41. #include <mutex>
  42. #include <thread>
  43. #include <utility>
  44. #include <io.h>
  45. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  46. #include <winsock2.h>
  47. #include <ws2tcpip.h>
  48. OPENSSL_MSVC_PRAGMA(warning(pop))
  49. typedef int ssize_t;
  50. OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
  51. #endif
  52. #include <openssl/err.h>
  53. #include <openssl/ssl.h>
  54. #include <openssl/x509.h>
  55. #include "../crypto/internal.h"
  56. #include "internal.h"
  57. #include "transport_common.h"
  58. #if !defined(OPENSSL_WINDOWS)
  59. static int closesocket(int sock) {
  60. return close(sock);
  61. }
  62. #endif
  63. bool InitSocketLibrary() {
  64. #if defined(OPENSSL_WINDOWS)
  65. WSADATA wsaData;
  66. int err = WSAStartup(MAKEWORD(2, 2), &wsaData);
  67. if (err != 0) {
  68. fprintf(stderr, "WSAStartup failed with error %d\n", err);
  69. return false;
  70. }
  71. #endif
  72. return true;
  73. }
  74. static void SplitHostPort(std::string *out_hostname, std::string *out_port,
  75. const std::string &hostname_and_port) {
  76. size_t colon_offset = hostname_and_port.find_last_of(':');
  77. const size_t bracket_offset = hostname_and_port.find_last_of(']');
  78. std::string hostname, port;
  79. // An IPv6 literal may have colons internally, guarded by square brackets.
  80. if (bracket_offset != std::string::npos &&
  81. colon_offset != std::string::npos && bracket_offset > colon_offset) {
  82. colon_offset = std::string::npos;
  83. }
  84. if (colon_offset == std::string::npos) {
  85. *out_hostname = hostname_and_port;
  86. *out_port = "443";
  87. } else {
  88. *out_hostname = hostname_and_port.substr(0, colon_offset);
  89. *out_port = hostname_and_port.substr(colon_offset + 1);
  90. }
  91. }
  92. static std::string GetLastSocketErrorString() {
  93. #if defined(OPENSSL_WINDOWS)
  94. int error = WSAGetLastError();
  95. char *buffer;
  96. DWORD len = FormatMessageA(
  97. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, 0, error, 0,
  98. reinterpret_cast<char *>(&buffer), 0, nullptr);
  99. if (len == 0) {
  100. char buf[256];
  101. snprintf(buf, sizeof(buf), "unknown error (0x%x)", error);
  102. return buf;
  103. }
  104. std::string ret(buffer, len);
  105. LocalFree(buffer);
  106. return ret;
  107. #else
  108. return strerror(errno);
  109. #endif
  110. }
  111. static void PrintSocketError(const char *function) {
  112. // On Windows, |perror| and |errno| are part of the C runtime, while sockets
  113. // are separate, so we must print errors manually.
  114. std::string error = GetLastSocketErrorString();
  115. fprintf(stderr, "%s: %s\n", function, error.c_str());
  116. }
  117. // Connect sets |*out_sock| to be a socket connected to the destination given
  118. // in |hostname_and_port|, which should be of the form "www.example.com:123".
  119. // It returns true on success and false otherwise.
  120. bool Connect(int *out_sock, const std::string &hostname_and_port) {
  121. std::string hostname, port;
  122. SplitHostPort(&hostname, &port, hostname_and_port);
  123. // Handle IPv6 literals.
  124. if (hostname.size() >= 2 && hostname[0] == '[' &&
  125. hostname[hostname.size() - 1] == ']') {
  126. hostname = hostname.substr(1, hostname.size() - 2);
  127. }
  128. struct addrinfo hint, *result;
  129. OPENSSL_memset(&hint, 0, sizeof(hint));
  130. hint.ai_family = AF_UNSPEC;
  131. hint.ai_socktype = SOCK_STREAM;
  132. int ret = getaddrinfo(hostname.c_str(), port.c_str(), &hint, &result);
  133. if (ret != 0) {
  134. fprintf(stderr, "getaddrinfo returned: %s\n", gai_strerror(ret));
  135. return false;
  136. }
  137. bool ok = false;
  138. char buf[256];
  139. *out_sock =
  140. socket(result->ai_family, result->ai_socktype, result->ai_protocol);
  141. if (*out_sock < 0) {
  142. PrintSocketError("socket");
  143. goto out;
  144. }
  145. switch (result->ai_family) {
  146. case AF_INET: {
  147. struct sockaddr_in *sin =
  148. reinterpret_cast<struct sockaddr_in *>(result->ai_addr);
  149. fprintf(stderr, "Connecting to %s:%d\n",
  150. inet_ntop(result->ai_family, &sin->sin_addr, buf, sizeof(buf)),
  151. ntohs(sin->sin_port));
  152. break;
  153. }
  154. case AF_INET6: {
  155. struct sockaddr_in6 *sin6 =
  156. reinterpret_cast<struct sockaddr_in6 *>(result->ai_addr);
  157. fprintf(stderr, "Connecting to [%s]:%d\n",
  158. inet_ntop(result->ai_family, &sin6->sin6_addr, buf, sizeof(buf)),
  159. ntohs(sin6->sin6_port));
  160. break;
  161. }
  162. }
  163. if (connect(*out_sock, result->ai_addr, result->ai_addrlen) != 0) {
  164. PrintSocketError("connect");
  165. goto out;
  166. }
  167. ok = true;
  168. out:
  169. freeaddrinfo(result);
  170. return ok;
  171. }
  172. Listener::~Listener() {
  173. if (server_sock_ >= 0) {
  174. closesocket(server_sock_);
  175. }
  176. }
  177. bool Listener::Init(const std::string &port) {
  178. if (server_sock_ >= 0) {
  179. return false;
  180. }
  181. struct sockaddr_in6 addr;
  182. OPENSSL_memset(&addr, 0, sizeof(addr));
  183. addr.sin6_family = AF_INET6;
  184. // Windows' IN6ADDR_ANY_INIT does not have enough curly braces for clang-cl
  185. // (https://crbug.com/772108), while other platforms like NaCl are missing
  186. // in6addr_any, so use a mix of both.
  187. #if defined(OPENSSL_WINDOWS)
  188. addr.sin6_addr = in6addr_any;
  189. #else
  190. addr.sin6_addr = IN6ADDR_ANY_INIT;
  191. #endif
  192. addr.sin6_port = htons(atoi(port.c_str()));
  193. #if defined(OPENSSL_WINDOWS)
  194. const BOOL enable = TRUE;
  195. #else
  196. const int enable = 1;
  197. #endif
  198. server_sock_ = socket(addr.sin6_family, SOCK_STREAM, 0);
  199. if (server_sock_ < 0) {
  200. PrintSocketError("socket");
  201. return false;
  202. }
  203. if (setsockopt(server_sock_, SOL_SOCKET, SO_REUSEADDR, (const char *)&enable,
  204. sizeof(enable)) < 0) {
  205. PrintSocketError("setsockopt");
  206. return false;
  207. }
  208. if (bind(server_sock_, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
  209. PrintSocketError("connect");
  210. return false;
  211. }
  212. listen(server_sock_, SOMAXCONN);
  213. return true;
  214. }
  215. bool Listener::Accept(int *out_sock) {
  216. struct sockaddr_in6 addr;
  217. socklen_t addr_len = sizeof(addr);
  218. *out_sock = accept(server_sock_, (struct sockaddr *)&addr, &addr_len);
  219. return *out_sock >= 0;
  220. }
  221. bool VersionFromString(uint16_t *out_version, const std::string &version) {
  222. if (version == "tls1" || version == "tls1.0") {
  223. *out_version = TLS1_VERSION;
  224. return true;
  225. } else if (version == "tls1.1") {
  226. *out_version = TLS1_1_VERSION;
  227. return true;
  228. } else if (version == "tls1.2") {
  229. *out_version = TLS1_2_VERSION;
  230. return true;
  231. } else if (version == "tls1.3") {
  232. *out_version = TLS1_3_VERSION;
  233. return true;
  234. }
  235. return false;
  236. }
  237. void PrintConnectionInfo(BIO *bio, const SSL *ssl) {
  238. const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
  239. BIO_printf(bio, " Version: %s\n", SSL_get_version(ssl));
  240. BIO_printf(bio, " Resumed session: %s\n",
  241. SSL_session_reused(ssl) ? "yes" : "no");
  242. BIO_printf(bio, " Cipher: %s\n", SSL_CIPHER_standard_name(cipher));
  243. uint16_t curve = SSL_get_curve_id(ssl);
  244. if (curve != 0) {
  245. BIO_printf(bio, " ECDHE curve: %s\n", SSL_get_curve_name(curve));
  246. }
  247. uint16_t sigalg = SSL_get_peer_signature_algorithm(ssl);
  248. if (sigalg != 0) {
  249. BIO_printf(bio, " Signature algorithm: %s\n",
  250. SSL_get_signature_algorithm_name(
  251. sigalg, SSL_version(ssl) != TLS1_2_VERSION));
  252. }
  253. BIO_printf(bio, " Secure renegotiation: %s\n",
  254. SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no");
  255. BIO_printf(bio, " Extended master secret: %s\n",
  256. SSL_get_extms_support(ssl) ? "yes" : "no");
  257. const uint8_t *next_proto;
  258. unsigned next_proto_len;
  259. SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
  260. BIO_printf(bio, " Next protocol negotiated: %.*s\n", next_proto_len,
  261. next_proto);
  262. const uint8_t *alpn;
  263. unsigned alpn_len;
  264. SSL_get0_alpn_selected(ssl, &alpn, &alpn_len);
  265. BIO_printf(bio, " ALPN protocol: %.*s\n", alpn_len, alpn);
  266. const char *host_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  267. if (host_name != nullptr && SSL_is_server(ssl)) {
  268. BIO_printf(bio, " Client sent SNI: %s\n", host_name);
  269. }
  270. if (!SSL_is_server(ssl)) {
  271. const uint8_t *ocsp_staple;
  272. size_t ocsp_staple_len;
  273. SSL_get0_ocsp_response(ssl, &ocsp_staple, &ocsp_staple_len);
  274. BIO_printf(bio, " OCSP staple: %s\n", ocsp_staple_len > 0 ? "yes" : "no");
  275. const uint8_t *sct_list;
  276. size_t sct_list_len;
  277. SSL_get0_signed_cert_timestamp_list(ssl, &sct_list, &sct_list_len);
  278. BIO_printf(bio, " SCT list: %s\n", sct_list_len > 0 ? "yes" : "no");
  279. }
  280. BIO_printf(
  281. bio, " Early data: %s\n",
  282. (SSL_early_data_accepted(ssl) || SSL_in_early_data(ssl)) ? "yes" : "no");
  283. // Print the server cert subject and issuer names.
  284. bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(ssl));
  285. if (peer != nullptr) {
  286. BIO_printf(bio, " Cert subject: ");
  287. X509_NAME_print_ex(bio, X509_get_subject_name(peer.get()), 0,
  288. XN_FLAG_ONELINE);
  289. BIO_printf(bio, "\n Cert issuer: ");
  290. X509_NAME_print_ex(bio, X509_get_issuer_name(peer.get()), 0,
  291. XN_FLAG_ONELINE);
  292. BIO_printf(bio, "\n");
  293. }
  294. }
  295. bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
  296. bool ok;
  297. #if defined(OPENSSL_WINDOWS)
  298. u_long arg = is_non_blocking;
  299. ok = 0 == ioctlsocket(sock, FIONBIO, &arg);
  300. #else
  301. int flags = fcntl(sock, F_GETFL, 0);
  302. if (flags < 0) {
  303. return false;
  304. }
  305. if (is_non_blocking) {
  306. flags |= O_NONBLOCK;
  307. } else {
  308. flags &= ~O_NONBLOCK;
  309. }
  310. ok = 0 == fcntl(sock, F_SETFL, flags);
  311. #endif
  312. if (!ok) {
  313. PrintSocketError("Failed to set socket non-blocking");
  314. }
  315. return ok;
  316. }
  317. enum class StdinWait {
  318. kStdinRead,
  319. kSocketWrite,
  320. };
  321. #if !defined(OPENSSL_WINDOWS)
  322. // SocketWaiter abstracts waiting for either the socket or stdin to be readable
  323. // between Windows and POSIX.
  324. class SocketWaiter {
  325. public:
  326. explicit SocketWaiter(int sock) : sock_(sock) {}
  327. SocketWaiter(const SocketWaiter &) = delete;
  328. SocketWaiter &operator=(const SocketWaiter &) = delete;
  329. // Init initializes the SocketWaiter. It returns whether it succeeded.
  330. bool Init() { return true; }
  331. // Wait waits for at least on of the socket or stdin or be ready. On success,
  332. // it sets |*socket_ready| and |*stdin_ready| to whether the respective
  333. // objects are readable and returns true. On error, it returns false. stdin's
  334. // readiness may either be the socket being writable or stdin being readable,
  335. // depending on |stdin_wait|.
  336. bool Wait(StdinWait stdin_wait, bool *socket_ready, bool *stdin_ready) {
  337. *socket_ready = true;
  338. *stdin_ready = false;
  339. fd_set read_fds, write_fds;
  340. FD_ZERO(&read_fds);
  341. FD_ZERO(&write_fds);
  342. if (stdin_wait == StdinWait::kSocketWrite) {
  343. FD_SET(sock_, &write_fds);
  344. } else if (stdin_open_) {
  345. FD_SET(STDIN_FILENO, &read_fds);
  346. }
  347. FD_SET(sock_, &read_fds);
  348. if (select(sock_ + 1, &read_fds, &write_fds, NULL, NULL) <= 0) {
  349. perror("select");
  350. return false;
  351. }
  352. if (FD_ISSET(STDIN_FILENO, &read_fds) || FD_ISSET(sock_, &write_fds)) {
  353. *stdin_ready = true;
  354. }
  355. if (FD_ISSET(sock_, &read_fds)) {
  356. *socket_ready = true;
  357. }
  358. return true;
  359. }
  360. // ReadStdin reads at most |max_out| bytes from stdin. On success, it writes
  361. // them to |out| and sets |*out_len| to the number of bytes written. On error,
  362. // it returns false. This method may only be called after |Wait| returned
  363. // stdin was ready.
  364. bool ReadStdin(void *out, size_t *out_len, size_t max_out) {
  365. ssize_t n;
  366. do {
  367. n = read(STDIN_FILENO, out, max_out);
  368. } while (n == -1 && errno == EINTR);
  369. if (n <= 0) {
  370. stdin_open_ = false;
  371. }
  372. if (n < 0) {
  373. perror("read from stdin");
  374. return false;
  375. }
  376. *out_len = static_cast<size_t>(n);
  377. return true;
  378. }
  379. private:
  380. bool stdin_open_ = true;
  381. int sock_;
  382. };
  383. #else // OPENSSL_WINDOWs
  384. class ScopedWSAEVENT {
  385. public:
  386. ScopedWSAEVENT() = default;
  387. ScopedWSAEVENT(WSAEVENT event) { reset(event); }
  388. ScopedWSAEVENT(const ScopedWSAEVENT &) = delete;
  389. ScopedWSAEVENT(ScopedWSAEVENT &&other) { *this = std::move(other); }
  390. ~ScopedWSAEVENT() { reset(); }
  391. ScopedWSAEVENT &operator=(const ScopedWSAEVENT &) = delete;
  392. ScopedWSAEVENT &operator=(ScopedWSAEVENT &&other) {
  393. reset(other.release());
  394. return *this;
  395. }
  396. explicit operator bool() const { return event_ != WSA_INVALID_EVENT; }
  397. WSAEVENT get() const { return event_; }
  398. WSAEVENT release() {
  399. WSAEVENT ret = event_;
  400. event_ = WSA_INVALID_EVENT;
  401. return ret;
  402. }
  403. void reset(WSAEVENT event = WSA_INVALID_EVENT) {
  404. if (event_ != WSA_INVALID_EVENT) {
  405. WSACloseEvent(event_);
  406. }
  407. event_ = event;
  408. }
  409. private:
  410. WSAEVENT event_ = WSA_INVALID_EVENT;
  411. };
  412. // SocketWaiter, on Windows, is more complicated. While |WaitForMultipleObjects|
  413. // works for both sockets and stdin, the latter is often a line-buffered
  414. // console. The |HANDLE| is considered readable if there are any console events
  415. // available, but reading blocks until a full line is available.
  416. //
  417. // So that |Wait| reflects final stdin read, we spawn a stdin reader thread that
  418. // writes to an in-memory buffer and signals a |WSAEVENT| to coordinate with the
  419. // socket.
  420. class SocketWaiter {
  421. public:
  422. explicit SocketWaiter(int sock) : sock_(sock) {}
  423. SocketWaiter(const SocketWaiter &) = delete;
  424. SocketWaiter &operator=(const SocketWaiter &) = delete;
  425. bool Init() {
  426. stdin_ = std::make_shared<StdinState>();
  427. stdin_->event.reset(WSACreateEvent());
  428. if (!stdin_->event) {
  429. PrintSocketError("Error in WSACreateEvent");
  430. return false;
  431. }
  432. // Spawn a thread to block on stdin.
  433. std::shared_ptr<StdinState> state = stdin_;
  434. std::thread thread([state]() {
  435. for (;;) {
  436. uint8_t buf[512];
  437. int ret = _read(0 /* stdin */, buf, sizeof(buf));
  438. if (ret <= 0) {
  439. if (ret < 0) {
  440. perror("read from stdin");
  441. }
  442. // Report the error or EOF to the caller.
  443. std::lock_guard<std::mutex> lock(state->lock);
  444. state->error = ret < 0;
  445. state->open = false;
  446. WSASetEvent(state->event.get());
  447. return;
  448. }
  449. size_t len = static_cast<size_t>(ret);
  450. size_t written = 0;
  451. while (written < len) {
  452. std::unique_lock<std::mutex> lock(state->lock);
  453. // Wait for there to be room in the buffer.
  454. state->cond.wait(lock, [&] { return !state->buffer_full(); });
  455. // Copy what we can and signal to the caller.
  456. size_t todo = std::min(len - written, state->buffer_remaining());
  457. state->buffer.insert(state->buffer.end(), buf + written,
  458. buf + written + todo);
  459. written += todo;
  460. WSASetEvent(state->event.get());
  461. }
  462. }
  463. });
  464. thread.detach();
  465. return true;
  466. }
  467. bool Wait(StdinWait stdin_wait, bool *socket_ready, bool *stdin_ready) {
  468. *socket_ready = true;
  469. *stdin_ready = false;
  470. ScopedWSAEVENT sock_read_event(WSACreateEvent());
  471. if (!sock_read_event ||
  472. WSAEventSelect(sock_, sock_read_event.get(), FD_READ | FD_CLOSE) != 0) {
  473. PrintSocketError("Error waiting for socket read");
  474. return false;
  475. }
  476. DWORD count = 1;
  477. WSAEVENT events[3] = {sock_read_event.get(), WSA_INVALID_EVENT};
  478. ScopedWSAEVENT sock_write_event;
  479. if (stdin_wait == StdinWait::kSocketWrite) {
  480. sock_write_event.reset(WSACreateEvent());
  481. if (!sock_write_event || WSAEventSelect(sock_, sock_write_event.get(),
  482. FD_WRITE | FD_CLOSE) != 0) {
  483. PrintSocketError("Error waiting for socket write");
  484. return false;
  485. }
  486. events[1] = sock_write_event.get();
  487. count++;
  488. } else if (listen_stdin_) {
  489. events[1] = stdin_->event.get();
  490. count++;
  491. }
  492. switch (WSAWaitForMultipleEvents(count, events, FALSE /* wait all */,
  493. WSA_INFINITE, FALSE /* alertable */)) {
  494. case WSA_WAIT_EVENT_0 + 0:
  495. *socket_ready = true;
  496. return true;
  497. case WSA_WAIT_EVENT_0 + 1:
  498. *stdin_ready = true;
  499. return true;
  500. case WSA_WAIT_TIMEOUT:
  501. return true;
  502. default:
  503. PrintSocketError("Error waiting for events");
  504. return false;
  505. }
  506. }
  507. bool ReadStdin(void *out, size_t *out_len, size_t max_out) {
  508. std::lock_guard<std::mutex> locked(stdin_->lock);
  509. if (stdin_->buffer.empty()) {
  510. // |ReadStdin| may only be called when |Wait| signals it is ready, so
  511. // stdin must have reached EOF or error.
  512. assert(!stdin_->open);
  513. listen_stdin_ = false;
  514. if (stdin_->error) {
  515. return false;
  516. }
  517. *out_len = 0;
  518. return true;
  519. }
  520. bool was_full = stdin_->buffer_full();
  521. // Copy as many bytes as well fit.
  522. *out_len = std::min(max_out, stdin_->buffer.size());
  523. auto begin = stdin_->buffer.begin();
  524. auto end = stdin_->buffer.begin() + *out_len;
  525. std::copy(begin, end, static_cast<uint8_t *>(out));
  526. stdin_->buffer.erase(begin, end);
  527. // Notify the stdin thread if there is more space.
  528. if (was_full && !stdin_->buffer_full()) {
  529. stdin_->cond.notify_one();
  530. }
  531. // If stdin is now waiting for input, clear the event.
  532. if (stdin_->buffer.empty() && stdin_->open) {
  533. WSAResetEvent(stdin_->event.get());
  534. }
  535. return true;
  536. }
  537. private:
  538. struct StdinState {
  539. static constexpr size_t kMaxBuffer = 1024;
  540. StdinState() = default;
  541. StdinState(const StdinState &) = delete;
  542. StdinState &operator=(const StdinState &) = delete;
  543. size_t buffer_remaining() const { return kMaxBuffer - buffer.size(); }
  544. bool buffer_full() const { return buffer_remaining() == 0; }
  545. ScopedWSAEVENT event;
  546. // lock protects the following fields.
  547. std::mutex lock;
  548. // cond notifies the stdin thread that |buffer| is no longer full.
  549. std::condition_variable cond;
  550. std::deque<uint8_t> buffer;
  551. bool open = true;
  552. bool error = false;
  553. };
  554. int sock_;
  555. std::shared_ptr<StdinState> stdin_;
  556. // listen_stdin_ is set to false when we have consumed an EOF or error from
  557. // |stdin_|. This is separate from |stdin_->open| because the signal may not
  558. // have been consumed yet.
  559. bool listen_stdin_ = true;
  560. };
  561. #endif // OPENSSL_WINDOWS
  562. void PrintSSLError(FILE *file, const char *msg, int ssl_err, int ret) {
  563. switch (ssl_err) {
  564. case SSL_ERROR_SSL:
  565. fprintf(file, "%s: %s\n", msg, ERR_reason_error_string(ERR_peek_error()));
  566. break;
  567. case SSL_ERROR_SYSCALL:
  568. if (ret == 0) {
  569. fprintf(file, "%s: peer closed connection\n", msg);
  570. } else {
  571. std::string error = GetLastSocketErrorString();
  572. fprintf(file, "%s: %s\n", msg, error.c_str());
  573. }
  574. break;
  575. case SSL_ERROR_ZERO_RETURN:
  576. fprintf(file, "%s: received close_notify\n", msg);
  577. break;
  578. default:
  579. fprintf(file, "%s: unexpected error: %s\n", msg,
  580. SSL_error_description(ssl_err));
  581. }
  582. ERR_print_errors_fp(file);
  583. }
  584. bool TransferData(SSL *ssl, int sock) {
  585. if (!SocketSetNonBlocking(sock, true)) {
  586. return false;
  587. }
  588. SocketWaiter waiter(sock);
  589. if (!waiter.Init()) {
  590. return false;
  591. }
  592. uint8_t pending_write[512];
  593. size_t pending_write_len = 0;
  594. for (;;) {
  595. bool socket_ready = false;
  596. bool stdin_ready = false;
  597. if (!waiter.Wait(pending_write_len == 0 ? StdinWait::kStdinRead
  598. : StdinWait::kSocketWrite,
  599. &socket_ready, &stdin_ready)) {
  600. return false;
  601. }
  602. if (stdin_ready) {
  603. if (pending_write_len == 0) {
  604. if (!waiter.ReadStdin(pending_write, &pending_write_len,
  605. sizeof(pending_write))) {
  606. return false;
  607. }
  608. if (pending_write_len == 0) {
  609. #if !defined(OPENSSL_WINDOWS)
  610. shutdown(sock, SHUT_WR);
  611. #else
  612. shutdown(sock, SD_SEND);
  613. #endif
  614. continue;
  615. }
  616. }
  617. int ssl_ret =
  618. SSL_write(ssl, pending_write, static_cast<int>(pending_write_len));
  619. if (ssl_ret <= 0) {
  620. int ssl_err = SSL_get_error(ssl, ssl_ret);
  621. if (ssl_err == SSL_ERROR_WANT_WRITE) {
  622. continue;
  623. }
  624. PrintSSLError(stderr, "Error while writing", ssl_err, ssl_ret);
  625. return false;
  626. }
  627. if (ssl_ret != static_cast<int>(pending_write_len)) {
  628. fprintf(stderr, "Short write from SSL_write.\n");
  629. return false;
  630. }
  631. pending_write_len = 0;
  632. }
  633. if (socket_ready) {
  634. for (;;) {
  635. uint8_t buffer[512];
  636. int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
  637. if (ssl_ret < 0) {
  638. int ssl_err = SSL_get_error(ssl, ssl_ret);
  639. if (ssl_err == SSL_ERROR_WANT_READ) {
  640. break;
  641. }
  642. PrintSSLError(stderr, "Error while reading", ssl_err, ssl_ret);
  643. return false;
  644. } else if (ssl_ret == 0) {
  645. return true;
  646. }
  647. ssize_t n;
  648. do {
  649. n = BORINGSSL_WRITE(1, buffer, ssl_ret);
  650. } while (n == -1 && errno == EINTR);
  651. if (n != ssl_ret) {
  652. fprintf(stderr, "Short write to stderr.\n");
  653. return false;
  654. }
  655. }
  656. }
  657. }
  658. }
  659. // SocketLineReader wraps a small buffer around a socket for line-orientated
  660. // protocols.
  661. class SocketLineReader {
  662. public:
  663. explicit SocketLineReader(int sock) : sock_(sock) {}
  664. // Next reads a '\n'- or '\r\n'-terminated line from the socket and, on
  665. // success, sets |*out_line| to it and returns true. Otherwise it returns
  666. // false.
  667. bool Next(std::string *out_line) {
  668. for (;;) {
  669. for (size_t i = 0; i < buf_len_; i++) {
  670. if (buf_[i] != '\n') {
  671. continue;
  672. }
  673. size_t length = i;
  674. if (i > 0 && buf_[i - 1] == '\r') {
  675. length--;
  676. }
  677. out_line->assign(buf_, length);
  678. buf_len_ -= i + 1;
  679. OPENSSL_memmove(buf_, &buf_[i + 1], buf_len_);
  680. return true;
  681. }
  682. if (buf_len_ == sizeof(buf_)) {
  683. fprintf(stderr, "Received line too long!\n");
  684. return false;
  685. }
  686. ssize_t n;
  687. do {
  688. n = recv(sock_, &buf_[buf_len_], sizeof(buf_) - buf_len_, 0);
  689. } while (n == -1 && errno == EINTR);
  690. if (n < 0) {
  691. fprintf(stderr, "Read error from socket\n");
  692. return false;
  693. }
  694. buf_len_ += n;
  695. }
  696. }
  697. // ReadSMTPReply reads one or more lines that make up an SMTP reply. On
  698. // success, it sets |*out_code| to the reply's code (e.g. 250) and
  699. // |*out_content| to the body of the reply (e.g. "OK") and returns true.
  700. // Otherwise it returns false.
  701. //
  702. // See https://tools.ietf.org/html/rfc821#page-48
  703. bool ReadSMTPReply(unsigned *out_code, std::string *out_content) {
  704. out_content->clear();
  705. // kMaxLines is the maximum number of lines that we'll accept in an SMTP
  706. // reply.
  707. static const unsigned kMaxLines = 512;
  708. for (unsigned i = 0; i < kMaxLines; i++) {
  709. std::string line;
  710. if (!Next(&line)) {
  711. return false;
  712. }
  713. if (line.size() < 4) {
  714. fprintf(stderr, "Short line from SMTP server: %s\n", line.c_str());
  715. return false;
  716. }
  717. const std::string code_str = line.substr(0, 3);
  718. char *endptr;
  719. const unsigned long code = strtoul(code_str.c_str(), &endptr, 10);
  720. if (*endptr || code > UINT_MAX) {
  721. fprintf(stderr, "Failed to parse code from line: %s\n", line.c_str());
  722. return false;
  723. }
  724. if (i == 0) {
  725. *out_code = code;
  726. } else if (code != *out_code) {
  727. fprintf(stderr,
  728. "Reply code varied within a single reply: was %u, now %u\n",
  729. *out_code, static_cast<unsigned>(code));
  730. return false;
  731. }
  732. if (line[3] == ' ') {
  733. // End of reply.
  734. *out_content += line.substr(4, std::string::npos);
  735. return true;
  736. } else if (line[3] == '-') {
  737. // Another line of reply will follow this one.
  738. *out_content += line.substr(4, std::string::npos);
  739. out_content->push_back('\n');
  740. } else {
  741. fprintf(stderr, "Bad character after code in SMTP reply: %s\n",
  742. line.c_str());
  743. return false;
  744. }
  745. }
  746. fprintf(stderr, "Rejected SMTP reply of more then %u lines\n", kMaxLines);
  747. return false;
  748. }
  749. private:
  750. const int sock_;
  751. char buf_[512];
  752. size_t buf_len_ = 0;
  753. };
  754. // SendAll writes |data_len| bytes from |data| to |sock|. It returns true on
  755. // success and false otherwise.
  756. static bool SendAll(int sock, const char *data, size_t data_len) {
  757. size_t done = 0;
  758. while (done < data_len) {
  759. ssize_t n;
  760. do {
  761. n = send(sock, &data[done], data_len - done, 0);
  762. } while (n == -1 && errno == EINTR);
  763. if (n < 0) {
  764. fprintf(stderr, "Error while writing to socket\n");
  765. return false;
  766. }
  767. done += n;
  768. }
  769. return true;
  770. }
  771. bool DoSMTPStartTLS(int sock) {
  772. SocketLineReader line_reader(sock);
  773. unsigned code_220 = 0;
  774. std::string reply_220;
  775. if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
  776. return false;
  777. }
  778. if (code_220 != 220) {
  779. fprintf(stderr, "Expected 220 line from SMTP server but got code %u\n",
  780. code_220);
  781. return false;
  782. }
  783. static const char kHelloLine[] = "EHLO BoringSSL\r\n";
  784. if (!SendAll(sock, kHelloLine, sizeof(kHelloLine) - 1)) {
  785. return false;
  786. }
  787. unsigned code_250 = 0;
  788. std::string reply_250;
  789. if (!line_reader.ReadSMTPReply(&code_250, &reply_250)) {
  790. return false;
  791. }
  792. if (code_250 != 250) {
  793. fprintf(stderr, "Expected 250 line after EHLO but got code %u\n", code_250);
  794. return false;
  795. }
  796. // https://tools.ietf.org/html/rfc1869#section-4.3
  797. if (("\n" + reply_250 + "\n").find("\nSTARTTLS\n") == std::string::npos) {
  798. fprintf(stderr, "Server does not support STARTTLS\n");
  799. return false;
  800. }
  801. static const char kSTARTTLSLine[] = "STARTTLS\r\n";
  802. if (!SendAll(sock, kSTARTTLSLine, sizeof(kSTARTTLSLine) - 1)) {
  803. return false;
  804. }
  805. if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
  806. return false;
  807. }
  808. if (code_220 != 220) {
  809. fprintf(
  810. stderr,
  811. "Expected 220 line from SMTP server after STARTTLS, but got code %u\n",
  812. code_220);
  813. return false;
  814. }
  815. return true;
  816. }
  817. bool DoHTTPTunnel(int sock, const std::string &hostname_and_port) {
  818. std::string hostname, port;
  819. SplitHostPort(&hostname, &port, hostname_and_port);
  820. fprintf(stderr, "Establishing HTTP tunnel to %s:%s.\n", hostname.c_str(),
  821. port.c_str());
  822. char buf[1024];
  823. snprintf(buf, sizeof(buf), "CONNECT %s:%s HTTP/1.0\r\n\r\n", hostname.c_str(),
  824. port.c_str());
  825. if (!SendAll(sock, buf, strlen(buf))) {
  826. return false;
  827. }
  828. SocketLineReader line_reader(sock);
  829. // Read until an empty line, signaling the end of the HTTP response.
  830. std::string line;
  831. for (;;) {
  832. if (!line_reader.Next(&line)) {
  833. return false;
  834. }
  835. if (line.empty()) {
  836. return true;
  837. }
  838. fprintf(stderr, "%s\n", line.c_str());
  839. }
  840. }