Enable EOR flag configuration for folly::AsyncSocket.
[folly.git] / folly / io / async / AsyncSSLSocket.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/io/async/AsyncSSLSocket.h>
18
19 #include <folly/io/async/EventBase.h>
20 #include <folly/portability/Sockets.h>
21
22 #include <boost/noncopyable.hpp>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <openssl/asn1.h>
26 #include <openssl/err.h>
27 #include <openssl/ssl.h>
28 #include <sys/types.h>
29 #include <chrono>
30
31 #include <folly/Bits.h>
32 #include <folly/SocketAddress.h>
33 #include <folly/SpinLock.h>
34 #include <folly/io/Cursor.h>
35 #include <folly/io/IOBuf.h>
36 #include <folly/portability/OpenSSL.h>
37 #include <folly/portability/Unistd.h>
38
39 using folly::SocketAddress;
40 using folly::SSLContext;
41 using std::string;
42 using std::shared_ptr;
43
44 using folly::Endian;
45 using folly::IOBuf;
46 using folly::SpinLock;
47 using folly::SpinLockGuard;
48 using folly::io::Cursor;
49 using std::unique_ptr;
50 using std::bind;
51
52 namespace {
53 using folly::AsyncSocket;
54 using folly::AsyncSocketException;
55 using folly::AsyncSSLSocket;
56 using folly::Optional;
57 using folly::SSLContext;
58 // For OpenSSL portability API
59 using namespace folly::ssl;
60 using folly::ssl::OpenSSLUtils;
61
62 // We have one single dummy SSL context so that we can implement attach
63 // and detach methods in a thread safe fashion without modifying opnessl.
64 static SSLContext *dummyCtx = nullptr;
65 static SpinLock dummyCtxLock;
66
67 // If given min write size is less than this, buffer will be allocated on
68 // stack, otherwise it is allocated on heap
69 const size_t MAX_STACK_BUF_SIZE = 2048;
70
71 // This converts "illegal" shutdowns into ZERO_RETURN
72 inline bool zero_return(int error, int rc) {
73   return (error == SSL_ERROR_ZERO_RETURN || (rc == 0 && errno == 0));
74 }
75
76 class AsyncSSLSocketConnector: public AsyncSocket::ConnectCallback,
77                                 public AsyncSSLSocket::HandshakeCB {
78
79  private:
80   AsyncSSLSocket *sslSocket_;
81   AsyncSSLSocket::ConnectCallback *callback_;
82   int timeout_;
83   int64_t startTime_;
84
85  protected:
86   ~AsyncSSLSocketConnector() override {}
87
88  public:
89   AsyncSSLSocketConnector(AsyncSSLSocket *sslSocket,
90                            AsyncSocket::ConnectCallback *callback,
91                            int timeout) :
92       sslSocket_(sslSocket),
93       callback_(callback),
94       timeout_(timeout),
95       startTime_(std::chrono::duration_cast<std::chrono::milliseconds>(
96                    std::chrono::steady_clock::now().time_since_epoch()).count()) {
97   }
98
99   void connectSuccess() noexcept override {
100     VLOG(7) << "client socket connected";
101
102     int64_t timeoutLeft = 0;
103     if (timeout_ > 0) {
104       auto curTime = std::chrono::duration_cast<std::chrono::milliseconds>(
105         std::chrono::steady_clock::now().time_since_epoch()).count();
106
107       timeoutLeft = timeout_ - (curTime - startTime_);
108       if (timeoutLeft <= 0) {
109         AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
110                                 "SSL connect timed out");
111         fail(ex);
112         delete this;
113         return;
114       }
115     }
116     sslSocket_->sslConn(this, std::chrono::milliseconds(timeoutLeft));
117   }
118
119   void connectErr(const AsyncSocketException& ex) noexcept override {
120     VLOG(1) << "TCP connect failed: " << ex.what();
121     fail(ex);
122     delete this;
123   }
124
125   void handshakeSuc(AsyncSSLSocket* /* sock */) noexcept override {
126     VLOG(7) << "client handshake success";
127     if (callback_) {
128       callback_->connectSuccess();
129     }
130     delete this;
131   }
132
133   void handshakeErr(AsyncSSLSocket* /* socket */,
134                     const AsyncSocketException& ex) noexcept override {
135     VLOG(1) << "client handshakeErr: " << ex.what();
136     fail(ex);
137     delete this;
138   }
139
140   void fail(const AsyncSocketException &ex) {
141     // fail is a noop if called twice
142     if (callback_) {
143       AsyncSSLSocket::ConnectCallback *cb = callback_;
144       callback_ = nullptr;
145
146       cb->connectErr(ex);
147       sslSocket_->closeNow();
148       // closeNow can call handshakeErr if it hasn't been called already.
149       // So this may have been deleted, no member variable access beyond this
150       // point
151       // Note that closeNow may invoke writeError callbacks if the socket had
152       // write data pending connection completion.
153     }
154   }
155 };
156
157 void setup_SSL_CTX(SSL_CTX *ctx) {
158 #ifdef SSL_MODE_RELEASE_BUFFERS
159   SSL_CTX_set_mode(ctx,
160                    SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
161                    SSL_MODE_ENABLE_PARTIAL_WRITE
162                    | SSL_MODE_RELEASE_BUFFERS
163                    );
164 #else
165   SSL_CTX_set_mode(ctx,
166                    SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
167                    SSL_MODE_ENABLE_PARTIAL_WRITE
168                    );
169 #endif
170 // SSL_CTX_set_mode is a Macro
171 #ifdef SSL_MODE_WRITE_IOVEC
172   SSL_CTX_set_mode(ctx,
173                    SSL_CTX_get_mode(ctx)
174                    | SSL_MODE_WRITE_IOVEC);
175 #endif
176
177 }
178
179 BIO_METHOD sslBioMethod;
180
181 void* initsslBioMethod(void) {
182   memcpy(&sslBioMethod, BIO_s_socket(), sizeof(sslBioMethod));
183   // override the bwrite method for MSG_EOR support
184   OpenSSLUtils::setCustomBioWriteMethod(
185       &sslBioMethod, AsyncSSLSocket::bioWrite);
186   OpenSSLUtils::setCustomBioReadMethod(&sslBioMethod, AsyncSSLSocket::bioRead);
187
188   // Note that the sslBioMethod.type and sslBioMethod.name are not
189   // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
190   // then have specific handlings. The sslWriteBioWrite should be compatible
191   // with the one in openssl.
192
193   // Return something here to enable AsyncSSLSocket to call this method using
194   // a function-scoped static.
195   return nullptr;
196 }
197
198 } // anonymous namespace
199
200 namespace folly {
201
202 /**
203  * Create a client AsyncSSLSocket
204  */
205 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
206                                EventBase* evb, bool deferSecurityNegotiation) :
207     AsyncSocket(evb),
208     ctx_(ctx),
209     handshakeTimeout_(this, evb),
210     connectionTimeout_(this, evb) {
211   init();
212   if (deferSecurityNegotiation) {
213     sslState_ = STATE_UNENCRYPTED;
214   }
215 }
216
217 /**
218  * Create a server/client AsyncSSLSocket
219  */
220 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
221                                EventBase* evb, int fd, bool server,
222                                bool deferSecurityNegotiation) :
223     AsyncSocket(evb, fd),
224     server_(server),
225     ctx_(ctx),
226     handshakeTimeout_(this, evb),
227     connectionTimeout_(this, evb) {
228   noTransparentTls_ = true;
229   init();
230   if (server) {
231     SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
232                               AsyncSSLSocket::sslInfoCallback);
233   }
234   if (deferSecurityNegotiation) {
235     sslState_ = STATE_UNENCRYPTED;
236   }
237 }
238
239 #if FOLLY_OPENSSL_HAS_SNI
240 /**
241  * Create a client AsyncSSLSocket and allow tlsext_hostname
242  * to be sent in Client Hello.
243  */
244 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
245                                  EventBase* evb,
246                                const std::string& serverName,
247                                bool deferSecurityNegotiation) :
248     AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
249   tlsextHostname_ = serverName;
250 }
251
252 /**
253  * Create a client AsyncSSLSocket from an already connected fd
254  * and allow tlsext_hostname to be sent in Client Hello.
255  */
256 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
257                                  EventBase* evb, int fd,
258                                const std::string& serverName,
259                                bool deferSecurityNegotiation) :
260     AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
261   tlsextHostname_ = serverName;
262 }
263 #endif // FOLLY_OPENSSL_HAS_SNI
264
265 AsyncSSLSocket::~AsyncSSLSocket() {
266   VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
267           << ", evb=" << eventBase_ << ", fd=" << fd_
268           << ", state=" << int(state_) << ", sslState="
269           << sslState_ << ", events=" << eventFlags_ << ")";
270 }
271
272 void AsyncSSLSocket::init() {
273   // Do this here to ensure we initialize this once before any use of
274   // AsyncSSLSocket instances and not as part of library load.
275   static const auto sslBioMethodInitializer = initsslBioMethod();
276   (void)sslBioMethodInitializer;
277
278   setup_SSL_CTX(ctx_->getSSLCtx());
279 }
280
281 void AsyncSSLSocket::closeNow() {
282   // Close the SSL connection.
283   if (ssl_ != nullptr && fd_ != -1) {
284     int rc = SSL_shutdown(ssl_);
285     if (rc == 0) {
286       rc = SSL_shutdown(ssl_);
287     }
288     if (rc < 0) {
289       ERR_clear_error();
290     }
291   }
292
293   if (sslSession_ != nullptr) {
294     SSL_SESSION_free(sslSession_);
295     sslSession_ = nullptr;
296   }
297
298   sslState_ = STATE_CLOSED;
299
300   if (handshakeTimeout_.isScheduled()) {
301     handshakeTimeout_.cancelTimeout();
302   }
303
304   DestructorGuard dg(this);
305
306   invokeHandshakeErr(
307       AsyncSocketException(
308         AsyncSocketException::END_OF_FILE,
309         "SSL connection closed locally"));
310
311   if (ssl_ != nullptr) {
312     SSL_free(ssl_);
313     ssl_ = nullptr;
314   }
315
316   // Close the socket.
317   AsyncSocket::closeNow();
318 }
319
320 void AsyncSSLSocket::shutdownWrite() {
321   // SSL sockets do not support half-shutdown, so just perform a full shutdown.
322   //
323   // (Performing a full shutdown here is more desirable than doing nothing at
324   // all.  The purpose of shutdownWrite() is normally to notify the other end
325   // of the connection that no more data will be sent.  If we do nothing, the
326   // other end will never know that no more data is coming, and this may result
327   // in protocol deadlock.)
328   close();
329 }
330
331 void AsyncSSLSocket::shutdownWriteNow() {
332   closeNow();
333 }
334
335 bool AsyncSSLSocket::good() const {
336   return (AsyncSocket::good() &&
337           (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
338            sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
339 }
340
341 // The TAsyncTransport definition of 'good' states that the transport is
342 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
343 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
344 // is connected but we haven't initiated the call to SSL_connect.
345 bool AsyncSSLSocket::connecting() const {
346   return (!server_ &&
347           (AsyncSocket::connecting() ||
348            (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
349                                      sslState_ == STATE_CONNECTING))));
350 }
351
352 std::string AsyncSSLSocket::getApplicationProtocol() noexcept {
353   const unsigned char* protoName = nullptr;
354   unsigned protoLength;
355   if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) {
356     return std::string(reinterpret_cast<const char*>(protoName), protoLength);
357   }
358   return "";
359 }
360
361 void AsyncSSLSocket::setEorTracking(bool track) {
362   if (isEorTrackingEnabled() != track) {
363     AsyncSocket::setEorTracking(track);
364     appEorByteNo_ = 0;
365     minEorRawByteNo_ = 0;
366   }
367 }
368
369 size_t AsyncSSLSocket::getRawBytesWritten() const {
370   // The bio(s) in the write path are in a chain
371   // each bio flushes to the next and finally written into the socket
372   // to get the rawBytesWritten on the socket,
373   // get the write bytes of the last bio
374   BIO *b;
375   if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
376     return 0;
377   }
378   BIO* next = BIO_next(b);
379   while (next != NULL) {
380     b = next;
381     next = BIO_next(b);
382   }
383
384   return BIO_number_written(b);
385 }
386
387 size_t AsyncSSLSocket::getRawBytesReceived() const {
388   BIO *b;
389   if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
390     return 0;
391   }
392
393   return BIO_number_read(b);
394 }
395
396
397 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
398   LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
399              << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
400              << "events=" << eventFlags_ << ", server=" << short(server_)
401              << "): " << "sslAccept/Connect() called in invalid "
402              << "state, handshake callback " << handshakeCallback_
403              << ", new callback " << callback;
404   assert(!handshakeTimeout_.isScheduled());
405   sslState_ = STATE_ERROR;
406
407   AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
408                          "sslAccept() called with socket in invalid state");
409
410   handshakeEndTime_ = std::chrono::steady_clock::now();
411   if (callback) {
412     callback->handshakeErr(this, ex);
413   }
414
415   failHandshake(__func__, ex);
416 }
417
418 void AsyncSSLSocket::sslAccept(
419     HandshakeCB* callback,
420     std::chrono::milliseconds timeout,
421     const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
422   DestructorGuard dg(this);
423   assert(eventBase_->isInEventBaseThread());
424   verifyPeer_ = verifyPeer;
425
426   // Make sure we're in the uninitialized state
427   if (!server_ || (sslState_ != STATE_UNINIT &&
428                    sslState_ != STATE_UNENCRYPTED) ||
429       handshakeCallback_ != nullptr) {
430     return invalidState(callback);
431   }
432
433   // Cache local and remote socket addresses to keep them available
434   // after socket file descriptor is closed.
435   if (cacheAddrOnFailure_ && -1 != getFd()) {
436     cacheLocalPeerAddr();
437   }
438
439   handshakeStartTime_ = std::chrono::steady_clock::now();
440   // Make end time at least >= start time.
441   handshakeEndTime_ = handshakeStartTime_;
442
443   sslState_ = STATE_ACCEPTING;
444   handshakeCallback_ = callback;
445
446   if (timeout > std::chrono::milliseconds::zero()) {
447     handshakeTimeout_.scheduleTimeout(timeout);
448   }
449
450   /* register for a read operation (waiting for CLIENT HELLO) */
451   updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
452
453   if (preReceivedData_) {
454     handleRead();
455   }
456 }
457
458 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
459 void AsyncSSLSocket::attachSSLContext(
460   const std::shared_ptr<SSLContext>& ctx) {
461
462   // Check to ensure we are in client mode. Changing a server's ssl
463   // context doesn't make sense since clients of that server would likely
464   // become confused when the server's context changes.
465   DCHECK(!server_);
466   DCHECK(!ctx_);
467   DCHECK(ctx);
468   DCHECK(ctx->getSSLCtx());
469   ctx_ = ctx;
470
471   // It's possible this could be attached before ssl_ is set up
472   if (!ssl_) {
473     return;
474   }
475
476   // In order to call attachSSLContext, detachSSLContext must have been
477   // previously called.
478   // We need to update the initial_ctx if necessary
479   auto sslCtx = ctx->getSSLCtx();
480   SSL_CTX_up_ref(sslCtx);
481 #ifndef OPENSSL_NO_TLSEXT
482   // note that detachSSLContext has already freed ssl_->initial_ctx
483   ssl_->initial_ctx = sslCtx;
484 #endif
485   // Detach sets the socket's context to the dummy context. Thus we must acquire
486   // this lock.
487   SpinLockGuard guard(dummyCtxLock);
488   SSL_set_SSL_CTX(ssl_, sslCtx);
489 }
490
491 void AsyncSSLSocket::detachSSLContext() {
492   DCHECK(ctx_);
493   ctx_.reset();
494   // It's possible for this to be called before ssl_ has been
495   // set up
496   if (!ssl_) {
497     return;
498   }
499 // Detach the initial_ctx as well.  Internally w/ OPENSSL_NO_TLSEXT
500 // it is used for session info.  It will be reattached in attachSSLContext
501 #ifndef OPENSSL_NO_TLSEXT
502   if (ssl_->initial_ctx) {
503     SSL_CTX_free(ssl_->initial_ctx);
504     ssl_->initial_ctx = nullptr;
505   }
506 #endif
507   SpinLockGuard guard(dummyCtxLock);
508   if (nullptr == dummyCtx) {
509     // We need to lazily initialize the dummy context so we don't
510     // accidentally override any programmatic settings to openssl
511     dummyCtx = new SSLContext;
512   }
513   // We must remove this socket's references to its context right now
514   // since this socket could get passed to any thread. If the context has
515   // had its locking disabled, just doing a set in attachSSLContext()
516   // would not be thread safe.
517   SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
518 }
519 #endif
520
521 #if FOLLY_OPENSSL_HAS_SNI
522 void AsyncSSLSocket::switchServerSSLContext(
523   const std::shared_ptr<SSLContext>& handshakeCtx) {
524   CHECK(server_);
525   if (sslState_ != STATE_ACCEPTING) {
526     // We log it here and allow the switch.
527     // It should not affect our re-negotiation support (which
528     // is not supported now).
529     VLOG(6) << "fd=" << getFd()
530             << " renegotation detected when switching SSL_CTX";
531   }
532
533   setup_SSL_CTX(handshakeCtx->getSSLCtx());
534   SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
535                             AsyncSSLSocket::sslInfoCallback);
536   handshakeCtx_ = handshakeCtx;
537   SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
538 }
539
540 bool AsyncSSLSocket::isServerNameMatch() const {
541   CHECK(!server_);
542
543   if (!ssl_) {
544     return false;
545   }
546
547   SSL_SESSION *ss = SSL_get_session(ssl_);
548   if (!ss) {
549     return false;
550   }
551
552   if(!ss->tlsext_hostname) {
553     return false;
554   }
555   return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
556 }
557
558 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
559   tlsextHostname_ = std::move(serverName);
560 }
561
562 #endif // FOLLY_OPENSSL_HAS_SNI
563
564 void AsyncSSLSocket::timeoutExpired() noexcept {
565   if (state_ == StateEnum::ESTABLISHED &&
566       (sslState_ == STATE_CACHE_LOOKUP ||
567        sslState_ == STATE_ASYNC_PENDING)) {
568     sslState_ = STATE_ERROR;
569     // We are expecting a callback in restartSSLAccept.  The cache lookup
570     // and rsa-call necessarily have pointers to this ssl socket, so delay
571     // the cleanup until he calls us back.
572   } else if (state_ == StateEnum::CONNECTING) {
573     assert(sslState_ == STATE_CONNECTING);
574     DestructorGuard dg(this);
575     AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
576                            "Fallback connect timed out during TFO");
577     failHandshake(__func__, ex);
578   } else {
579     assert(state_ == StateEnum::ESTABLISHED &&
580            (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
581     DestructorGuard dg(this);
582     AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
583                            (sslState_ == STATE_CONNECTING) ?
584                            "SSL connect timed out" : "SSL accept timed out");
585     failHandshake(__func__, ex);
586   }
587 }
588
589 int AsyncSSLSocket::getSSLExDataIndex() {
590   static auto index = SSL_get_ex_new_index(
591       0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
592   return index;
593 }
594
595 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
596   return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
597       getSSLExDataIndex()));
598 }
599
600 void AsyncSSLSocket::failHandshake(const char* /* fn */,
601                                    const AsyncSocketException& ex) {
602   startFail();
603   if (handshakeTimeout_.isScheduled()) {
604     handshakeTimeout_.cancelTimeout();
605   }
606   invokeHandshakeErr(ex);
607   finishFail();
608 }
609
610 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
611   handshakeEndTime_ = std::chrono::steady_clock::now();
612   if (handshakeCallback_ != nullptr) {
613     HandshakeCB* callback = handshakeCallback_;
614     handshakeCallback_ = nullptr;
615     callback->handshakeErr(this, ex);
616   }
617 }
618
619 void AsyncSSLSocket::invokeHandshakeCB() {
620   handshakeEndTime_ = std::chrono::steady_clock::now();
621   if (handshakeTimeout_.isScheduled()) {
622     handshakeTimeout_.cancelTimeout();
623   }
624   if (handshakeCallback_) {
625     HandshakeCB* callback = handshakeCallback_;
626     handshakeCallback_ = nullptr;
627     callback->handshakeSuc(this);
628   }
629 }
630
631 void AsyncSSLSocket::cacheLocalPeerAddr() {
632   SocketAddress address;
633   try {
634     getLocalAddress(&address);
635     getPeerAddress(&address);
636   } catch (const std::system_error& e) {
637     // The handle can be still valid while the connection is already closed.
638     if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
639       throw;
640     }
641   }
642 }
643
644 void AsyncSSLSocket::connect(ConnectCallback* callback,
645                               const folly::SocketAddress& address,
646                               int timeout,
647                               const OptionMap &options,
648                               const folly::SocketAddress& bindAddr)
649                               noexcept {
650   assert(!server_);
651   assert(state_ == StateEnum::UNINIT);
652   assert(sslState_ == STATE_UNINIT);
653   noTransparentTls_ = true;
654   AsyncSSLSocketConnector *connector =
655     new AsyncSSLSocketConnector(this, callback, timeout);
656   AsyncSocket::connect(connector, address, timeout, options, bindAddr);
657 }
658
659 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
660   // apply the settings specified in verifyPeer_
661   if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
662     if(ctx_->needsPeerVerification()) {
663       SSL_set_verify(ssl, ctx_->getVerificationMode(),
664         AsyncSSLSocket::sslVerifyCallback);
665     }
666   } else {
667     if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
668         verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
669       SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
670         AsyncSSLSocket::sslVerifyCallback);
671     }
672   }
673 }
674
675 bool AsyncSSLSocket::setupSSLBio() {
676   auto sslBio = BIO_new(&sslBioMethod);
677
678   if (!sslBio) {
679     return false;
680   }
681
682   OpenSSLUtils::setBioAppData(sslBio, this);
683   OpenSSLUtils::setBioFd(sslBio, fd_, BIO_NOCLOSE);
684   SSL_set_bio(ssl_, sslBio, sslBio);
685   return true;
686 }
687
688 void AsyncSSLSocket::sslConn(
689     HandshakeCB* callback,
690     std::chrono::milliseconds timeout,
691     const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
692   DestructorGuard dg(this);
693   assert(eventBase_->isInEventBaseThread());
694
695   // Cache local and remote socket addresses to keep them available
696   // after socket file descriptor is closed.
697   if (cacheAddrOnFailure_ && -1 != getFd()) {
698     cacheLocalPeerAddr();
699   }
700
701   verifyPeer_ = verifyPeer;
702
703   // Make sure we're in the uninitialized state
704   if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
705                   STATE_UNENCRYPTED) ||
706       handshakeCallback_ != nullptr) {
707     return invalidState(callback);
708   }
709
710   sslState_ = STATE_CONNECTING;
711   handshakeCallback_ = callback;
712
713   try {
714     ssl_ = ctx_->createSSL();
715   } catch (std::exception &e) {
716     sslState_ = STATE_ERROR;
717     AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
718                            "error calling SSLContext::createSSL()");
719     LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
720             << fd_ << "): " << e.what();
721     return failHandshake(__func__, ex);
722   }
723
724   if (!setupSSLBio()) {
725     sslState_ = STATE_ERROR;
726     AsyncSocketException ex(
727         AsyncSocketException::INTERNAL_ERROR, "error creating SSL bio");
728     return failHandshake(__func__, ex);
729   }
730
731   applyVerificationOptions(ssl_);
732
733   if (sslSession_ != nullptr) {
734     sessionResumptionAttempted_ = true;
735     SSL_set_session(ssl_, sslSession_);
736     SSL_SESSION_free(sslSession_);
737     sslSession_ = nullptr;
738   }
739 #if FOLLY_OPENSSL_HAS_SNI
740   if (tlsextHostname_.size()) {
741     SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
742   }
743 #endif
744
745   SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
746
747   handshakeConnectTimeout_ = timeout;
748   startSSLConnect();
749 }
750
751 // This could be called multiple times, during normal ssl connections
752 // and after TFO fallback.
753 void AsyncSSLSocket::startSSLConnect() {
754   handshakeStartTime_ = std::chrono::steady_clock::now();
755   // Make end time at least >= start time.
756   handshakeEndTime_ = handshakeStartTime_;
757   if (handshakeConnectTimeout_ > std::chrono::milliseconds::zero()) {
758     handshakeTimeout_.scheduleTimeout(handshakeConnectTimeout_);
759   }
760   handleConnect();
761 }
762
763 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
764   if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
765     return SSL_get1_session(ssl_);
766   }
767
768   return sslSession_;
769 }
770
771 const SSL* AsyncSSLSocket::getSSL() const {
772   return ssl_;
773 }
774
775 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
776   sslSession_ = session;
777   if (!takeOwnership && session != nullptr) {
778     // Increment the reference count
779     // This API exists in BoringSSL and OpenSSL 1.1.0
780     SSL_SESSION_up_ref(session);
781   }
782 }
783
784 void AsyncSSLSocket::getSelectedNextProtocol(
785     const unsigned char** protoName,
786     unsigned* protoLen,
787     SSLContext::NextProtocolType* protoType) const {
788   if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
789     throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
790                               "NPN not supported");
791   }
792 }
793
794 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
795     const unsigned char** protoName,
796     unsigned* protoLen,
797     SSLContext::NextProtocolType* protoType) const {
798   *protoName = nullptr;
799   *protoLen = 0;
800 #if FOLLY_OPENSSL_HAS_ALPN
801   SSL_get0_alpn_selected(ssl_, protoName, protoLen);
802   if (*protoLen > 0) {
803     if (protoType) {
804       *protoType = SSLContext::NextProtocolType::ALPN;
805     }
806     return true;
807   }
808 #endif
809 #ifdef OPENSSL_NPN_NEGOTIATED
810   SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
811   if (protoType) {
812     *protoType = SSLContext::NextProtocolType::NPN;
813   }
814   return true;
815 #else
816   (void)protoType;
817   return false;
818 #endif
819 }
820
821 bool AsyncSSLSocket::getSSLSessionReused() const {
822   if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
823     return SSL_session_reused(ssl_);
824   }
825   return false;
826 }
827
828 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
829   return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
830 }
831
832 /* static */
833 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
834   if (ssl == nullptr) {
835     return nullptr;
836   }
837 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
838   return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
839 #else
840   return nullptr;
841 #endif
842 }
843
844 const char *AsyncSSLSocket::getSSLServerName() const {
845 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
846   return getSSLServerNameFromSSL(ssl_);
847 #else
848   throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
849                              "SNI not supported");
850 #endif
851 }
852
853 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
854   return getSSLServerNameFromSSL(ssl_);
855 }
856
857 int AsyncSSLSocket::getSSLVersion() const {
858   return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
859 }
860
861 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
862   X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
863   if (cert) {
864     int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
865     return OBJ_nid2ln(nid);
866   }
867   return nullptr;
868 }
869
870 int AsyncSSLSocket::getSSLCertSize() const {
871   int certSize = 0;
872   X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
873   if (cert) {
874     EVP_PKEY *key = X509_get_pubkey(cert);
875     certSize = EVP_PKEY_bits(key);
876     EVP_PKEY_free(key);
877   }
878   return certSize;
879 }
880
881 const X509* AsyncSSLSocket::getSelfCert() const {
882   return (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
883 }
884
885 bool AsyncSSLSocket::willBlock(int ret,
886                                int* sslErrorOut,
887                                unsigned long* errErrorOut) noexcept {
888   *errErrorOut = 0;
889   int error = *sslErrorOut = SSL_get_error(ssl_, ret);
890   if (error == SSL_ERROR_WANT_READ) {
891     // Register for read event if not already.
892     updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
893     return true;
894   } else if (error == SSL_ERROR_WANT_WRITE) {
895     VLOG(3) << "AsyncSSLSocket(fd=" << fd_
896             << ", state=" << int(state_) << ", sslState="
897             << sslState_ << ", events=" << eventFlags_ << "): "
898             << "SSL_ERROR_WANT_WRITE";
899     // Register for write event if not already.
900     updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
901     return true;
902 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
903   } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
904     // We will block but we can't register our own socket.  The callback that
905     // triggered this code will re-call handleAccept at the appropriate time.
906
907     // We can only get here if the linked libssl.so has support for this feature
908     // as well, otherwise SSL_get_error cannot return our error code.
909     sslState_ = STATE_CACHE_LOOKUP;
910
911     // Unregister for all events while blocked here
912     updateEventRegistration(EventHandler::NONE,
913                             EventHandler::READ | EventHandler::WRITE);
914
915     // The timeout (if set) keeps running here
916     return true;
917 #endif
918   } else if (0
919 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
920       || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
921 #endif
922 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
923       || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
924 #endif
925       ) {
926     // Our custom openssl function has kicked off an async request to do
927     // rsa/ecdsa private key operation.  When that call returns, a callback will
928     // be invoked that will re-call handleAccept.
929     sslState_ = STATE_ASYNC_PENDING;
930
931     // Unregister for all events while blocked here
932     updateEventRegistration(
933       EventHandler::NONE,
934       EventHandler::READ | EventHandler::WRITE
935     );
936
937     // The timeout (if set) keeps running here
938     return true;
939   } else {
940     unsigned long lastError = *errErrorOut = ERR_get_error();
941     VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
942             << "state=" << state_ << ", "
943             << "sslState=" << sslState_ << ", "
944             << "events=" << std::hex << eventFlags_ << "): "
945             << "SSL error: " << error << ", "
946             << "errno: " << errno << ", "
947             << "ret: " << ret << ", "
948             << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
949             << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
950             << "func: " << ERR_func_error_string(lastError) << ", "
951             << "reason: " << ERR_reason_error_string(lastError);
952     return false;
953   }
954 }
955
956 void AsyncSSLSocket::checkForImmediateRead() noexcept {
957   // openssl may have buffered data that it read from the socket already.
958   // In this case we have to process it immediately, rather than waiting for
959   // the socket to become readable again.
960   if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
961     AsyncSocket::handleRead();
962   }
963 }
964
965 void
966 AsyncSSLSocket::restartSSLAccept()
967 {
968   VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this
969           << ", fd=" << fd_ << ", state=" << int(state_) << ", "
970           << "sslState=" << sslState_ << ", events=" << eventFlags_;
971   DestructorGuard dg(this);
972   assert(
973     sslState_ == STATE_CACHE_LOOKUP ||
974     sslState_ == STATE_ASYNC_PENDING ||
975     sslState_ == STATE_ERROR ||
976     sslState_ == STATE_CLOSED);
977   if (sslState_ == STATE_CLOSED) {
978     // I sure hope whoever closed this socket didn't delete it already,
979     // but this is not strictly speaking an error
980     return;
981   }
982   if (sslState_ == STATE_ERROR) {
983     // go straight to fail if timeout expired during lookup
984     AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
985                            "SSL accept timed out");
986     failHandshake(__func__, ex);
987     return;
988   }
989   sslState_ = STATE_ACCEPTING;
990   this->handleAccept();
991 }
992
993 void
994 AsyncSSLSocket::handleAccept() noexcept {
995   VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
996           << ", fd=" << fd_ << ", state=" << int(state_) << ", "
997           << "sslState=" << sslState_ << ", events=" << eventFlags_;
998   assert(server_);
999   assert(state_ == StateEnum::ESTABLISHED &&
1000          sslState_ == STATE_ACCEPTING);
1001   if (!ssl_) {
1002     /* lazily create the SSL structure */
1003     try {
1004       ssl_ = ctx_->createSSL();
1005     } catch (std::exception &e) {
1006       sslState_ = STATE_ERROR;
1007       AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1008                              "error calling SSLContext::createSSL()");
1009       LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
1010                  << ", fd=" << fd_ << "): " << e.what();
1011       return failHandshake(__func__, ex);
1012     }
1013
1014     if (!setupSSLBio()) {
1015       sslState_ = STATE_ERROR;
1016       AsyncSocketException ex(
1017           AsyncSocketException::INTERNAL_ERROR, "error creating write bio");
1018       return failHandshake(__func__, ex);
1019     }
1020
1021     SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
1022
1023     applyVerificationOptions(ssl_);
1024   }
1025
1026   if (server_ && parseClientHello_) {
1027     SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1028     SSL_set_msg_callback_arg(ssl_, this);
1029   }
1030
1031   clearOpenSSLErrors();
1032   int ret = SSL_accept(ssl_);
1033   if (ret <= 0) {
1034     int sslError;
1035     unsigned long errError;
1036     int errnoCopy = errno;
1037     if (willBlock(ret, &sslError, &errError)) {
1038       return;
1039     } else {
1040       sslState_ = STATE_ERROR;
1041       SSLException ex(sslError, errError, ret, errnoCopy);
1042       return failHandshake(__func__, ex);
1043     }
1044   }
1045
1046   handshakeComplete_ = true;
1047   updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1048
1049   // Move into STATE_ESTABLISHED in the normal case that we are in
1050   // STATE_ACCEPTING.
1051   sslState_ = STATE_ESTABLISHED;
1052
1053   VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1054           << " successfully accepted; state=" << int(state_)
1055           << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1056
1057   // Remember the EventBase we are attached to, before we start invoking any
1058   // callbacks (since the callbacks may call detachEventBase()).
1059   EventBase* originalEventBase = eventBase_;
1060
1061   // Call the accept callback.
1062   invokeHandshakeCB();
1063
1064   // Note that the accept callback may have changed our state.
1065   // (set or unset the read callback, called write(), closed the socket, etc.)
1066   // The following code needs to handle these situations correctly.
1067   //
1068   // If the socket has been closed, readCallback_ and writeReqHead_ will
1069   // always be nullptr, so that will prevent us from trying to read or write.
1070   //
1071   // The main thing to check for is if eventBase_ is still originalEventBase.
1072   // If not, we have been detached from this event base, so we shouldn't
1073   // perform any more operations.
1074   if (eventBase_ != originalEventBase) {
1075     return;
1076   }
1077
1078   AsyncSocket::handleInitialReadWrite();
1079 }
1080
1081 void AsyncSSLSocket::clearOpenSSLErrors() {
1082   // Normally clearing out the error before calling into an openssl method
1083   // is a bad idea. However there might be other code that we don't control
1084   // calling into openssl in the same thread, which doesn't use openssl
1085   // correctly. We want to safe-guard ourselves from that code.
1086   // However touching the ERR stack each and every time has a cost of taking
1087   // a lock, so we only do this when we've opted in.
1088   if (clearOpenSSLErrors_) {
1089     ERR_clear_error();
1090   }
1091 }
1092
1093 void
1094 AsyncSSLSocket::handleConnect() noexcept {
1095   VLOG(3) <<  "AsyncSSLSocket::handleConnect() this=" << this
1096           << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1097           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1098   assert(!server_);
1099   if (state_ < StateEnum::ESTABLISHED) {
1100     return AsyncSocket::handleConnect();
1101   }
1102
1103   assert(
1104       (state_ == StateEnum::FAST_OPEN || state_ == StateEnum::ESTABLISHED) &&
1105       sslState_ == STATE_CONNECTING);
1106   assert(ssl_);
1107
1108   clearOpenSSLErrors();
1109   auto originalState = state_;
1110   int ret = SSL_connect(ssl_);
1111   if (ret <= 0) {
1112     int sslError;
1113     unsigned long errError;
1114     int errnoCopy = errno;
1115     if (willBlock(ret, &sslError, &errError)) {
1116       // We fell back to connecting state due to TFO
1117       if (state_ == StateEnum::CONNECTING) {
1118         DCHECK_EQ(StateEnum::FAST_OPEN, originalState);
1119         if (handshakeTimeout_.isScheduled()) {
1120           handshakeTimeout_.cancelTimeout();
1121         }
1122       }
1123       return;
1124     } else {
1125       sslState_ = STATE_ERROR;
1126       SSLException ex(sslError, errError, ret, errnoCopy);
1127       return failHandshake(__func__, ex);
1128     }
1129   }
1130
1131   handshakeComplete_ = true;
1132   updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1133
1134   // Move into STATE_ESTABLISHED in the normal case that we are in
1135   // STATE_CONNECTING.
1136   sslState_ = STATE_ESTABLISHED;
1137
1138   VLOG(3) << "AsyncSSLSocket " << this << ": "
1139           << "fd " << fd_ << " successfully connected; "
1140           << "state=" << int(state_) << ", sslState=" << sslState_
1141           << ", events=" << eventFlags_;
1142
1143   // Remember the EventBase we are attached to, before we start invoking any
1144   // callbacks (since the callbacks may call detachEventBase()).
1145   EventBase* originalEventBase = eventBase_;
1146
1147   // Call the handshake callback.
1148   invokeHandshakeCB();
1149
1150   // Note that the connect callback may have changed our state.
1151   // (set or unset the read callback, called write(), closed the socket, etc.)
1152   // The following code needs to handle these situations correctly.
1153   //
1154   // If the socket has been closed, readCallback_ and writeReqHead_ will
1155   // always be nullptr, so that will prevent us from trying to read or write.
1156   //
1157   // The main thing to check for is if eventBase_ is still originalEventBase.
1158   // If not, we have been detached from this event base, so we shouldn't
1159   // perform any more operations.
1160   if (eventBase_ != originalEventBase) {
1161     return;
1162   }
1163
1164   AsyncSocket::handleInitialReadWrite();
1165 }
1166
1167 void AsyncSSLSocket::invokeConnectErr(const AsyncSocketException& ex) {
1168   connectionTimeout_.cancelTimeout();
1169   AsyncSocket::invokeConnectErr(ex);
1170   if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1171     if (handshakeTimeout_.isScheduled()) {
1172       handshakeTimeout_.cancelTimeout();
1173     }
1174     // If we fell back to connecting state during TFO and the connection
1175     // failed, it would be an SSL failure as well.
1176     invokeHandshakeErr(ex);
1177   }
1178 }
1179
1180 void AsyncSSLSocket::invokeConnectSuccess() {
1181   connectionTimeout_.cancelTimeout();
1182   if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1183     assert(tfoAttempted_);
1184     // If we failed TFO, we'd fall back to trying to connect the socket,
1185     // to setup things like timeouts.
1186     startSSLConnect();
1187   }
1188   // still invoke the base class since it re-sets the connect time.
1189   AsyncSocket::invokeConnectSuccess();
1190 }
1191
1192 void AsyncSSLSocket::scheduleConnectTimeout() {
1193   if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1194     // We fell back from TFO, and need to set the timeouts.
1195     // We will not have a connect callback in this case, thus if the timer
1196     // expires we would have no-one to notify.
1197     // Thus we should reset even the connect timers to point to the handshake
1198     // timeouts.
1199     assert(connectCallback_ == nullptr);
1200     // We use a different connect timeout here than the handshake timeout, so
1201     // that we can disambiguate the 2 timers.
1202     if (connectTimeout_.count() > 0) {
1203       if (!connectionTimeout_.scheduleTimeout(connectTimeout_)) {
1204         throw AsyncSocketException(
1205             AsyncSocketException::INTERNAL_ERROR,
1206             withAddr("failed to schedule AsyncSSLSocket connect timeout"));
1207       }
1208     }
1209     return;
1210   }
1211   AsyncSocket::scheduleConnectTimeout();
1212 }
1213
1214 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1215 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1216   // turn on the buffer movable in openssl
1217   if (bufferMovableEnabled_ && ssl_ != nullptr && !isBufferMovable_ &&
1218       callback != nullptr && callback->isBufferMovable()) {
1219     SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1220     isBufferMovable_ = true;
1221   }
1222 #endif
1223
1224   AsyncSocket::setReadCB(callback);
1225 }
1226
1227 void AsyncSSLSocket::setBufferMovableEnabled(bool enabled) {
1228   bufferMovableEnabled_ = enabled;
1229 }
1230
1231 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1232   CHECK(readCallback_);
1233   if (isBufferMovable_) {
1234     *buf = nullptr;
1235     *buflen = 0;
1236   } else {
1237     // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1238     readCallback_->getReadBuffer(buf, buflen);
1239   }
1240 }
1241
1242 void
1243 AsyncSSLSocket::handleRead() noexcept {
1244   VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1245           << ", state=" << int(state_) << ", "
1246           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1247   if (state_ < StateEnum::ESTABLISHED) {
1248     return AsyncSocket::handleRead();
1249   }
1250
1251
1252   if (sslState_ == STATE_ACCEPTING) {
1253     assert(server_);
1254     handleAccept();
1255     return;
1256   }
1257   else if (sslState_ == STATE_CONNECTING) {
1258     assert(!server_);
1259     handleConnect();
1260     return;
1261   }
1262
1263   // Normal read
1264   AsyncSocket::handleRead();
1265 }
1266
1267 AsyncSocket::ReadResult
1268 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1269   VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf
1270           << ", buflen=" << *buflen;
1271
1272   if (sslState_ == STATE_UNENCRYPTED) {
1273     return AsyncSocket::performRead(buf, buflen, offset);
1274   }
1275
1276   clearOpenSSLErrors();
1277   int bytes = 0;
1278   if (!isBufferMovable_) {
1279     bytes = SSL_read(ssl_, *buf, int(*buflen));
1280   }
1281 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1282   else {
1283     bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1284   }
1285 #endif
1286
1287   if (server_ && renegotiateAttempted_) {
1288     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1289                << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1290                << "): client intitiated SSL renegotiation not permitted";
1291     return ReadResult(
1292         READ_ERROR,
1293         folly::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION));
1294   }
1295   if (bytes <= 0) {
1296     int error = SSL_get_error(ssl_, bytes);
1297     if (error == SSL_ERROR_WANT_READ) {
1298       // The caller will register for read event if not already.
1299       if (errno == EWOULDBLOCK || errno == EAGAIN) {
1300         return ReadResult(READ_BLOCKING);
1301       } else {
1302         return ReadResult(READ_ERROR);
1303       }
1304     } else if (error == SSL_ERROR_WANT_WRITE) {
1305       // TODO: Even though we are attempting to read data, SSL_read() may
1306       // need to write data if renegotiation is being performed.  We currently
1307       // don't support this and just fail the read.
1308       LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1309                  << ", sslState=" << sslState_ << ", events=" << eventFlags_
1310                  << "): unsupported SSL renegotiation during read";
1311       return ReadResult(
1312           READ_ERROR,
1313           folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1314     } else {
1315       if (zero_return(error, bytes)) {
1316         return ReadResult(bytes);
1317       }
1318       long errError = ERR_get_error();
1319       VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1320               << "state=" << state_ << ", "
1321               << "sslState=" << sslState_ << ", "
1322               << "events=" << std::hex << eventFlags_ << "): "
1323               << "bytes: " << bytes << ", "
1324               << "error: " << error << ", "
1325               << "errno: " << errno << ", "
1326               << "func: " << ERR_func_error_string(errError) << ", "
1327               << "reason: " << ERR_reason_error_string(errError);
1328       return ReadResult(
1329           READ_ERROR,
1330           folly::make_unique<SSLException>(error, errError, bytes, errno));
1331     }
1332   } else {
1333     appBytesReceived_ += bytes;
1334     return ReadResult(bytes);
1335   }
1336 }
1337
1338 void AsyncSSLSocket::handleWrite() noexcept {
1339   VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1340           << ", state=" << int(state_) << ", "
1341           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1342   if (state_ < StateEnum::ESTABLISHED) {
1343     return AsyncSocket::handleWrite();
1344   }
1345
1346   if (sslState_ == STATE_ACCEPTING) {
1347     assert(server_);
1348     handleAccept();
1349     return;
1350   }
1351
1352   if (sslState_ == STATE_CONNECTING) {
1353     assert(!server_);
1354     handleConnect();
1355     return;
1356   }
1357
1358   // Normal write
1359   AsyncSocket::handleWrite();
1360 }
1361
1362 AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {
1363   if (error == SSL_ERROR_WANT_READ) {
1364     // Even though we are attempting to write data, SSL_write() may
1365     // need to read data if renegotiation is being performed.  We currently
1366     // don't support this and just fail the write.
1367     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1368                << ", sslState=" << sslState_ << ", events=" << eventFlags_
1369                << "): "
1370                << "unsupported SSL renegotiation during write";
1371     return WriteResult(
1372         WRITE_ERROR,
1373         folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1374   } else {
1375     if (zero_return(error, rc)) {
1376       return WriteResult(0);
1377     }
1378     auto errError = ERR_get_error();
1379     VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1380             << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1381             << "SSL error: " << error << ", errno: " << errno
1382             << ", func: " << ERR_func_error_string(errError)
1383             << ", reason: " << ERR_reason_error_string(errError);
1384     return WriteResult(
1385         WRITE_ERROR,
1386         folly::make_unique<SSLException>(error, errError, rc, errno));
1387   }
1388 }
1389
1390 AsyncSocket::WriteResult AsyncSSLSocket::performWrite(
1391     const iovec* vec,
1392     uint32_t count,
1393     WriteFlags flags,
1394     uint32_t* countWritten,
1395     uint32_t* partialWritten) {
1396   if (sslState_ == STATE_UNENCRYPTED) {
1397     return AsyncSocket::performWrite(
1398       vec, count, flags, countWritten, partialWritten);
1399   }
1400   if (sslState_ != STATE_ESTABLISHED) {
1401     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1402                << ", sslState=" << sslState_
1403                << ", events=" << eventFlags_ << "): "
1404                << "TODO: AsyncSSLSocket currently does not support calling "
1405                << "write() before the handshake has fully completed";
1406     return WriteResult(
1407         WRITE_ERROR, folly::make_unique<SSLException>(SSLError::EARLY_WRITE));
1408   }
1409
1410   // Declare a buffer used to hold small write requests.  It could point to a
1411   // memory block either on stack or on heap. If it is on heap, we release it
1412   // manually when scope exits
1413   char* combinedBuf{nullptr};
1414   SCOPE_EXIT {
1415     // Note, always keep this check consistent with what we do below
1416     if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1417       delete[] combinedBuf;
1418     }
1419   };
1420
1421   *countWritten = 0;
1422   *partialWritten = 0;
1423   ssize_t totalWritten = 0;
1424   size_t bytesStolenFromNextBuffer = 0;
1425   for (uint32_t i = 0; i < count; i++) {
1426     const iovec* v = vec + i;
1427     size_t offset = bytesStolenFromNextBuffer;
1428     bytesStolenFromNextBuffer = 0;
1429     size_t len = v->iov_len - offset;
1430     const void* buf;
1431     if (len == 0) {
1432       (*countWritten)++;
1433       continue;
1434     }
1435     buf = ((const char*)v->iov_base) + offset;
1436
1437     ssize_t bytes;
1438     uint32_t buffersStolen = 0;
1439     auto sslWriteBuf = buf;
1440     if ((len < minWriteSize_) && ((i + 1) < count)) {
1441       // Combine this buffer with part or all of the next buffers in
1442       // order to avoid really small-grained calls to SSL_write().
1443       // Each call to SSL_write() produces a separate record in
1444       // the egress SSL stream, and we've found that some low-end
1445       // mobile clients can't handle receiving an HTTP response
1446       // header and the first part of the response body in two
1447       // separate SSL records (even if those two records are in
1448       // the same TCP packet).
1449
1450       if (combinedBuf == nullptr) {
1451         if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1452           // Allocate the buffer on heap
1453           combinedBuf = new char[minWriteSize_];
1454         } else {
1455           // Allocate the buffer on stack
1456           combinedBuf = (char*)alloca(minWriteSize_);
1457         }
1458       }
1459       assert(combinedBuf != nullptr);
1460       sslWriteBuf = combinedBuf;
1461
1462       memcpy(combinedBuf, buf, len);
1463       do {
1464         // INVARIANT: i + buffersStolen == complete chunks serialized
1465         uint32_t nextIndex = i + buffersStolen + 1;
1466         bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1467                                              minWriteSize_ - len);
1468         memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1469                bytesStolenFromNextBuffer);
1470         len += bytesStolenFromNextBuffer;
1471         if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1472           // couldn't steal the whole buffer
1473           break;
1474         } else {
1475           bytesStolenFromNextBuffer = 0;
1476           buffersStolen++;
1477         }
1478       } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1479     }
1480
1481     // Advance any empty buffers immediately after.
1482     if (bytesStolenFromNextBuffer == 0) {
1483       while ((i + buffersStolen + 1) < count &&
1484              vec[i + buffersStolen + 1].iov_len == 0) {
1485         buffersStolen++;
1486       }
1487     }
1488
1489     corkCurrentWrite_ =
1490         isSet(flags, WriteFlags::CORK) || (i + buffersStolen + 1 < count);
1491     bytes = eorAwareSSLWrite(
1492         ssl_,
1493         sslWriteBuf,
1494         int(len),
1495         (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1496
1497     if (bytes <= 0) {
1498       int error = SSL_get_error(ssl_, int(bytes));
1499       if (error == SSL_ERROR_WANT_WRITE) {
1500         // The caller will register for write event if not already.
1501         *partialWritten = uint32_t(offset);
1502         return WriteResult(totalWritten);
1503       }
1504       auto writeResult = interpretSSLError(int(bytes), error);
1505       if (writeResult.writeReturn < 0) {
1506         return writeResult;
1507       } // else fall through to below to correctly record totalWritten
1508     }
1509
1510     totalWritten += bytes;
1511
1512     if (bytes == (ssize_t)len) {
1513       // The full iovec is written.
1514       (*countWritten) += 1 + buffersStolen;
1515       i += buffersStolen;
1516       // continue
1517     } else {
1518       bytes += offset; // adjust bytes to account for all of v
1519       while (bytes >= (ssize_t)v->iov_len) {
1520         // We combined this buf with part or all of the next one, and
1521         // we managed to write all of this buf but not all of the bytes
1522         // from the next one that we'd hoped to write.
1523         bytes -= v->iov_len;
1524         (*countWritten)++;
1525         v = &(vec[++i]);
1526       }
1527       *partialWritten = uint32_t(bytes);
1528       return WriteResult(totalWritten);
1529     }
1530   }
1531
1532   return WriteResult(totalWritten);
1533 }
1534
1535 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1536                                       bool eor) {
1537   if (eor && isEorTrackingEnabled()) {
1538     if (appEorByteNo_) {
1539       // cannot track for more than one app byte EOR
1540       CHECK(appEorByteNo_ == appBytesWritten_ + n);
1541     } else {
1542       appEorByteNo_ = appBytesWritten_ + n;
1543     }
1544
1545     // 1. It is fine to keep updating minEorRawByteNo_.
1546     // 2. It is _min_ in the sense that SSL record will add some overhead.
1547     minEorRawByteNo_ = getRawBytesWritten() + n;
1548   }
1549
1550   n = sslWriteImpl(ssl, buf, n);
1551   if (n > 0) {
1552     appBytesWritten_ += n;
1553     if (appEorByteNo_) {
1554       if (getRawBytesWritten() >= minEorRawByteNo_) {
1555         minEorRawByteNo_ = 0;
1556       }
1557       if(appBytesWritten_ == appEorByteNo_) {
1558         appEorByteNo_ = 0;
1559       } else {
1560         CHECK(appBytesWritten_ < appEorByteNo_);
1561       }
1562     }
1563   }
1564   return n;
1565 }
1566
1567 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) {
1568   AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1569   if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1570     sslSocket->renegotiateAttempted_ = true;
1571   }
1572   if (where & SSL_CB_READ_ALERT) {
1573     const char* type = SSL_alert_type_string(ret);
1574     if (type) {
1575       const char* desc = SSL_alert_desc_string(ret);
1576       sslSocket->alertsReceived_.emplace_back(
1577           *type, StringPiece(desc, std::strlen(desc)));
1578     }
1579   }
1580 }
1581
1582 int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) {
1583   struct msghdr msg;
1584   struct iovec iov;
1585   int flags = 0;
1586   AsyncSSLSocket* tsslSock;
1587
1588   iov.iov_base = const_cast<char*>(in);
1589   iov.iov_len = inl;
1590   memset(&msg, 0, sizeof(msg));
1591   msg.msg_iov = &iov;
1592   msg.msg_iovlen = 1;
1593
1594   auto appData = OpenSSLUtils::getBioAppData(b);
1595   CHECK(appData);
1596
1597   tsslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1598   CHECK(tsslSock);
1599
1600   if (tsslSock->isEorTrackingEnabled() && tsslSock->minEorRawByteNo_ &&
1601       tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1602     flags = MSG_EOR;
1603   }
1604
1605 #ifdef MSG_NOSIGNAL
1606   flags |= MSG_NOSIGNAL;
1607 #endif
1608
1609 #ifdef MSG_MORE
1610   if (tsslSock->corkCurrentWrite_) {
1611     flags |= MSG_MORE;
1612   }
1613 #endif
1614
1615   auto result = tsslSock->sendSocketMessage(
1616       OpenSSLUtils::getBioFd(b, nullptr), &msg, flags);
1617   BIO_clear_retry_flags(b);
1618   if (!result.exception && result.writeReturn <= 0) {
1619     if (OpenSSLUtils::getBioShouldRetryWrite(int(result.writeReturn))) {
1620       BIO_set_retry_write(b);
1621     }
1622   }
1623   return int(result.writeReturn);
1624 }
1625
1626 int AsyncSSLSocket::bioRead(BIO* b, char* out, int outl) {
1627   if (!out) {
1628     return 0;
1629   }
1630   BIO_clear_retry_flags(b);
1631
1632   auto appData = OpenSSLUtils::getBioAppData(b);
1633   CHECK(appData);
1634   auto sslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1635
1636   if (sslSock->preReceivedData_ && !sslSock->preReceivedData_->empty()) {
1637     VLOG(5) << "AsyncSSLSocket::bioRead() this=" << sslSock
1638             << ", reading pre-received data";
1639
1640     Cursor cursor(sslSock->preReceivedData_.get());
1641     auto len = cursor.pullAtMost(out, outl);
1642
1643     IOBufQueue queue;
1644     queue.append(std::move(sslSock->preReceivedData_));
1645     queue.trimStart(len);
1646     sslSock->preReceivedData_ = queue.move();
1647     return len;
1648   } else {
1649     auto result = recv(OpenSSLUtils::getBioFd(b, nullptr), out, outl, 0);
1650     if (result <= 0 && OpenSSLUtils::getBioShouldRetryWrite(result)) {
1651       BIO_set_retry_read(b);
1652     }
1653     return result;
1654   }
1655 }
1656
1657 int AsyncSSLSocket::sslVerifyCallback(
1658     int preverifyOk,
1659     X509_STORE_CTX* x509Ctx) {
1660   SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1661     x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1662   AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1663
1664   VLOG(3) <<  "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1665           << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1666   return (self->handshakeCallback_) ?
1667     self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1668     preverifyOk;
1669 }
1670
1671 void AsyncSSLSocket::setPreReceivedData(std::unique_ptr<IOBuf> data) {
1672   CHECK(sslState_ == STATE_UNINIT || sslState_ == STATE_UNENCRYPTED);
1673   CHECK(!preReceivedData_);
1674   preReceivedData_ = std::move(data);
1675 }
1676
1677 void AsyncSSLSocket::enableClientHelloParsing()  {
1678     parseClientHello_ = true;
1679     clientHelloInfo_.reset(new ssl::ClientHelloInfo());
1680 }
1681
1682 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl)  {
1683   SSL_set_msg_callback(ssl, nullptr);
1684   SSL_set_msg_callback_arg(ssl, nullptr);
1685   clientHelloInfo_->clientHelloBuf_.clear();
1686 }
1687
1688 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1689                                                 int /* version */,
1690                                                 int contentType,
1691                                                 const void* buf,
1692                                                 size_t len,
1693                                                 SSL* ssl,
1694                                                 void* arg) {
1695   AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1696   if (written != 0) {
1697     sock->resetClientHelloParsing(ssl);
1698     return;
1699   }
1700   if (contentType != SSL3_RT_HANDSHAKE) {
1701     return;
1702   }
1703   if (len == 0) {
1704     return;
1705   }
1706
1707   auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1708   clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1709   try {
1710     Cursor cursor(clientHelloBuf.front());
1711     if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1712       sock->resetClientHelloParsing(ssl);
1713       return;
1714     }
1715
1716     if (cursor.totalLength() < 3) {
1717       clientHelloBuf.trimEnd(len);
1718       clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1719       return;
1720     }
1721
1722     uint32_t messageLength = cursor.read<uint8_t>();
1723     messageLength <<= 8;
1724     messageLength |= cursor.read<uint8_t>();
1725     messageLength <<= 8;
1726     messageLength |= cursor.read<uint8_t>();
1727     if (cursor.totalLength() < messageLength) {
1728       clientHelloBuf.trimEnd(len);
1729       clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1730       return;
1731     }
1732
1733     sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1734     sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1735
1736     cursor.skip(4); // gmt_unix_time
1737     cursor.skip(28); // random_bytes
1738
1739     cursor.skip(cursor.read<uint8_t>()); // session_id
1740
1741     uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1742     for (int i = 0; i < cipherSuitesLength; i += 2) {
1743       sock->clientHelloInfo_->
1744         clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1745     }
1746
1747     uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1748     for (int i = 0; i < compressionMethodsLength; ++i) {
1749       sock->clientHelloInfo_->
1750         clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1751     }
1752
1753     if (cursor.totalLength() > 0) {
1754       uint16_t extensionsLength = cursor.readBE<uint16_t>();
1755       while (extensionsLength) {
1756         ssl::TLSExtension extensionType =
1757             static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>());
1758         sock->clientHelloInfo_->
1759           clientHelloExtensions_.push_back(extensionType);
1760         extensionsLength -= 2;
1761         uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1762         extensionsLength -= 2;
1763         extensionsLength -= extensionDataLength;
1764
1765         if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) {
1766           cursor.skip(2);
1767           extensionDataLength -= 2;
1768           while (extensionDataLength) {
1769             ssl::HashAlgorithm hashAlg =
1770                 static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>());
1771             ssl::SignatureAlgorithm sigAlg =
1772                 static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>());
1773             extensionDataLength -= 2;
1774             sock->clientHelloInfo_->
1775               clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1776           }
1777         } else if (extensionType == ssl::TLSExtension::SUPPORTED_VERSIONS) {
1778           cursor.skip(1);
1779           extensionDataLength -= 1;
1780           while (extensionDataLength) {
1781             sock->clientHelloInfo_->clientHelloSupportedVersions_.push_back(
1782                 cursor.readBE<uint16_t>());
1783             extensionDataLength -= 2;
1784           }
1785         } else {
1786           cursor.skip(extensionDataLength);
1787         }
1788       }
1789     }
1790   } catch (std::out_of_range&) {
1791     // we'll use what we found and cleanup below.
1792     VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1793       << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1794   }
1795
1796   sock->resetClientHelloParsing(ssl);
1797 }
1798
1799 void AsyncSSLSocket::getSSLClientCiphers(
1800     std::string& clientCiphers,
1801     bool convertToString) const {
1802   std::string ciphers;
1803
1804   if (parseClientHello_ == false
1805       || clientHelloInfo_->clientHelloCipherSuites_.empty()) {
1806     clientCiphers = "";
1807     return;
1808   }
1809
1810   bool first = true;
1811   for (auto originalCipherCode : clientHelloInfo_->clientHelloCipherSuites_)
1812   {
1813     if (first) {
1814       first = false;
1815     } else {
1816       ciphers +=  ":";
1817     }
1818
1819     bool nameFound = convertToString;
1820
1821     if (convertToString) {
1822       const auto& name = OpenSSLUtils::getCipherName(originalCipherCode);
1823       if (name.empty()) {
1824         nameFound = false;
1825       } else {
1826         ciphers += name;
1827       }
1828     }
1829
1830     if (!nameFound) {
1831       folly::hexlify(
1832           std::array<uint8_t, 2>{{
1833               static_cast<uint8_t>((originalCipherCode >> 8) & 0xffL),
1834               static_cast<uint8_t>(originalCipherCode & 0x00ffL) }},
1835           ciphers,
1836           /* append to ciphers = */ true);
1837     }
1838   }
1839
1840   clientCiphers = std::move(ciphers);
1841 }
1842
1843 std::string AsyncSSLSocket::getSSLClientComprMethods() const {
1844   if (!parseClientHello_) {
1845     return "";
1846   }
1847   return folly::join(":", clientHelloInfo_->clientHelloCompressionMethods_);
1848 }
1849
1850 std::string AsyncSSLSocket::getSSLClientExts() const {
1851   if (!parseClientHello_) {
1852     return "";
1853   }
1854   return folly::join(":", clientHelloInfo_->clientHelloExtensions_);
1855 }
1856
1857 std::string AsyncSSLSocket::getSSLClientSigAlgs() const {
1858   if (!parseClientHello_) {
1859     return "";
1860   }
1861
1862   std::string sigAlgs;
1863   sigAlgs.reserve(clientHelloInfo_->clientHelloSigAlgs_.size() * 4);
1864   for (size_t i = 0; i < clientHelloInfo_->clientHelloSigAlgs_.size(); i++) {
1865     if (i) {
1866       sigAlgs.push_back(':');
1867     }
1868     sigAlgs.append(folly::to<std::string>(
1869         clientHelloInfo_->clientHelloSigAlgs_[i].first));
1870     sigAlgs.push_back(',');
1871     sigAlgs.append(folly::to<std::string>(
1872         clientHelloInfo_->clientHelloSigAlgs_[i].second));
1873   }
1874
1875   return sigAlgs;
1876 }
1877
1878 std::string AsyncSSLSocket::getSSLClientSupportedVersions() const {
1879   if (!parseClientHello_) {
1880     return "";
1881   }
1882   return folly::join(":", clientHelloInfo_->clientHelloSupportedVersions_);
1883 }
1884
1885 std::string AsyncSSLSocket::getSSLAlertsReceived() const {
1886   std::string ret;
1887
1888   for (const auto& alert : alertsReceived_) {
1889     if (!ret.empty()) {
1890       ret.append(",");
1891     }
1892     ret.append(folly::to<std::string>(alert.first, ": ", alert.second));
1893   }
1894
1895   return ret;
1896 }
1897
1898 void AsyncSSLSocket::getSSLSharedCiphers(std::string& sharedCiphers) const {
1899   char ciphersBuffer[1024];
1900   ciphersBuffer[0] = '\0';
1901   SSL_get_shared_ciphers(ssl_, ciphersBuffer, sizeof(ciphersBuffer) - 1);
1902   sharedCiphers = ciphersBuffer;
1903 }
1904
1905 void AsyncSSLSocket::getSSLServerCiphers(std::string& serverCiphers) const {
1906   serverCiphers = SSL_get_cipher_list(ssl_, 0);
1907   int i = 1;
1908   const char *cipher;
1909   while ((cipher = SSL_get_cipher_list(ssl_, i)) != nullptr) {
1910     serverCiphers.append(":");
1911     serverCiphers.append(cipher);
1912     i++;
1913   }
1914 }
1915
1916 } // namespace