You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

715 regels
19 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. #include <openssl/base.h>
  15. #include <string>
  16. #include <vector>
  17. #include <errno.h>
  18. #include <limits.h>
  19. #include <stddef.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <sys/types.h>
  23. #if !defined(OPENSSL_WINDOWS)
  24. #include <arpa/inet.h>
  25. #include <fcntl.h>
  26. #include <netdb.h>
  27. #include <netinet/in.h>
  28. #include <sys/select.h>
  29. #include <sys/socket.h>
  30. #include <unistd.h>
  31. #else
  32. #include <io.h>
  33. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  34. #include <winsock2.h>
  35. #include <ws2tcpip.h>
  36. OPENSSL_MSVC_PRAGMA(warning(pop))
  37. typedef int ssize_t;
  38. OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
  39. #endif
  40. #include <openssl/err.h>
  41. #include <openssl/ssl.h>
  42. #include <openssl/x509.h>
  43. #include "../crypto/internal.h"
  44. #include "internal.h"
  45. #include "transport_common.h"
  46. #if !defined(OPENSSL_WINDOWS)
  47. static int closesocket(int sock) {
  48. return close(sock);
  49. }
  50. #endif
  51. bool InitSocketLibrary() {
  52. #if defined(OPENSSL_WINDOWS)
  53. WSADATA wsaData;
  54. int err = WSAStartup(MAKEWORD(2, 2), &wsaData);
  55. if (err != 0) {
  56. fprintf(stderr, "WSAStartup failed with error %d\n", err);
  57. return false;
  58. }
  59. #endif
  60. return true;
  61. }
  62. static void SplitHostPort(std::string *out_hostname, std::string *out_port,
  63. const std::string &hostname_and_port) {
  64. size_t colon_offset = hostname_and_port.find_last_of(':');
  65. const size_t bracket_offset = hostname_and_port.find_last_of(']');
  66. std::string hostname, port;
  67. // An IPv6 literal may have colons internally, guarded by square brackets.
  68. if (bracket_offset != std::string::npos &&
  69. colon_offset != std::string::npos && bracket_offset > colon_offset) {
  70. colon_offset = std::string::npos;
  71. }
  72. if (colon_offset == std::string::npos) {
  73. *out_hostname = hostname_and_port;
  74. *out_port = "443";
  75. } else {
  76. *out_hostname = hostname_and_port.substr(0, colon_offset);
  77. *out_port = hostname_and_port.substr(colon_offset + 1);
  78. }
  79. }
  80. // Connect sets |*out_sock| to be a socket connected to the destination given
  81. // in |hostname_and_port|, which should be of the form "www.example.com:123".
  82. // It returns true on success and false otherwise.
  83. bool Connect(int *out_sock, const std::string &hostname_and_port) {
  84. std::string hostname, port;
  85. SplitHostPort(&hostname, &port, hostname_and_port);
  86. // Handle IPv6 literals.
  87. if (hostname.size() >= 2 && hostname[0] == '[' &&
  88. hostname[hostname.size() - 1] == ']') {
  89. hostname = hostname.substr(1, hostname.size() - 2);
  90. }
  91. struct addrinfo hint, *result;
  92. OPENSSL_memset(&hint, 0, sizeof(hint));
  93. hint.ai_family = AF_UNSPEC;
  94. hint.ai_socktype = SOCK_STREAM;
  95. int ret = getaddrinfo(hostname.c_str(), port.c_str(), &hint, &result);
  96. if (ret != 0) {
  97. fprintf(stderr, "getaddrinfo returned: %s\n", gai_strerror(ret));
  98. return false;
  99. }
  100. bool ok = false;
  101. char buf[256];
  102. *out_sock =
  103. socket(result->ai_family, result->ai_socktype, result->ai_protocol);
  104. if (*out_sock < 0) {
  105. perror("socket");
  106. goto out;
  107. }
  108. switch (result->ai_family) {
  109. case AF_INET: {
  110. struct sockaddr_in *sin =
  111. reinterpret_cast<struct sockaddr_in *>(result->ai_addr);
  112. fprintf(stderr, "Connecting to %s:%d\n",
  113. inet_ntop(result->ai_family, &sin->sin_addr, buf, sizeof(buf)),
  114. ntohs(sin->sin_port));
  115. break;
  116. }
  117. case AF_INET6: {
  118. struct sockaddr_in6 *sin6 =
  119. reinterpret_cast<struct sockaddr_in6 *>(result->ai_addr);
  120. fprintf(stderr, "Connecting to [%s]:%d\n",
  121. inet_ntop(result->ai_family, &sin6->sin6_addr, buf, sizeof(buf)),
  122. ntohs(sin6->sin6_port));
  123. break;
  124. }
  125. }
  126. if (connect(*out_sock, result->ai_addr, result->ai_addrlen) != 0) {
  127. perror("connect");
  128. goto out;
  129. }
  130. ok = true;
  131. out:
  132. freeaddrinfo(result);
  133. return ok;
  134. }
  135. Listener::~Listener() {
  136. if (server_sock_ >= 0) {
  137. closesocket(server_sock_);
  138. }
  139. }
  140. bool Listener::Init(const std::string &port) {
  141. if (server_sock_ >= 0) {
  142. return false;
  143. }
  144. struct sockaddr_in6 addr;
  145. OPENSSL_memset(&addr, 0, sizeof(addr));
  146. addr.sin6_family = AF_INET6;
  147. addr.sin6_addr = IN6ADDR_ANY_INIT;
  148. addr.sin6_port = htons(atoi(port.c_str()));
  149. #if defined(OPENSSL_WINDOWS)
  150. const BOOL enable = TRUE;
  151. #else
  152. const int enable = 1;
  153. #endif
  154. server_sock_ = socket(addr.sin6_family, SOCK_STREAM, 0);
  155. if (server_sock_ < 0) {
  156. perror("socket");
  157. return false;
  158. }
  159. if (setsockopt(server_sock_, SOL_SOCKET, SO_REUSEADDR, (const char *)&enable,
  160. sizeof(enable)) < 0) {
  161. perror("setsockopt");
  162. return false;
  163. }
  164. if (bind(server_sock_, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
  165. perror("connect");
  166. return false;
  167. }
  168. listen(server_sock_, SOMAXCONN);
  169. return true;
  170. }
  171. bool Listener::Accept(int *out_sock) {
  172. struct sockaddr_in6 addr;
  173. socklen_t addr_len = sizeof(addr);
  174. *out_sock = accept(server_sock_, (struct sockaddr *)&addr, &addr_len);
  175. return *out_sock >= 0;
  176. }
  177. bool VersionFromString(uint16_t *out_version, const std::string &version) {
  178. if (version == "ssl3") {
  179. *out_version = SSL3_VERSION;
  180. return true;
  181. } else if (version == "tls1" || version == "tls1.0") {
  182. *out_version = TLS1_VERSION;
  183. return true;
  184. } else if (version == "tls1.1") {
  185. *out_version = TLS1_1_VERSION;
  186. return true;
  187. } else if (version == "tls1.2") {
  188. *out_version = TLS1_2_VERSION;
  189. return true;
  190. } else if (version == "tls1.3") {
  191. *out_version = TLS1_3_VERSION;
  192. return true;
  193. }
  194. return false;
  195. }
  196. static const char *SignatureAlgorithmToString(uint16_t version, uint16_t sigalg) {
  197. const bool is_tls12 = version == TLS1_2_VERSION || version == DTLS1_2_VERSION;
  198. switch (sigalg) {
  199. case SSL_SIGN_RSA_PKCS1_SHA1:
  200. return "rsa_pkcs1_sha1";
  201. case SSL_SIGN_RSA_PKCS1_SHA256:
  202. return "rsa_pkcs1_sha256";
  203. case SSL_SIGN_RSA_PKCS1_SHA384:
  204. return "rsa_pkcs1_sha384";
  205. case SSL_SIGN_RSA_PKCS1_SHA512:
  206. return "rsa_pkcs1_sha512";
  207. case SSL_SIGN_ECDSA_SHA1:
  208. return "ecdsa_sha1";
  209. case SSL_SIGN_ECDSA_SECP256R1_SHA256:
  210. return is_tls12 ? "ecdsa_sha256" : "ecdsa_secp256r1_sha256";
  211. case SSL_SIGN_ECDSA_SECP384R1_SHA384:
  212. return is_tls12 ? "ecdsa_sha384" : "ecdsa_secp384r1_sha384";
  213. case SSL_SIGN_ECDSA_SECP521R1_SHA512:
  214. return is_tls12 ? "ecdsa_sha512" : "ecdsa_secp521r1_sha512";
  215. case SSL_SIGN_RSA_PSS_SHA256:
  216. return "rsa_pss_sha256";
  217. case SSL_SIGN_RSA_PSS_SHA384:
  218. return "rsa_pss_sha384";
  219. case SSL_SIGN_RSA_PSS_SHA512:
  220. return "rsa_pss_sha512";
  221. case SSL_SIGN_ED25519:
  222. return "ed25519";
  223. default:
  224. return "(unknown)";
  225. }
  226. }
  227. void PrintConnectionInfo(const SSL *ssl) {
  228. const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
  229. fprintf(stderr, " Version: %s\n", SSL_get_version(ssl));
  230. fprintf(stderr, " Resumed session: %s\n",
  231. SSL_session_reused(ssl) ? "yes" : "no");
  232. fprintf(stderr, " Cipher: %s\n", SSL_CIPHER_standard_name(cipher));
  233. uint16_t curve = SSL_get_curve_id(ssl);
  234. if (curve != 0) {
  235. fprintf(stderr, " ECDHE curve: %s\n", SSL_get_curve_name(curve));
  236. }
  237. uint16_t sigalg = SSL_get_peer_signature_algorithm(ssl);
  238. if (sigalg != 0) {
  239. fprintf(stderr, " Signature algorithm: %s\n",
  240. SignatureAlgorithmToString(SSL_version(ssl), sigalg));
  241. }
  242. fprintf(stderr, " Secure renegotiation: %s\n",
  243. SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no");
  244. fprintf(stderr, " Extended master secret: %s\n",
  245. SSL_get_extms_support(ssl) ? "yes" : "no");
  246. const uint8_t *next_proto;
  247. unsigned next_proto_len;
  248. SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
  249. fprintf(stderr, " Next protocol negotiated: %.*s\n", next_proto_len,
  250. next_proto);
  251. const uint8_t *alpn;
  252. unsigned alpn_len;
  253. SSL_get0_alpn_selected(ssl, &alpn, &alpn_len);
  254. fprintf(stderr, " ALPN protocol: %.*s\n", alpn_len, alpn);
  255. const char *host_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  256. if (host_name != nullptr && SSL_is_server(ssl)) {
  257. fprintf(stderr, " Client sent SNI: %s\n", host_name);
  258. }
  259. if (!SSL_is_server(ssl)) {
  260. const uint8_t *ocsp_staple;
  261. size_t ocsp_staple_len;
  262. SSL_get0_ocsp_response(ssl, &ocsp_staple, &ocsp_staple_len);
  263. fprintf(stderr, " OCSP staple: %s\n", ocsp_staple_len > 0 ? "yes" : "no");
  264. const uint8_t *sct_list;
  265. size_t sct_list_len;
  266. SSL_get0_signed_cert_timestamp_list(ssl, &sct_list, &sct_list_len);
  267. fprintf(stderr, " SCT list: %s\n", sct_list_len > 0 ? "yes" : "no");
  268. }
  269. fprintf(stderr, " Early data: %s\n",
  270. SSL_early_data_accepted(ssl) ? "yes" : "no");
  271. // Print the server cert subject and issuer names.
  272. bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(ssl));
  273. if (peer != nullptr) {
  274. fprintf(stderr, " Cert subject: ");
  275. X509_NAME_print_ex_fp(stderr, X509_get_subject_name(peer.get()), 0,
  276. XN_FLAG_ONELINE);
  277. fprintf(stderr, "\n Cert issuer: ");
  278. X509_NAME_print_ex_fp(stderr, X509_get_issuer_name(peer.get()), 0,
  279. XN_FLAG_ONELINE);
  280. fprintf(stderr, "\n");
  281. }
  282. }
  283. bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
  284. bool ok;
  285. #if defined(OPENSSL_WINDOWS)
  286. u_long arg = is_non_blocking;
  287. ok = 0 == ioctlsocket(sock, FIONBIO, &arg);
  288. #else
  289. int flags = fcntl(sock, F_GETFL, 0);
  290. if (flags < 0) {
  291. return false;
  292. }
  293. if (is_non_blocking) {
  294. flags |= O_NONBLOCK;
  295. } else {
  296. flags &= ~O_NONBLOCK;
  297. }
  298. ok = 0 == fcntl(sock, F_SETFL, flags);
  299. #endif
  300. if (!ok) {
  301. fprintf(stderr, "Failed to set socket non-blocking.\n");
  302. }
  303. return ok;
  304. }
  305. static bool SocketSelect(int sock, bool stdin_open, bool *socket_ready,
  306. bool *stdin_ready) {
  307. #if !defined(OPENSSL_WINDOWS)
  308. fd_set read_fds;
  309. FD_ZERO(&read_fds);
  310. if (stdin_open) {
  311. FD_SET(0, &read_fds);
  312. }
  313. FD_SET(sock, &read_fds);
  314. if (select(sock + 1, &read_fds, NULL, NULL, NULL) <= 0) {
  315. perror("select");
  316. return false;
  317. }
  318. if (FD_ISSET(0, &read_fds)) {
  319. *stdin_ready = true;
  320. }
  321. if (FD_ISSET(sock, &read_fds)) {
  322. *socket_ready = true;
  323. }
  324. return true;
  325. #else
  326. WSAEVENT socket_handle = WSACreateEvent();
  327. if (socket_handle == WSA_INVALID_EVENT ||
  328. WSAEventSelect(sock, socket_handle, FD_READ) != 0) {
  329. WSACloseEvent(socket_handle);
  330. return false;
  331. }
  332. HANDLE read_fds[2];
  333. read_fds[0] = socket_handle;
  334. read_fds[1] = GetStdHandle(STD_INPUT_HANDLE);
  335. switch (
  336. WaitForMultipleObjects(stdin_open ? 2 : 1, read_fds, FALSE, INFINITE)) {
  337. case WAIT_OBJECT_0 + 0:
  338. *socket_ready = true;
  339. break;
  340. case WAIT_OBJECT_0 + 1:
  341. *stdin_ready = true;
  342. break;
  343. case WAIT_TIMEOUT:
  344. break;
  345. default:
  346. WSACloseEvent(socket_handle);
  347. return false;
  348. }
  349. WSACloseEvent(socket_handle);
  350. return true;
  351. #endif
  352. }
  353. // PrintErrorCallback is a callback function from OpenSSL's
  354. // |ERR_print_errors_cb| that writes errors to a given |FILE*|.
  355. int PrintErrorCallback(const char *str, size_t len, void *ctx) {
  356. fwrite(str, len, 1, reinterpret_cast<FILE*>(ctx));
  357. return 1;
  358. }
  359. bool TransferData(SSL *ssl, int sock) {
  360. if (!SocketSetNonBlocking(sock, true)) {
  361. return false;
  362. }
  363. bool stdin_open = true;
  364. for (;;) {
  365. bool socket_ready = false;
  366. bool stdin_ready = false;
  367. if (!SocketSelect(sock, stdin_open, &socket_ready, &stdin_ready)) {
  368. return false;
  369. }
  370. if (stdin_ready) {
  371. uint8_t buffer[512];
  372. ssize_t n;
  373. do {
  374. n = BORINGSSL_READ(0, buffer, sizeof(buffer));
  375. } while (n == -1 && errno == EINTR);
  376. if (n == 0) {
  377. stdin_open = false;
  378. #if !defined(OPENSSL_WINDOWS)
  379. shutdown(sock, SHUT_WR);
  380. #else
  381. shutdown(sock, SD_SEND);
  382. #endif
  383. continue;
  384. } else if (n < 0) {
  385. perror("read from stdin");
  386. return false;
  387. }
  388. // On Windows, SocketSelect ends up setting sock to non-blocking.
  389. #if !defined(OPENSSL_WINDOWS)
  390. if (!SocketSetNonBlocking(sock, false)) {
  391. return false;
  392. }
  393. #endif
  394. int ssl_ret = SSL_write(ssl, buffer, n);
  395. if (!SocketSetNonBlocking(sock, true)) {
  396. return false;
  397. }
  398. if (ssl_ret <= 0) {
  399. int ssl_err = SSL_get_error(ssl, ssl_ret);
  400. fprintf(stderr, "Error while writing: %d\n", ssl_err);
  401. ERR_print_errors_cb(PrintErrorCallback, stderr);
  402. return false;
  403. } else if (ssl_ret != n) {
  404. fprintf(stderr, "Short write from SSL_write.\n");
  405. return false;
  406. }
  407. }
  408. if (socket_ready) {
  409. uint8_t buffer[512];
  410. int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
  411. if (ssl_ret < 0) {
  412. int ssl_err = SSL_get_error(ssl, ssl_ret);
  413. if (ssl_err == SSL_ERROR_WANT_READ) {
  414. continue;
  415. }
  416. fprintf(stderr, "Error while reading: %d\n", ssl_err);
  417. ERR_print_errors_cb(PrintErrorCallback, stderr);
  418. return false;
  419. } else if (ssl_ret == 0) {
  420. return true;
  421. }
  422. ssize_t n;
  423. do {
  424. n = BORINGSSL_WRITE(1, buffer, ssl_ret);
  425. } while (n == -1 && errno == EINTR);
  426. if (n != ssl_ret) {
  427. fprintf(stderr, "Short write to stderr.\n");
  428. return false;
  429. }
  430. }
  431. }
  432. }
  433. // SocketLineReader wraps a small buffer around a socket for line-orientated
  434. // protocols.
  435. class SocketLineReader {
  436. public:
  437. explicit SocketLineReader(int sock) : sock_(sock) {}
  438. // Next reads a '\n'- or '\r\n'-terminated line from the socket and, on
  439. // success, sets |*out_line| to it and returns true. Otherwise it returns
  440. // false.
  441. bool Next(std::string *out_line) {
  442. for (;;) {
  443. for (size_t i = 0; i < buf_len_; i++) {
  444. if (buf_[i] != '\n') {
  445. continue;
  446. }
  447. size_t length = i;
  448. if (i > 0 && buf_[i - 1] == '\r') {
  449. length--;
  450. }
  451. out_line->assign(buf_, length);
  452. buf_len_ -= i + 1;
  453. OPENSSL_memmove(buf_, &buf_[i + 1], buf_len_);
  454. return true;
  455. }
  456. if (buf_len_ == sizeof(buf_)) {
  457. fprintf(stderr, "Received line too long!\n");
  458. return false;
  459. }
  460. ssize_t n;
  461. do {
  462. n = recv(sock_, &buf_[buf_len_], sizeof(buf_) - buf_len_, 0);
  463. } while (n == -1 && errno == EINTR);
  464. if (n < 0) {
  465. fprintf(stderr, "Read error from socket\n");
  466. return false;
  467. }
  468. buf_len_ += n;
  469. }
  470. }
  471. // ReadSMTPReply reads one or more lines that make up an SMTP reply. On
  472. // success, it sets |*out_code| to the reply's code (e.g. 250) and
  473. // |*out_content| to the body of the reply (e.g. "OK") and returns true.
  474. // Otherwise it returns false.
  475. //
  476. // See https://tools.ietf.org/html/rfc821#page-48
  477. bool ReadSMTPReply(unsigned *out_code, std::string *out_content) {
  478. out_content->clear();
  479. // kMaxLines is the maximum number of lines that we'll accept in an SMTP
  480. // reply.
  481. static const unsigned kMaxLines = 512;
  482. for (unsigned i = 0; i < kMaxLines; i++) {
  483. std::string line;
  484. if (!Next(&line)) {
  485. return false;
  486. }
  487. if (line.size() < 4) {
  488. fprintf(stderr, "Short line from SMTP server: %s\n", line.c_str());
  489. return false;
  490. }
  491. const std::string code_str = line.substr(0, 3);
  492. char *endptr;
  493. const unsigned long code = strtoul(code_str.c_str(), &endptr, 10);
  494. if (*endptr || code > UINT_MAX) {
  495. fprintf(stderr, "Failed to parse code from line: %s\n", line.c_str());
  496. return false;
  497. }
  498. if (i == 0) {
  499. *out_code = code;
  500. } else if (code != *out_code) {
  501. fprintf(stderr,
  502. "Reply code varied within a single reply: was %u, now %u\n",
  503. *out_code, static_cast<unsigned>(code));
  504. return false;
  505. }
  506. if (line[3] == ' ') {
  507. // End of reply.
  508. *out_content += line.substr(4, std::string::npos);
  509. return true;
  510. } else if (line[3] == '-') {
  511. // Another line of reply will follow this one.
  512. *out_content += line.substr(4, std::string::npos);
  513. out_content->push_back('\n');
  514. } else {
  515. fprintf(stderr, "Bad character after code in SMTP reply: %s\n",
  516. line.c_str());
  517. return false;
  518. }
  519. }
  520. fprintf(stderr, "Rejected SMTP reply of more then %u lines\n", kMaxLines);
  521. return false;
  522. }
  523. private:
  524. const int sock_;
  525. char buf_[512];
  526. size_t buf_len_ = 0;
  527. };
  528. // SendAll writes |data_len| bytes from |data| to |sock|. It returns true on
  529. // success and false otherwise.
  530. static bool SendAll(int sock, const char *data, size_t data_len) {
  531. size_t done = 0;
  532. while (done < data_len) {
  533. ssize_t n;
  534. do {
  535. n = send(sock, &data[done], data_len - done, 0);
  536. } while (n == -1 && errno == EINTR);
  537. if (n < 0) {
  538. fprintf(stderr, "Error while writing to socket\n");
  539. return false;
  540. }
  541. done += n;
  542. }
  543. return true;
  544. }
  545. bool DoSMTPStartTLS(int sock) {
  546. SocketLineReader line_reader(sock);
  547. unsigned code_220 = 0;
  548. std::string reply_220;
  549. if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
  550. return false;
  551. }
  552. if (code_220 != 220) {
  553. fprintf(stderr, "Expected 220 line from SMTP server but got code %u\n",
  554. code_220);
  555. return false;
  556. }
  557. static const char kHelloLine[] = "EHLO BoringSSL\r\n";
  558. if (!SendAll(sock, kHelloLine, sizeof(kHelloLine) - 1)) {
  559. return false;
  560. }
  561. unsigned code_250 = 0;
  562. std::string reply_250;
  563. if (!line_reader.ReadSMTPReply(&code_250, &reply_250)) {
  564. return false;
  565. }
  566. if (code_250 != 250) {
  567. fprintf(stderr, "Expected 250 line after EHLO but got code %u\n", code_250);
  568. return false;
  569. }
  570. // https://tools.ietf.org/html/rfc1869#section-4.3
  571. if (("\n" + reply_250 + "\n").find("\nSTARTTLS\n") == std::string::npos) {
  572. fprintf(stderr, "Server does not support STARTTLS\n");
  573. return false;
  574. }
  575. static const char kSTARTTLSLine[] = "STARTTLS\r\n";
  576. if (!SendAll(sock, kSTARTTLSLine, sizeof(kSTARTTLSLine) - 1)) {
  577. return false;
  578. }
  579. if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
  580. return false;
  581. }
  582. if (code_220 != 220) {
  583. fprintf(
  584. stderr,
  585. "Expected 220 line from SMTP server after STARTTLS, but got code %u\n",
  586. code_220);
  587. return false;
  588. }
  589. return true;
  590. }
  591. bool DoHTTPTunnel(int sock, const std::string &hostname_and_port) {
  592. std::string hostname, port;
  593. SplitHostPort(&hostname, &port, hostname_and_port);
  594. fprintf(stderr, "Establishing HTTP tunnel to %s:%s.\n", hostname.c_str(),
  595. port.c_str());
  596. char buf[1024];
  597. snprintf(buf, sizeof(buf), "CONNECT %s:%s HTTP/1.0\r\n\r\n", hostname.c_str(),
  598. port.c_str());
  599. if (!SendAll(sock, buf, strlen(buf))) {
  600. return false;
  601. }
  602. SocketLineReader line_reader(sock);
  603. // Read until an empty line, signaling the end of the HTTP response.
  604. std::string line;
  605. for (;;) {
  606. if (!line_reader.Next(&line)) {
  607. return false;
  608. }
  609. if (line.empty()) {
  610. return true;
  611. }
  612. fprintf(stderr, "%s\n", line.c_str());
  613. }
  614. }