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