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