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