Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

974 řádky
28 KiB

  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 == "ssl3") {
  223. *out_version = SSL3_VERSION;
  224. return true;
  225. } else if (version == "tls1" || version == "tls1.0") {
  226. *out_version = TLS1_VERSION;
  227. return true;
  228. } else if (version == "tls1.1") {
  229. *out_version = TLS1_1_VERSION;
  230. return true;
  231. } else if (version == "tls1.2") {
  232. *out_version = TLS1_2_VERSION;
  233. return true;
  234. } else if (version == "tls1.3") {
  235. *out_version = TLS1_3_VERSION;
  236. return true;
  237. }
  238. return false;
  239. }
  240. void PrintConnectionInfo(BIO *bio, const SSL *ssl) {
  241. const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
  242. BIO_printf(bio, " Version: %s\n", SSL_get_version(ssl));
  243. BIO_printf(bio, " Resumed session: %s\n",
  244. SSL_session_reused(ssl) ? "yes" : "no");
  245. BIO_printf(bio, " Cipher: %s\n", SSL_CIPHER_standard_name(cipher));
  246. uint16_t curve = SSL_get_curve_id(ssl);
  247. if (curve != 0) {
  248. BIO_printf(bio, " ECDHE curve: %s\n", SSL_get_curve_name(curve));
  249. }
  250. uint16_t sigalg = SSL_get_peer_signature_algorithm(ssl);
  251. if (sigalg != 0) {
  252. BIO_printf(bio, " Signature algorithm: %s\n",
  253. SSL_get_signature_algorithm_name(
  254. sigalg, SSL_version(ssl) != TLS1_2_VERSION));
  255. }
  256. BIO_printf(bio, " Secure renegotiation: %s\n",
  257. SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no");
  258. BIO_printf(bio, " Extended master secret: %s\n",
  259. SSL_get_extms_support(ssl) ? "yes" : "no");
  260. const uint8_t *next_proto;
  261. unsigned next_proto_len;
  262. SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
  263. BIO_printf(bio, " Next protocol negotiated: %.*s\n", next_proto_len,
  264. next_proto);
  265. const uint8_t *alpn;
  266. unsigned alpn_len;
  267. SSL_get0_alpn_selected(ssl, &alpn, &alpn_len);
  268. BIO_printf(bio, " ALPN protocol: %.*s\n", alpn_len, alpn);
  269. const char *host_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  270. if (host_name != nullptr && SSL_is_server(ssl)) {
  271. BIO_printf(bio, " Client sent SNI: %s\n", host_name);
  272. }
  273. if (!SSL_is_server(ssl)) {
  274. const uint8_t *ocsp_staple;
  275. size_t ocsp_staple_len;
  276. SSL_get0_ocsp_response(ssl, &ocsp_staple, &ocsp_staple_len);
  277. BIO_printf(bio, " OCSP staple: %s\n", ocsp_staple_len > 0 ? "yes" : "no");
  278. const uint8_t *sct_list;
  279. size_t sct_list_len;
  280. SSL_get0_signed_cert_timestamp_list(ssl, &sct_list, &sct_list_len);
  281. BIO_printf(bio, " SCT list: %s\n", sct_list_len > 0 ? "yes" : "no");
  282. }
  283. BIO_printf(
  284. bio, " Early data: %s\n",
  285. (SSL_early_data_accepted(ssl) || SSL_in_early_data(ssl)) ? "yes" : "no");
  286. // Print the server cert subject and issuer names.
  287. bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(ssl));
  288. if (peer != nullptr) {
  289. BIO_printf(bio, " Cert subject: ");
  290. X509_NAME_print_ex(bio, X509_get_subject_name(peer.get()), 0,
  291. XN_FLAG_ONELINE);
  292. BIO_printf(bio, "\n Cert issuer: ");
  293. X509_NAME_print_ex(bio, X509_get_issuer_name(peer.get()), 0,
  294. XN_FLAG_ONELINE);
  295. BIO_printf(bio, "\n");
  296. }
  297. }
  298. bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
  299. bool ok;
  300. #if defined(OPENSSL_WINDOWS)
  301. u_long arg = is_non_blocking;
  302. ok = 0 == ioctlsocket(sock, FIONBIO, &arg);
  303. #else
  304. int flags = fcntl(sock, F_GETFL, 0);
  305. if (flags < 0) {
  306. return false;
  307. }
  308. if (is_non_blocking) {
  309. flags |= O_NONBLOCK;
  310. } else {
  311. flags &= ~O_NONBLOCK;
  312. }
  313. ok = 0 == fcntl(sock, F_SETFL, flags);
  314. #endif
  315. if (!ok) {
  316. PrintSocketError("Failed to set socket non-blocking");
  317. }
  318. return ok;
  319. }
  320. enum class StdinWait {
  321. kStdinRead,
  322. kSocketWrite,
  323. };
  324. #if !defined(OPENSSL_WINDOWS)
  325. // SocketWaiter abstracts waiting for either the socket or stdin to be readable
  326. // between Windows and POSIX.
  327. class SocketWaiter {
  328. public:
  329. explicit SocketWaiter(int sock) : sock_(sock) {}
  330. SocketWaiter(const SocketWaiter &) = delete;
  331. SocketWaiter &operator=(const SocketWaiter &) = delete;
  332. // Init initializes the SocketWaiter. It returns whether it succeeded.
  333. bool Init() { return true; }
  334. // Wait waits for at least on of the socket or stdin or be ready. On success,
  335. // it sets |*socket_ready| and |*stdin_ready| to whether the respective
  336. // objects are readable and returns true. On error, it returns false. stdin's
  337. // readiness may either be the socket being writable or stdin being readable,
  338. // depending on |stdin_wait|.
  339. bool Wait(StdinWait stdin_wait, bool *socket_ready, bool *stdin_ready) {
  340. *socket_ready = true;
  341. *stdin_ready = false;
  342. fd_set read_fds, write_fds;
  343. FD_ZERO(&read_fds);
  344. FD_ZERO(&write_fds);
  345. if (stdin_wait == StdinWait::kSocketWrite) {
  346. FD_SET(sock_, &write_fds);
  347. } else if (stdin_open_) {
  348. FD_SET(STDIN_FILENO, &read_fds);
  349. }
  350. FD_SET(sock_, &read_fds);
  351. if (select(sock_ + 1, &read_fds, &write_fds, NULL, NULL) <= 0) {
  352. perror("select");
  353. return false;
  354. }
  355. if (FD_ISSET(STDIN_FILENO, &read_fds) || FD_ISSET(sock_, &write_fds)) {
  356. *stdin_ready = true;
  357. }
  358. if (FD_ISSET(sock_, &read_fds)) {
  359. *socket_ready = true;
  360. }
  361. return true;
  362. }
  363. // ReadStdin reads at most |max_out| bytes from stdin. On success, it writes
  364. // them to |out| and sets |*out_len| to the number of bytes written. On error,
  365. // it returns false. This method may only be called after |Wait| returned
  366. // stdin was ready.
  367. bool ReadStdin(void *out, size_t *out_len, size_t max_out) {
  368. ssize_t n;
  369. do {
  370. n = read(STDIN_FILENO, out, max_out);
  371. } while (n == -1 && errno == EINTR);
  372. if (n <= 0) {
  373. stdin_open_ = false;
  374. }
  375. if (n < 0) {
  376. perror("read from stdin");
  377. return false;
  378. }
  379. *out_len = static_cast<size_t>(n);
  380. return true;
  381. }
  382. private:
  383. bool stdin_open_ = true;
  384. int sock_;
  385. };
  386. #else // OPENSSL_WINDOWs
  387. class ScopedWSAEVENT {
  388. public:
  389. ScopedWSAEVENT() = default;
  390. ScopedWSAEVENT(WSAEVENT event) { reset(event); }
  391. ScopedWSAEVENT(const ScopedWSAEVENT &) = delete;
  392. ScopedWSAEVENT(ScopedWSAEVENT &&other) { *this = std::move(other); }
  393. ~ScopedWSAEVENT() { reset(); }
  394. ScopedWSAEVENT &operator=(const ScopedWSAEVENT &) = delete;
  395. ScopedWSAEVENT &operator=(ScopedWSAEVENT &&other) {
  396. reset(other.release());
  397. return *this;
  398. }
  399. explicit operator bool() const { return event_ != WSA_INVALID_EVENT; }
  400. WSAEVENT get() const { return event_; }
  401. WSAEVENT release() {
  402. WSAEVENT ret = event_;
  403. event_ = WSA_INVALID_EVENT;
  404. return ret;
  405. }
  406. void reset(WSAEVENT event = WSA_INVALID_EVENT) {
  407. if (event_ != WSA_INVALID_EVENT) {
  408. WSACloseEvent(event_);
  409. }
  410. event_ = event;
  411. }
  412. private:
  413. WSAEVENT event_ = WSA_INVALID_EVENT;
  414. };
  415. // SocketWaiter, on Windows, is more complicated. While |WaitForMultipleObjects|
  416. // works for both sockets and stdin, the latter is often a line-buffered
  417. // console. The |HANDLE| is considered readable if there are any console events
  418. // available, but reading blocks until a full line is available.
  419. //
  420. // So that |Wait| reflects final stdin read, we spawn a stdin reader thread that
  421. // writes to an in-memory buffer and signals a |WSAEVENT| to coordinate with the
  422. // socket.
  423. class SocketWaiter {
  424. public:
  425. explicit SocketWaiter(int sock) : sock_(sock) {}
  426. SocketWaiter(const SocketWaiter &) = delete;
  427. SocketWaiter &operator=(const SocketWaiter &) = delete;
  428. bool Init() {
  429. stdin_ = std::make_shared<StdinState>();
  430. stdin_->event.reset(WSACreateEvent());
  431. if (!stdin_->event) {
  432. PrintSocketError("Error in WSACreateEvent");
  433. return false;
  434. }
  435. // Spawn a thread to block on stdin.
  436. std::shared_ptr<StdinState> state = stdin_;
  437. std::thread thread([state]() {
  438. for (;;) {
  439. uint8_t buf[512];
  440. int ret = _read(0 /* stdin */, buf, sizeof(buf));
  441. if (ret <= 0) {
  442. if (ret < 0) {
  443. perror("read from stdin");
  444. }
  445. // Report the error or EOF to the caller.
  446. std::lock_guard<std::mutex> lock(state->lock);
  447. state->error = ret < 0;
  448. state->open = false;
  449. WSASetEvent(state->event.get());
  450. return;
  451. }
  452. size_t len = static_cast<size_t>(ret);
  453. size_t written = 0;
  454. while (written < len) {
  455. std::unique_lock<std::mutex> lock(state->lock);
  456. // Wait for there to be room in the buffer.
  457. state->cond.wait(lock, [&] { return !state->buffer_full(); });
  458. // Copy what we can and signal to the caller.
  459. size_t todo = std::min(len - written, state->buffer_remaining());
  460. state->buffer.insert(state->buffer.end(), buf + written,
  461. buf + written + todo);
  462. written += todo;
  463. WSASetEvent(state->event.get());
  464. }
  465. }
  466. });
  467. thread.detach();
  468. return true;
  469. }
  470. bool Wait(StdinWait stdin_wait, bool *socket_ready, bool *stdin_ready) {
  471. *socket_ready = true;
  472. *stdin_ready = false;
  473. ScopedWSAEVENT sock_read_event(WSACreateEvent());
  474. if (!sock_read_event ||
  475. WSAEventSelect(sock_, sock_read_event.get(), FD_READ | FD_CLOSE) != 0) {
  476. PrintSocketError("Error waiting for socket read");
  477. return false;
  478. }
  479. DWORD count = 1;
  480. WSAEVENT events[3] = {sock_read_event.get(), WSA_INVALID_EVENT};
  481. ScopedWSAEVENT sock_write_event;
  482. if (stdin_wait == StdinWait::kSocketWrite) {
  483. sock_write_event.reset(WSACreateEvent());
  484. if (!sock_write_event || WSAEventSelect(sock_, sock_write_event.get(),
  485. FD_WRITE | FD_CLOSE) != 0) {
  486. PrintSocketError("Error waiting for socket write");
  487. return false;
  488. }
  489. events[1] = sock_write_event.get();
  490. count++;
  491. } else if (listen_stdin_) {
  492. events[1] = stdin_->event.get();
  493. count++;
  494. }
  495. switch (WSAWaitForMultipleEvents(count, events, FALSE /* wait all */,
  496. WSA_INFINITE, FALSE /* alertable */)) {
  497. case WSA_WAIT_EVENT_0 + 0:
  498. *socket_ready = true;
  499. return true;
  500. case WSA_WAIT_EVENT_0 + 1:
  501. *stdin_ready = true;
  502. return true;
  503. case WSA_WAIT_TIMEOUT:
  504. return true;
  505. default:
  506. PrintSocketError("Error waiting for events");
  507. return false;
  508. }
  509. }
  510. bool ReadStdin(void *out, size_t *out_len, size_t max_out) {
  511. std::lock_guard<std::mutex> locked(stdin_->lock);
  512. if (stdin_->buffer.empty()) {
  513. // |ReadStdin| may only be called when |Wait| signals it is ready, so
  514. // stdin must have reached EOF or error.
  515. assert(!stdin_->open);
  516. listen_stdin_ = false;
  517. if (stdin_->error) {
  518. return false;
  519. }
  520. *out_len = 0;
  521. return true;
  522. }
  523. bool was_full = stdin_->buffer_full();
  524. // Copy as many bytes as well fit.
  525. *out_len = std::min(max_out, stdin_->buffer.size());
  526. auto begin = stdin_->buffer.begin();
  527. auto end = stdin_->buffer.begin() + *out_len;
  528. std::copy(begin, end, static_cast<uint8_t *>(out));
  529. stdin_->buffer.erase(begin, end);
  530. // Notify the stdin thread if there is more space.
  531. if (was_full && !stdin_->buffer_full()) {
  532. stdin_->cond.notify_one();
  533. }
  534. // If stdin is now waiting for input, clear the event.
  535. if (stdin_->buffer.empty() && stdin_->open) {
  536. WSAResetEvent(stdin_->event.get());
  537. }
  538. return true;
  539. }
  540. private:
  541. struct StdinState {
  542. static constexpr size_t kMaxBuffer = 1024;
  543. StdinState() = default;
  544. StdinState(const StdinState &) = delete;
  545. StdinState &operator=(const StdinState &) = delete;
  546. size_t buffer_remaining() const { return kMaxBuffer - buffer.size(); }
  547. bool buffer_full() const { return buffer_remaining() == 0; }
  548. ScopedWSAEVENT event;
  549. // lock protects the following fields.
  550. std::mutex lock;
  551. // cond notifies the stdin thread that |buffer| is no longer full.
  552. std::condition_variable cond;
  553. std::deque<uint8_t> buffer;
  554. bool open = true;
  555. bool error = false;
  556. };
  557. int sock_;
  558. std::shared_ptr<StdinState> stdin_;
  559. // listen_stdin_ is set to false when we have consumed an EOF or error from
  560. // |stdin_|. This is separate from |stdin_->open| because the signal may not
  561. // have been consumed yet.
  562. bool listen_stdin_ = true;
  563. };
  564. #endif // OPENSSL_WINDOWS
  565. void PrintSSLError(FILE *file, const char *msg, int ssl_err, int ret) {
  566. switch (ssl_err) {
  567. case SSL_ERROR_SSL:
  568. fprintf(file, "%s: %s\n", msg, ERR_reason_error_string(ERR_peek_error()));
  569. break;
  570. case SSL_ERROR_SYSCALL:
  571. if (ret == 0) {
  572. fprintf(file, "%s: peer closed connection\n", msg);
  573. } else {
  574. std::string error = GetLastSocketErrorString();
  575. fprintf(file, "%s: %s\n", msg, error.c_str());
  576. }
  577. break;
  578. case SSL_ERROR_ZERO_RETURN:
  579. fprintf(file, "%s: received close_notify\n", msg);
  580. break;
  581. default:
  582. fprintf(file, "%s: unknown error type (%d)\n", msg, ssl_err);
  583. }
  584. ERR_print_errors_fp(file);
  585. }
  586. bool TransferData(SSL *ssl, int sock) {
  587. if (!SocketSetNonBlocking(sock, true)) {
  588. return false;
  589. }
  590. SocketWaiter waiter(sock);
  591. if (!waiter.Init()) {
  592. return false;
  593. }
  594. uint8_t pending_write[512];
  595. size_t pending_write_len = 0;
  596. for (;;) {
  597. bool socket_ready = false;
  598. bool stdin_ready = false;
  599. if (!waiter.Wait(pending_write_len == 0 ? StdinWait::kStdinRead
  600. : StdinWait::kSocketWrite,
  601. &socket_ready, &stdin_ready)) {
  602. return false;
  603. }
  604. if (stdin_ready) {
  605. if (pending_write_len == 0) {
  606. if (!waiter.ReadStdin(pending_write, &pending_write_len,
  607. sizeof(pending_write))) {
  608. return false;
  609. }
  610. if (pending_write_len == 0) {
  611. #if !defined(OPENSSL_WINDOWS)
  612. shutdown(sock, SHUT_WR);
  613. #else
  614. shutdown(sock, SD_SEND);
  615. #endif
  616. continue;
  617. }
  618. }
  619. int ssl_ret =
  620. SSL_write(ssl, pending_write, static_cast<int>(pending_write_len));
  621. if (ssl_ret <= 0) {
  622. int ssl_err = SSL_get_error(ssl, ssl_ret);
  623. if (ssl_err == SSL_ERROR_WANT_WRITE) {
  624. continue;
  625. }
  626. PrintSSLError(stderr, "Error while writing", ssl_err, ssl_ret);
  627. return false;
  628. }
  629. if (ssl_ret != static_cast<int>(pending_write_len)) {
  630. fprintf(stderr, "Short write from SSL_write.\n");
  631. return false;
  632. }
  633. pending_write_len = 0;
  634. }
  635. if (socket_ready) {
  636. for (;;) {
  637. uint8_t buffer[512];
  638. int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
  639. if (ssl_ret < 0) {
  640. int ssl_err = SSL_get_error(ssl, ssl_ret);
  641. if (ssl_err == SSL_ERROR_WANT_READ) {
  642. break;
  643. }
  644. PrintSSLError(stderr, "Error while reading", ssl_err, ssl_ret);
  645. return false;
  646. } else if (ssl_ret == 0) {
  647. return true;
  648. }
  649. ssize_t n;
  650. do {
  651. n = BORINGSSL_WRITE(1, buffer, ssl_ret);
  652. } while (n == -1 && errno == EINTR);
  653. if (n != ssl_ret) {
  654. fprintf(stderr, "Short write to stderr.\n");
  655. return false;
  656. }
  657. }
  658. }
  659. }
  660. }
  661. // SocketLineReader wraps a small buffer around a socket for line-orientated
  662. // protocols.
  663. class SocketLineReader {
  664. public:
  665. explicit SocketLineReader(int sock) : sock_(sock) {}
  666. // Next reads a '\n'- or '\r\n'-terminated line from the socket and, on
  667. // success, sets |*out_line| to it and returns true. Otherwise it returns
  668. // false.
  669. bool Next(std::string *out_line) {
  670. for (;;) {
  671. for (size_t i = 0; i < buf_len_; i++) {
  672. if (buf_[i] != '\n') {
  673. continue;
  674. }
  675. size_t length = i;
  676. if (i > 0 && buf_[i - 1] == '\r') {
  677. length--;
  678. }
  679. out_line->assign(buf_, length);
  680. buf_len_ -= i + 1;
  681. OPENSSL_memmove(buf_, &buf_[i + 1], buf_len_);
  682. return true;
  683. }
  684. if (buf_len_ == sizeof(buf_)) {
  685. fprintf(stderr, "Received line too long!\n");
  686. return false;
  687. }
  688. ssize_t n;
  689. do {
  690. n = recv(sock_, &buf_[buf_len_], sizeof(buf_) - buf_len_, 0);
  691. } while (n == -1 && errno == EINTR);
  692. if (n < 0) {
  693. fprintf(stderr, "Read error from socket\n");
  694. return false;
  695. }
  696. buf_len_ += n;
  697. }
  698. }
  699. // ReadSMTPReply reads one or more lines that make up an SMTP reply. On
  700. // success, it sets |*out_code| to the reply's code (e.g. 250) and
  701. // |*out_content| to the body of the reply (e.g. "OK") and returns true.
  702. // Otherwise it returns false.
  703. //
  704. // See https://tools.ietf.org/html/rfc821#page-48
  705. bool ReadSMTPReply(unsigned *out_code, std::string *out_content) {
  706. out_content->clear();
  707. // kMaxLines is the maximum number of lines that we'll accept in an SMTP
  708. // reply.
  709. static const unsigned kMaxLines = 512;
  710. for (unsigned i = 0; i < kMaxLines; i++) {
  711. std::string line;
  712. if (!Next(&line)) {
  713. return false;
  714. }
  715. if (line.size() < 4) {
  716. fprintf(stderr, "Short line from SMTP server: %s\n", line.c_str());
  717. return false;
  718. }
  719. const std::string code_str = line.substr(0, 3);
  720. char *endptr;
  721. const unsigned long code = strtoul(code_str.c_str(), &endptr, 10);
  722. if (*endptr || code > UINT_MAX) {
  723. fprintf(stderr, "Failed to parse code from line: %s\n", line.c_str());
  724. return false;
  725. }
  726. if (i == 0) {
  727. *out_code = code;
  728. } else if (code != *out_code) {
  729. fprintf(stderr,
  730. "Reply code varied within a single reply: was %u, now %u\n",
  731. *out_code, static_cast<unsigned>(code));
  732. return false;
  733. }
  734. if (line[3] == ' ') {
  735. // End of reply.
  736. *out_content += line.substr(4, std::string::npos);
  737. return true;
  738. } else if (line[3] == '-') {
  739. // Another line of reply will follow this one.
  740. *out_content += line.substr(4, std::string::npos);
  741. out_content->push_back('\n');
  742. } else {
  743. fprintf(stderr, "Bad character after code in SMTP reply: %s\n",
  744. line.c_str());
  745. return false;
  746. }
  747. }
  748. fprintf(stderr, "Rejected SMTP reply of more then %u lines\n", kMaxLines);
  749. return false;
  750. }
  751. private:
  752. const int sock_;
  753. char buf_[512];
  754. size_t buf_len_ = 0;
  755. };
  756. // SendAll writes |data_len| bytes from |data| to |sock|. It returns true on
  757. // success and false otherwise.
  758. static bool SendAll(int sock, const char *data, size_t data_len) {
  759. size_t done = 0;
  760. while (done < data_len) {
  761. ssize_t n;
  762. do {
  763. n = send(sock, &data[done], data_len - done, 0);
  764. } while (n == -1 && errno == EINTR);
  765. if (n < 0) {
  766. fprintf(stderr, "Error while writing to socket\n");
  767. return false;
  768. }
  769. done += n;
  770. }
  771. return true;
  772. }
  773. bool DoSMTPStartTLS(int sock) {
  774. SocketLineReader line_reader(sock);
  775. unsigned code_220 = 0;
  776. std::string reply_220;
  777. if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
  778. return false;
  779. }
  780. if (code_220 != 220) {
  781. fprintf(stderr, "Expected 220 line from SMTP server but got code %u\n",
  782. code_220);
  783. return false;
  784. }
  785. static const char kHelloLine[] = "EHLO BoringSSL\r\n";
  786. if (!SendAll(sock, kHelloLine, sizeof(kHelloLine) - 1)) {
  787. return false;
  788. }
  789. unsigned code_250 = 0;
  790. std::string reply_250;
  791. if (!line_reader.ReadSMTPReply(&code_250, &reply_250)) {
  792. return false;
  793. }
  794. if (code_250 != 250) {
  795. fprintf(stderr, "Expected 250 line after EHLO but got code %u\n", code_250);
  796. return false;
  797. }
  798. // https://tools.ietf.org/html/rfc1869#section-4.3
  799. if (("\n" + reply_250 + "\n").find("\nSTARTTLS\n") == std::string::npos) {
  800. fprintf(stderr, "Server does not support STARTTLS\n");
  801. return false;
  802. }
  803. static const char kSTARTTLSLine[] = "STARTTLS\r\n";
  804. if (!SendAll(sock, kSTARTTLSLine, sizeof(kSTARTTLSLine) - 1)) {
  805. return false;
  806. }
  807. if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
  808. return false;
  809. }
  810. if (code_220 != 220) {
  811. fprintf(
  812. stderr,
  813. "Expected 220 line from SMTP server after STARTTLS, but got code %u\n",
  814. code_220);
  815. return false;
  816. }
  817. return true;
  818. }
  819. bool DoHTTPTunnel(int sock, const std::string &hostname_and_port) {
  820. std::string hostname, port;
  821. SplitHostPort(&hostname, &port, hostname_and_port);
  822. fprintf(stderr, "Establishing HTTP tunnel to %s:%s.\n", hostname.c_str(),
  823. port.c_str());
  824. char buf[1024];
  825. snprintf(buf, sizeof(buf), "CONNECT %s:%s HTTP/1.0\r\n\r\n", hostname.c_str(),
  826. port.c_str());
  827. if (!SendAll(sock, buf, strlen(buf))) {
  828. return false;
  829. }
  830. SocketLineReader line_reader(sock);
  831. // Read until an empty line, signaling the end of the HTTP response.
  832. std::string line;
  833. for (;;) {
  834. if (!line_reader.Next(&line)) {
  835. return false;
  836. }
  837. if (line.empty()) {
  838. return true;
  839. }
  840. fprintf(stderr, "%s\n", line.c_str());
  841. }
  842. }