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