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