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