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