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


grpc
Author(s):
autogenerated on Fri May 16 2025 03:00:40