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