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