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