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