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