Add TFO support to AsyncSSLSocket
[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 sslWriteBioMethod;
227
228 void* initsslWriteBioMethod(void) {
229   memcpy(&sslWriteBioMethod, BIO_s_socket(), sizeof(sslWriteBioMethod));
230   // override the bwrite method for MSG_EOR support
231   sslWriteBioMethod.bwrite = AsyncSSLSocket::bioWrite;
232
233   // Note that the sslWriteBioMethod.type and sslWriteBioMethod.name are not
234   // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
235   // then have specific handlings. The sslWriteBioWrite 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 sslWriteBioMethodInitializer = initsslWriteBioMethod();
318   (void)sslWriteBioMethodInitializer;
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   return trackEor_;
405 }
406
407 void AsyncSSLSocket::setEorTracking(bool track) {
408   if (trackEor_ != track) {
409     trackEor_ = track;
410     appEorByteNo_ = 0;
411     minEorRawByteNo_ = 0;
412   }
413 }
414
415 size_t AsyncSSLSocket::getRawBytesWritten() const {
416   BIO *b;
417   if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
418     return 0;
419   }
420
421   return BIO_number_written(b);
422 }
423
424 size_t AsyncSSLSocket::getRawBytesReceived() const {
425   BIO *b;
426   if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
427     return 0;
428   }
429
430   return BIO_number_read(b);
431 }
432
433
434 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
435   LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
436              << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
437              << "events=" << eventFlags_ << ", server=" << short(server_) << "): "
438              << "sslAccept/Connect() called in invalid "
439              << "state, handshake callback " << handshakeCallback_ << ", new callback "
440              << callback;
441   assert(!handshakeTimeout_.isScheduled());
442   sslState_ = STATE_ERROR;
443
444   AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
445                          "sslAccept() called with socket in invalid state");
446
447   handshakeEndTime_ = std::chrono::steady_clock::now();
448   if (callback) {
449     callback->handshakeErr(this, ex);
450   }
451
452   // Check the socket state not the ssl state here.
453   if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
454     failHandshake(__func__, ex);
455   }
456 }
457
458 void AsyncSSLSocket::sslAccept(HandshakeCB* callback, uint32_t timeout,
459       const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
460   DestructorGuard dg(this);
461   assert(eventBase_->isInEventBaseThread());
462   verifyPeer_ = verifyPeer;
463
464   // Make sure we're in the uninitialized state
465   if (!server_ || (sslState_ != STATE_UNINIT &&
466                    sslState_ != STATE_UNENCRYPTED) ||
467       handshakeCallback_ != nullptr) {
468     return invalidState(callback);
469   }
470
471   // Cache local and remote socket addresses to keep them available
472   // after socket file descriptor is closed.
473   if (cacheAddrOnFailure_ && -1 != getFd()) {
474     cacheLocalPeerAddr();
475   }
476
477   handshakeStartTime_ = std::chrono::steady_clock::now();
478   // Make end time at least >= start time.
479   handshakeEndTime_ = handshakeStartTime_;
480
481   sslState_ = STATE_ACCEPTING;
482   handshakeCallback_ = callback;
483
484   if (timeout > 0) {
485     handshakeTimeout_.scheduleTimeout(timeout);
486   }
487
488   /* register for a read operation (waiting for CLIENT HELLO) */
489   updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
490 }
491
492 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
493 void AsyncSSLSocket::attachSSLContext(
494   const std::shared_ptr<SSLContext>& ctx) {
495
496   // Check to ensure we are in client mode. Changing a server's ssl
497   // context doesn't make sense since clients of that server would likely
498   // become confused when the server's context changes.
499   DCHECK(!server_);
500   DCHECK(!ctx_);
501   DCHECK(ctx);
502   DCHECK(ctx->getSSLCtx());
503   ctx_ = ctx;
504
505   // In order to call attachSSLContext, detachSSLContext must have been
506   // previously called which sets the socket's context to the dummy
507   // context. Thus we must acquire this lock.
508   SpinLockGuard guard(dummyCtxLock);
509   SSL_set_SSL_CTX(ssl_, ctx->getSSLCtx());
510 }
511
512 void AsyncSSLSocket::detachSSLContext() {
513   DCHECK(ctx_);
514   ctx_.reset();
515   // We aren't using the initial_ctx for now, and it can introduce race
516   // conditions in the destructor of the SSL object.
517 #ifndef OPENSSL_NO_TLSEXT
518   if (ssl_->initial_ctx) {
519     SSL_CTX_free(ssl_->initial_ctx);
520     ssl_->initial_ctx = nullptr;
521   }
522 #endif
523   SpinLockGuard guard(dummyCtxLock);
524   if (nullptr == dummyCtx) {
525     // We need to lazily initialize the dummy context so we don't
526     // accidentally override any programmatic settings to openssl
527     dummyCtx = new SSLContext;
528   }
529   // We must remove this socket's references to its context right now
530   // since this socket could get passed to any thread. If the context has
531   // had its locking disabled, just doing a set in attachSSLContext()
532   // would not be thread safe.
533   SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
534 }
535 #endif
536
537 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
538 void AsyncSSLSocket::switchServerSSLContext(
539   const std::shared_ptr<SSLContext>& handshakeCtx) {
540   CHECK(server_);
541   if (sslState_ != STATE_ACCEPTING) {
542     // We log it here and allow the switch.
543     // It should not affect our re-negotiation support (which
544     // is not supported now).
545     VLOG(6) << "fd=" << getFd()
546             << " renegotation detected when switching SSL_CTX";
547   }
548
549   setup_SSL_CTX(handshakeCtx->getSSLCtx());
550   SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
551                             AsyncSSLSocket::sslInfoCallback);
552   handshakeCtx_ = handshakeCtx;
553   SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
554 }
555
556 bool AsyncSSLSocket::isServerNameMatch() const {
557   CHECK(!server_);
558
559   if (!ssl_) {
560     return false;
561   }
562
563   SSL_SESSION *ss = SSL_get_session(ssl_);
564   if (!ss) {
565     return false;
566   }
567
568   if(!ss->tlsext_hostname) {
569     return false;
570   }
571   return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
572 }
573
574 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
575   tlsextHostname_ = std::move(serverName);
576 }
577
578 #endif
579
580 void AsyncSSLSocket::timeoutExpired() noexcept {
581   if (state_ == StateEnum::ESTABLISHED &&
582       (sslState_ == STATE_CACHE_LOOKUP ||
583        sslState_ == STATE_ASYNC_PENDING)) {
584     sslState_ = STATE_ERROR;
585     // We are expecting a callback in restartSSLAccept.  The cache lookup
586     // and rsa-call necessarily have pointers to this ssl socket, so delay
587     // the cleanup until he calls us back.
588   } else {
589     assert(state_ == StateEnum::ESTABLISHED &&
590            (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
591     DestructorGuard dg(this);
592     AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
593                            (sslState_ == STATE_CONNECTING) ?
594                            "SSL connect timed out" : "SSL accept timed out");
595     failHandshake(__func__, ex);
596   }
597 }
598
599 int AsyncSSLSocket::getSSLExDataIndex() {
600   static auto index = SSL_get_ex_new_index(
601       0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
602   return index;
603 }
604
605 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
606   return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
607       getSSLExDataIndex()));
608 }
609
610 void AsyncSSLSocket::failHandshake(const char* /* fn */,
611                                    const AsyncSocketException& ex) {
612   startFail();
613   if (handshakeTimeout_.isScheduled()) {
614     handshakeTimeout_.cancelTimeout();
615   }
616   invokeHandshakeErr(ex);
617   finishFail();
618 }
619
620 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
621   handshakeEndTime_ = std::chrono::steady_clock::now();
622   if (handshakeCallback_ != nullptr) {
623     HandshakeCB* callback = handshakeCallback_;
624     handshakeCallback_ = nullptr;
625     callback->handshakeErr(this, ex);
626   }
627 }
628
629 void AsyncSSLSocket::invokeHandshakeCB() {
630   handshakeEndTime_ = std::chrono::steady_clock::now();
631   if (handshakeTimeout_.isScheduled()) {
632     handshakeTimeout_.cancelTimeout();
633   }
634   if (handshakeCallback_) {
635     HandshakeCB* callback = handshakeCallback_;
636     handshakeCallback_ = nullptr;
637     callback->handshakeSuc(this);
638   }
639 }
640
641 void AsyncSSLSocket::cacheLocalPeerAddr() {
642   SocketAddress address;
643   try {
644     getLocalAddress(&address);
645     getPeerAddress(&address);
646   } catch (const std::system_error& e) {
647     // The handle can be still valid while the connection is already closed.
648     if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
649       throw;
650     }
651   }
652 }
653
654 void AsyncSSLSocket::connect(ConnectCallback* callback,
655                               const folly::SocketAddress& address,
656                               int timeout,
657                               const OptionMap &options,
658                               const folly::SocketAddress& bindAddr)
659                               noexcept {
660   assert(!server_);
661   assert(state_ == StateEnum::UNINIT);
662   assert(sslState_ == STATE_UNINIT);
663   AsyncSSLSocketConnector *connector =
664     new AsyncSSLSocketConnector(this, callback, timeout);
665   AsyncSocket::connect(connector, address, timeout, options, bindAddr);
666 }
667
668 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
669   // apply the settings specified in verifyPeer_
670   if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
671     if(ctx_->needsPeerVerification()) {
672       SSL_set_verify(ssl, ctx_->getVerificationMode(),
673         AsyncSSLSocket::sslVerifyCallback);
674     }
675   } else {
676     if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
677         verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
678       SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
679         AsyncSSLSocket::sslVerifyCallback);
680     }
681   }
682 }
683
684 bool AsyncSSLSocket::setupSSLBio() {
685   auto wb = BIO_new(&sslWriteBioMethod);
686
687   if (!wb) {
688     return false;
689   }
690
691   BIO_set_app_data(wb, this);
692   BIO_set_fd(wb, fd_, BIO_NOCLOSE);
693   SSL_set_bio(ssl_, wb, wb);
694   return true;
695 }
696
697 void AsyncSSLSocket::sslConn(HandshakeCB* callback, uint64_t timeout,
698         const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
699   DestructorGuard dg(this);
700   assert(eventBase_->isInEventBaseThread());
701
702   // Cache local and remote socket addresses to keep them available
703   // after socket file descriptor is closed.
704   if (cacheAddrOnFailure_ && -1 != getFd()) {
705     cacheLocalPeerAddr();
706   }
707
708   verifyPeer_ = verifyPeer;
709
710   // Make sure we're in the uninitialized state
711   if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
712                   STATE_UNENCRYPTED) ||
713       handshakeCallback_ != nullptr) {
714     return invalidState(callback);
715   }
716
717   handshakeStartTime_ = std::chrono::steady_clock::now();
718   // Make end time at least >= start time.
719   handshakeEndTime_ = handshakeStartTime_;
720
721   sslState_ = STATE_CONNECTING;
722   handshakeCallback_ = callback;
723
724   try {
725     ssl_ = ctx_->createSSL();
726   } catch (std::exception &e) {
727     sslState_ = STATE_ERROR;
728     AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
729                            "error calling SSLContext::createSSL()");
730     LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
731             << fd_ << "): " << e.what();
732     return failHandshake(__func__, ex);
733   }
734
735   if (!setupSSLBio()) {
736     sslState_ = STATE_ERROR;
737     AsyncSocketException ex(
738         AsyncSocketException::INTERNAL_ERROR, "error creating SSL bio");
739     return failHandshake(__func__, ex);
740   }
741
742   applyVerificationOptions(ssl_);
743
744   if (sslSession_ != nullptr) {
745     SSL_set_session(ssl_, sslSession_);
746     SSL_SESSION_free(sslSession_);
747     sslSession_ = nullptr;
748   }
749 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
750   if (tlsextHostname_.size()) {
751     SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
752   }
753 #endif
754
755   SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
756
757   if (timeout > 0) {
758     handshakeTimeout_.scheduleTimeout(timeout);
759   }
760
761   handleConnect();
762 }
763
764 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
765   if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
766     return SSL_get1_session(ssl_);
767   }
768
769   return sslSession_;
770 }
771
772 const SSL* AsyncSSLSocket::getSSL() const {
773   return ssl_;
774 }
775
776 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
777   sslSession_ = session;
778   if (!takeOwnership && session != nullptr) {
779     // Increment the reference count
780     CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
781   }
782 }
783
784 void AsyncSSLSocket::getSelectedNextProtocol(
785     const unsigned char** protoName,
786     unsigned* protoLen,
787     SSLContext::NextProtocolType* protoType) const {
788   if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
789     throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
790                               "NPN not supported");
791   }
792 }
793
794 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
795     const unsigned char** protoName,
796     unsigned* protoLen,
797     SSLContext::NextProtocolType* protoType) const {
798   *protoName = nullptr;
799   *protoLen = 0;
800 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
801   SSL_get0_alpn_selected(ssl_, protoName, protoLen);
802   if (*protoLen > 0) {
803     if (protoType) {
804       *protoType = SSLContext::NextProtocolType::ALPN;
805     }
806     return true;
807   }
808 #endif
809 #ifdef OPENSSL_NPN_NEGOTIATED
810   SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
811   if (protoType) {
812     *protoType = SSLContext::NextProtocolType::NPN;
813   }
814   return true;
815 #else
816   (void)protoType;
817   return false;
818 #endif
819 }
820
821 bool AsyncSSLSocket::getSSLSessionReused() const {
822   if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
823     return SSL_session_reused(ssl_);
824   }
825   return false;
826 }
827
828 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
829   return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
830 }
831
832 /* static */
833 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
834   if (ssl == nullptr) {
835     return nullptr;
836   }
837 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
838   return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
839 #else
840   return nullptr;
841 #endif
842 }
843
844 const char *AsyncSSLSocket::getSSLServerName() const {
845 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
846   return getSSLServerNameFromSSL(ssl_);
847 #else
848   throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
849                              "SNI not supported");
850 #endif
851 }
852
853 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
854   return getSSLServerNameFromSSL(ssl_);
855 }
856
857 int AsyncSSLSocket::getSSLVersion() const {
858   return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
859 }
860
861 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
862   X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
863   if (cert) {
864     int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
865     return OBJ_nid2ln(nid);
866   }
867   return nullptr;
868 }
869
870 int AsyncSSLSocket::getSSLCertSize() const {
871   int certSize = 0;
872   X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
873   if (cert) {
874     EVP_PKEY *key = X509_get_pubkey(cert);
875     certSize = EVP_PKEY_bits(key);
876     EVP_PKEY_free(key);
877   }
878   return certSize;
879 }
880
881 bool AsyncSSLSocket::willBlock(int ret,
882                                int* sslErrorOut,
883                                unsigned long* errErrorOut) noexcept {
884   *errErrorOut = 0;
885   int error = *sslErrorOut = SSL_get_error(ssl_, ret);
886   if (error == SSL_ERROR_WANT_READ) {
887     // Register for read event if not already.
888     updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
889     return true;
890   } else if (error == SSL_ERROR_WANT_WRITE) {
891     VLOG(3) << "AsyncSSLSocket(fd=" << fd_
892             << ", state=" << int(state_) << ", sslState="
893             << sslState_ << ", events=" << eventFlags_ << "): "
894             << "SSL_ERROR_WANT_WRITE";
895     // Register for write event if not already.
896     updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
897     return true;
898 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
899   } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
900     // We will block but we can't register our own socket.  The callback that
901     // triggered this code will re-call handleAccept at the appropriate time.
902
903     // We can only get here if the linked libssl.so has support for this feature
904     // as well, otherwise SSL_get_error cannot return our error code.
905     sslState_ = STATE_CACHE_LOOKUP;
906
907     // Unregister for all events while blocked here
908     updateEventRegistration(EventHandler::NONE,
909                             EventHandler::READ | EventHandler::WRITE);
910
911     // The timeout (if set) keeps running here
912     return true;
913 #endif
914   } else if (0
915 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
916       || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
917 #endif
918 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
919       || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
920 #endif
921       ) {
922     // Our custom openssl function has kicked off an async request to do
923     // rsa/ecdsa private key operation.  When that call returns, a callback will
924     // be invoked that will re-call handleAccept.
925     sslState_ = STATE_ASYNC_PENDING;
926
927     // Unregister for all events while blocked here
928     updateEventRegistration(
929       EventHandler::NONE,
930       EventHandler::READ | EventHandler::WRITE
931     );
932
933     // The timeout (if set) keeps running here
934     return true;
935   } else {
936     unsigned long lastError = *errErrorOut = ERR_get_error();
937     VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
938             << "state=" << state_ << ", "
939             << "sslState=" << sslState_ << ", "
940             << "events=" << std::hex << eventFlags_ << "): "
941             << "SSL error: " << error << ", "
942             << "errno: " << errno << ", "
943             << "ret: " << ret << ", "
944             << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
945             << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
946             << "func: " << ERR_func_error_string(lastError) << ", "
947             << "reason: " << ERR_reason_error_string(lastError);
948     return false;
949   }
950 }
951
952 void AsyncSSLSocket::checkForImmediateRead() noexcept {
953   // openssl may have buffered data that it read from the socket already.
954   // In this case we have to process it immediately, rather than waiting for
955   // the socket to become readable again.
956   if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
957     AsyncSocket::handleRead();
958   }
959 }
960
961 void
962 AsyncSSLSocket::restartSSLAccept()
963 {
964   VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this << ", fd=" << fd_
965           << ", state=" << int(state_) << ", "
966           << "sslState=" << sslState_ << ", events=" << eventFlags_;
967   DestructorGuard dg(this);
968   assert(
969     sslState_ == STATE_CACHE_LOOKUP ||
970     sslState_ == STATE_ASYNC_PENDING ||
971     sslState_ == STATE_ERROR ||
972     sslState_ == STATE_CLOSED
973   );
974   if (sslState_ == STATE_CLOSED) {
975     // I sure hope whoever closed this socket didn't delete it already,
976     // but this is not strictly speaking an error
977     return;
978   }
979   if (sslState_ == STATE_ERROR) {
980     // go straight to fail if timeout expired during lookup
981     AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
982                            "SSL accept timed out");
983     failHandshake(__func__, ex);
984     return;
985   }
986   sslState_ = STATE_ACCEPTING;
987   this->handleAccept();
988 }
989
990 void
991 AsyncSSLSocket::handleAccept() noexcept {
992   VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
993           << ", fd=" << fd_ << ", state=" << int(state_) << ", "
994           << "sslState=" << sslState_ << ", events=" << eventFlags_;
995   assert(server_);
996   assert(state_ == StateEnum::ESTABLISHED &&
997          sslState_ == STATE_ACCEPTING);
998   if (!ssl_) {
999     /* lazily create the SSL structure */
1000     try {
1001       ssl_ = ctx_->createSSL();
1002     } catch (std::exception &e) {
1003       sslState_ = STATE_ERROR;
1004       AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1005                              "error calling SSLContext::createSSL()");
1006       LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
1007                  << ", fd=" << fd_ << "): " << e.what();
1008       return failHandshake(__func__, ex);
1009     }
1010
1011     if (!setupSSLBio()) {
1012       sslState_ = STATE_ERROR;
1013       AsyncSocketException ex(
1014           AsyncSocketException::INTERNAL_ERROR, "error creating write bio");
1015       return failHandshake(__func__, ex);
1016     }
1017
1018     SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
1019
1020     applyVerificationOptions(ssl_);
1021   }
1022
1023   if (server_ && parseClientHello_) {
1024     SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1025     SSL_set_msg_callback_arg(ssl_, this);
1026   }
1027
1028   int ret = SSL_accept(ssl_);
1029   if (ret <= 0) {
1030     int sslError;
1031     unsigned long errError;
1032     int errnoCopy = errno;
1033     if (willBlock(ret, &sslError, &errError)) {
1034       return;
1035     } else {
1036       sslState_ = STATE_ERROR;
1037       SSLException ex(sslError, errError, ret, errnoCopy);
1038       return failHandshake(__func__, ex);
1039     }
1040   }
1041
1042   handshakeComplete_ = true;
1043   updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1044
1045   // Move into STATE_ESTABLISHED in the normal case that we are in
1046   // STATE_ACCEPTING.
1047   sslState_ = STATE_ESTABLISHED;
1048
1049   VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1050           << " successfully accepted; state=" << int(state_)
1051           << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1052
1053   // Remember the EventBase we are attached to, before we start invoking any
1054   // callbacks (since the callbacks may call detachEventBase()).
1055   EventBase* originalEventBase = eventBase_;
1056
1057   // Call the accept callback.
1058   invokeHandshakeCB();
1059
1060   // Note that the accept callback may have changed our state.
1061   // (set or unset the read callback, called write(), closed the socket, etc.)
1062   // The following code needs to handle these situations correctly.
1063   //
1064   // If the socket has been closed, readCallback_ and writeReqHead_ will
1065   // always be nullptr, so that will prevent us from trying to read or write.
1066   //
1067   // The main thing to check for is if eventBase_ is still originalEventBase.
1068   // If not, we have been detached from this event base, so we shouldn't
1069   // perform any more operations.
1070   if (eventBase_ != originalEventBase) {
1071     return;
1072   }
1073
1074   AsyncSocket::handleInitialReadWrite();
1075 }
1076
1077 void
1078 AsyncSSLSocket::handleConnect() noexcept {
1079   VLOG(3) <<  "AsyncSSLSocket::handleConnect() this=" << this
1080           << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1081           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1082   assert(!server_);
1083   if (state_ < StateEnum::ESTABLISHED) {
1084     return AsyncSocket::handleConnect();
1085   }
1086
1087   assert(
1088       (state_ == StateEnum::FAST_OPEN || state_ == StateEnum::ESTABLISHED) &&
1089       sslState_ == STATE_CONNECTING);
1090   assert(ssl_);
1091
1092   int ret = SSL_connect(ssl_);
1093   if (ret <= 0) {
1094     int sslError;
1095     unsigned long errError;
1096     int errnoCopy = errno;
1097     if (willBlock(ret, &sslError, &errError)) {
1098       return;
1099     } else {
1100       sslState_ = STATE_ERROR;
1101       SSLException ex(sslError, errError, ret, errnoCopy);
1102       return failHandshake(__func__, ex);
1103     }
1104   }
1105
1106   handshakeComplete_ = true;
1107   updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1108
1109   // Move into STATE_ESTABLISHED in the normal case that we are in
1110   // STATE_CONNECTING.
1111   sslState_ = STATE_ESTABLISHED;
1112
1113   VLOG(3) << "AsyncSSLSocket " << this << ": "
1114           << "fd " << fd_ << " successfully connected; "
1115           << "state=" << int(state_) << ", sslState=" << sslState_
1116           << ", events=" << eventFlags_;
1117
1118   // Remember the EventBase we are attached to, before we start invoking any
1119   // callbacks (since the callbacks may call detachEventBase()).
1120   EventBase* originalEventBase = eventBase_;
1121
1122   // Call the handshake callback.
1123   invokeHandshakeCB();
1124
1125   // Note that the connect callback may have changed our state.
1126   // (set or unset the read callback, called write(), closed the socket, etc.)
1127   // The following code needs to handle these situations correctly.
1128   //
1129   // If the socket has been closed, readCallback_ and writeReqHead_ will
1130   // always be nullptr, so that will prevent us from trying to read or write.
1131   //
1132   // The main thing to check for is if eventBase_ is still originalEventBase.
1133   // If not, we have been detached from this event base, so we shouldn't
1134   // perform any more operations.
1135   if (eventBase_ != originalEventBase) {
1136     return;
1137   }
1138
1139   AsyncSocket::handleInitialReadWrite();
1140 }
1141
1142 void AsyncSSLSocket::invokeConnectSuccess() {
1143   if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1144     // If we failed TFO, we'd fall back to trying to connect the socket,
1145     // when we succeed we should handle the writes that caused us to start
1146     // TFO.
1147     handleWrite();
1148   }
1149   AsyncSocket::invokeConnectSuccess();
1150 }
1151
1152 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1153 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1154   // turn on the buffer movable in openssl
1155   if (bufferMovableEnabled_ && ssl_ != nullptr && !isBufferMovable_ &&
1156       callback != nullptr && callback->isBufferMovable()) {
1157     SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1158     isBufferMovable_ = true;
1159   }
1160 #endif
1161
1162   AsyncSocket::setReadCB(callback);
1163 }
1164
1165 void AsyncSSLSocket::setBufferMovableEnabled(bool enabled) {
1166   bufferMovableEnabled_ = enabled;
1167 }
1168
1169 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) noexcept {
1170   CHECK(readCallback_);
1171   if (isBufferMovable_) {
1172     *buf = nullptr;
1173     *buflen = 0;
1174   } else {
1175     // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1176     readCallback_->getReadBuffer(buf, buflen);
1177   }
1178 }
1179
1180 void
1181 AsyncSSLSocket::handleRead() noexcept {
1182   VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1183           << ", state=" << int(state_) << ", "
1184           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1185   if (state_ < StateEnum::ESTABLISHED) {
1186     return AsyncSocket::handleRead();
1187   }
1188
1189
1190   if (sslState_ == STATE_ACCEPTING) {
1191     assert(server_);
1192     handleAccept();
1193     return;
1194   }
1195   else if (sslState_ == STATE_CONNECTING) {
1196     assert(!server_);
1197     handleConnect();
1198     return;
1199   }
1200
1201   // Normal read
1202   AsyncSocket::handleRead();
1203 }
1204
1205 AsyncSocket::ReadResult
1206 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1207   VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf
1208           << ", buflen=" << *buflen;
1209
1210   if (sslState_ == STATE_UNENCRYPTED) {
1211     return AsyncSocket::performRead(buf, buflen, offset);
1212   }
1213
1214   ssize_t bytes = 0;
1215   if (!isBufferMovable_) {
1216     bytes = SSL_read(ssl_, *buf, *buflen);
1217   }
1218 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1219   else {
1220     bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1221   }
1222 #endif
1223
1224   if (server_ && renegotiateAttempted_) {
1225     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1226                << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1227                << "): client intitiated SSL renegotiation not permitted";
1228     return ReadResult(
1229         READ_ERROR,
1230         folly::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION));
1231   }
1232   if (bytes <= 0) {
1233     int error = SSL_get_error(ssl_, bytes);
1234     if (error == SSL_ERROR_WANT_READ) {
1235       // The caller will register for read event if not already.
1236       if (errno == EWOULDBLOCK || errno == EAGAIN) {
1237         return ReadResult(READ_BLOCKING);
1238       } else {
1239         return ReadResult(READ_ERROR);
1240       }
1241     } else if (error == SSL_ERROR_WANT_WRITE) {
1242       // TODO: Even though we are attempting to read data, SSL_read() may
1243       // need to write data if renegotiation is being performed.  We currently
1244       // don't support this and just fail the read.
1245       LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1246                  << ", sslState=" << sslState_ << ", events=" << eventFlags_
1247                  << "): unsupported SSL renegotiation during read";
1248       return ReadResult(
1249           READ_ERROR,
1250           folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1251     } else {
1252       if (zero_return(error, bytes)) {
1253         return ReadResult(bytes);
1254       }
1255       long errError = ERR_get_error();
1256       VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1257               << "state=" << state_ << ", "
1258               << "sslState=" << sslState_ << ", "
1259               << "events=" << std::hex << eventFlags_ << "): "
1260               << "bytes: " << bytes << ", "
1261               << "error: " << error << ", "
1262               << "errno: " << errno << ", "
1263               << "func: " << ERR_func_error_string(errError) << ", "
1264               << "reason: " << ERR_reason_error_string(errError);
1265       return ReadResult(
1266           READ_ERROR,
1267           folly::make_unique<SSLException>(error, errError, bytes, errno));
1268     }
1269   } else {
1270     appBytesReceived_ += bytes;
1271     return ReadResult(bytes);
1272   }
1273 }
1274
1275 void AsyncSSLSocket::handleWrite() noexcept {
1276   VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1277           << ", state=" << int(state_) << ", "
1278           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1279   if (state_ < StateEnum::ESTABLISHED) {
1280     return AsyncSocket::handleWrite();
1281   }
1282
1283   if (sslState_ == STATE_ACCEPTING) {
1284     assert(server_);
1285     handleAccept();
1286     return;
1287   }
1288
1289   if (sslState_ == STATE_CONNECTING) {
1290     assert(!server_);
1291     handleConnect();
1292     return;
1293   }
1294
1295   // Normal write
1296   AsyncSocket::handleWrite();
1297 }
1298
1299 AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {
1300   if (error == SSL_ERROR_WANT_READ) {
1301     // Even though we are attempting to write data, SSL_write() may
1302     // need to read data if renegotiation is being performed.  We currently
1303     // don't support this and just fail the write.
1304     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1305                << ", sslState=" << sslState_ << ", events=" << eventFlags_
1306                << "): "
1307                << "unsupported SSL renegotiation during write";
1308     return WriteResult(
1309         WRITE_ERROR,
1310         folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1311   } else {
1312     if (zero_return(error, rc)) {
1313       return WriteResult(0);
1314     }
1315     auto errError = ERR_get_error();
1316     VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1317             << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1318             << "SSL error: " << error << ", errno: " << errno
1319             << ", func: " << ERR_func_error_string(errError)
1320             << ", reason: " << ERR_reason_error_string(errError);
1321     return WriteResult(
1322         WRITE_ERROR,
1323         folly::make_unique<SSLException>(error, errError, rc, errno));
1324   }
1325 }
1326
1327 AsyncSocket::WriteResult AsyncSSLSocket::performWrite(
1328     const iovec* vec,
1329     uint32_t count,
1330     WriteFlags flags,
1331     uint32_t* countWritten,
1332     uint32_t* partialWritten) {
1333   if (sslState_ == STATE_UNENCRYPTED) {
1334     return AsyncSocket::performWrite(
1335       vec, count, flags, countWritten, partialWritten);
1336   }
1337   if (sslState_ != STATE_ESTABLISHED) {
1338     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1339                << ", sslState=" << sslState_
1340                << ", events=" << eventFlags_ << "): "
1341                << "TODO: AsyncSSLSocket currently does not support calling "
1342                << "write() before the handshake has fully completed";
1343     return WriteResult(
1344         WRITE_ERROR, folly::make_unique<SSLException>(SSLError::EARLY_WRITE));
1345   }
1346
1347   bool cork = isSet(flags, WriteFlags::CORK);
1348   CorkGuard guard(fd_, count > 1, cork, &corked_);
1349
1350   // Declare a buffer used to hold small write requests.  It could point to a
1351   // memory block either on stack or on heap. If it is on heap, we release it
1352   // manually when scope exits
1353   char* combinedBuf{nullptr};
1354   SCOPE_EXIT {
1355     // Note, always keep this check consistent with what we do below
1356     if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1357       delete[] combinedBuf;
1358     }
1359   };
1360
1361   *countWritten = 0;
1362   *partialWritten = 0;
1363   ssize_t totalWritten = 0;
1364   size_t bytesStolenFromNextBuffer = 0;
1365   for (uint32_t i = 0; i < count; i++) {
1366     const iovec* v = vec + i;
1367     size_t offset = bytesStolenFromNextBuffer;
1368     bytesStolenFromNextBuffer = 0;
1369     size_t len = v->iov_len - offset;
1370     const void* buf;
1371     if (len == 0) {
1372       (*countWritten)++;
1373       continue;
1374     }
1375     buf = ((const char*)v->iov_base) + offset;
1376
1377     ssize_t bytes;
1378     uint32_t buffersStolen = 0;
1379     if ((len < minWriteSize_) && ((i + 1) < count)) {
1380       // Combine this buffer with part or all of the next buffers in
1381       // order to avoid really small-grained calls to SSL_write().
1382       // Each call to SSL_write() produces a separate record in
1383       // the egress SSL stream, and we've found that some low-end
1384       // mobile clients can't handle receiving an HTTP response
1385       // header and the first part of the response body in two
1386       // separate SSL records (even if those two records are in
1387       // the same TCP packet).
1388
1389       if (combinedBuf == nullptr) {
1390         if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1391           // Allocate the buffer on heap
1392           combinedBuf = new char[minWriteSize_];
1393         } else {
1394           // Allocate the buffer on stack
1395           combinedBuf = (char*)alloca(minWriteSize_);
1396         }
1397       }
1398       assert(combinedBuf != nullptr);
1399
1400       memcpy(combinedBuf, buf, len);
1401       do {
1402         // INVARIANT: i + buffersStolen == complete chunks serialized
1403         uint32_t nextIndex = i + buffersStolen + 1;
1404         bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1405                                              minWriteSize_ - len);
1406         memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1407                bytesStolenFromNextBuffer);
1408         len += bytesStolenFromNextBuffer;
1409         if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1410           // couldn't steal the whole buffer
1411           break;
1412         } else {
1413           bytesStolenFromNextBuffer = 0;
1414           buffersStolen++;
1415         }
1416       } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1417       bytes = eorAwareSSLWrite(
1418         ssl_, combinedBuf, len,
1419         (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1420
1421     } else {
1422       bytes = eorAwareSSLWrite(ssl_, buf, len,
1423                            (isSet(flags, WriteFlags::EOR) && i + 1 == count));
1424     }
1425
1426     if (bytes <= 0) {
1427       int error = SSL_get_error(ssl_, bytes);
1428       if (error == SSL_ERROR_WANT_WRITE) {
1429         // The caller will register for write event if not already.
1430         *partialWritten = offset;
1431         return WriteResult(totalWritten);
1432       }
1433       auto writeResult = interpretSSLError(bytes, error);
1434       if (writeResult.writeReturn < 0) {
1435         return writeResult;
1436       } // else fall through to below to correctly record totalWritten
1437     }
1438
1439     totalWritten += bytes;
1440
1441     if (bytes == (ssize_t)len) {
1442       // The full iovec is written.
1443       (*countWritten) += 1 + buffersStolen;
1444       i += buffersStolen;
1445       // continue
1446     } else {
1447       bytes += offset; // adjust bytes to account for all of v
1448       while (bytes >= (ssize_t)v->iov_len) {
1449         // We combined this buf with part or all of the next one, and
1450         // we managed to write all of this buf but not all of the bytes
1451         // from the next one that we'd hoped to write.
1452         bytes -= v->iov_len;
1453         (*countWritten)++;
1454         v = &(vec[++i]);
1455       }
1456       *partialWritten = bytes;
1457       return WriteResult(totalWritten);
1458     }
1459   }
1460
1461   return WriteResult(totalWritten);
1462 }
1463
1464 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1465                                       bool eor) {
1466   if (eor && trackEor_) {
1467     if (appEorByteNo_) {
1468       // cannot track for more than one app byte EOR
1469       CHECK(appEorByteNo_ == appBytesWritten_ + n);
1470     } else {
1471       appEorByteNo_ = appBytesWritten_ + n;
1472     }
1473
1474     // 1. It is fine to keep updating minEorRawByteNo_.
1475     // 2. It is _min_ in the sense that SSL record will add some overhead.
1476     minEorRawByteNo_ = getRawBytesWritten() + n;
1477   }
1478
1479   n = sslWriteImpl(ssl, buf, n);
1480   if (n > 0) {
1481     appBytesWritten_ += n;
1482     if (appEorByteNo_) {
1483       if (getRawBytesWritten() >= minEorRawByteNo_) {
1484         minEorRawByteNo_ = 0;
1485       }
1486       if(appBytesWritten_ == appEorByteNo_) {
1487         appEorByteNo_ = 0;
1488       } else {
1489         CHECK(appBytesWritten_ < appEorByteNo_);
1490       }
1491     }
1492   }
1493   return n;
1494 }
1495
1496 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) {
1497   AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1498   if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1499     sslSocket->renegotiateAttempted_ = true;
1500   }
1501   if (where & SSL_CB_READ_ALERT) {
1502     const char* type = SSL_alert_type_string(ret);
1503     if (type) {
1504       const char* desc = SSL_alert_desc_string(ret);
1505       sslSocket->alertsReceived_.emplace_back(
1506           *type, StringPiece(desc, std::strlen(desc)));
1507     }
1508   }
1509 }
1510
1511 int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) {
1512   struct msghdr msg;
1513   struct iovec iov;
1514   int flags = 0;
1515   AsyncSSLSocket* tsslSock;
1516
1517   iov.iov_base = const_cast<char*>(in);
1518   iov.iov_len = inl;
1519   memset(&msg, 0, sizeof(msg));
1520   msg.msg_iov = &iov;
1521   msg.msg_iovlen = 1;
1522
1523   auto appData = BIO_get_app_data(b);
1524   CHECK(appData);
1525
1526   tsslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1527   CHECK(tsslSock);
1528
1529   if (tsslSock->trackEor_ && tsslSock->minEorRawByteNo_ &&
1530       tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1531     flags = MSG_EOR;
1532   }
1533
1534   auto result =
1535       tsslSock->sendSocketMessage(BIO_get_fd(b, nullptr), &msg, flags);
1536   BIO_clear_retry_flags(b);
1537   if (!result.exception && result.writeReturn <= 0) {
1538     if (BIO_sock_should_retry(result.writeReturn)) {
1539       BIO_set_retry_write(b);
1540     }
1541   }
1542   return result.writeReturn;
1543 }
1544
1545 int AsyncSSLSocket::sslVerifyCallback(
1546     int preverifyOk,
1547     X509_STORE_CTX* x509Ctx) {
1548   SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1549     x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1550   AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1551
1552   VLOG(3) <<  "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1553           << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1554   return (self->handshakeCallback_) ?
1555     self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1556     preverifyOk;
1557 }
1558
1559 void AsyncSSLSocket::enableClientHelloParsing()  {
1560     parseClientHello_ = true;
1561     clientHelloInfo_.reset(new ssl::ClientHelloInfo());
1562 }
1563
1564 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl)  {
1565   SSL_set_msg_callback(ssl, nullptr);
1566   SSL_set_msg_callback_arg(ssl, nullptr);
1567   clientHelloInfo_->clientHelloBuf_.clear();
1568 }
1569
1570 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1571                                                 int /* version */,
1572                                                 int contentType,
1573                                                 const void* buf,
1574                                                 size_t len,
1575                                                 SSL* ssl,
1576                                                 void* arg) {
1577   AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1578   if (written != 0) {
1579     sock->resetClientHelloParsing(ssl);
1580     return;
1581   }
1582   if (contentType != SSL3_RT_HANDSHAKE) {
1583     return;
1584   }
1585   if (len == 0) {
1586     return;
1587   }
1588
1589   auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1590   clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1591   try {
1592     Cursor cursor(clientHelloBuf.front());
1593     if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1594       sock->resetClientHelloParsing(ssl);
1595       return;
1596     }
1597
1598     if (cursor.totalLength() < 3) {
1599       clientHelloBuf.trimEnd(len);
1600       clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1601       return;
1602     }
1603
1604     uint32_t messageLength = cursor.read<uint8_t>();
1605     messageLength <<= 8;
1606     messageLength |= cursor.read<uint8_t>();
1607     messageLength <<= 8;
1608     messageLength |= cursor.read<uint8_t>();
1609     if (cursor.totalLength() < messageLength) {
1610       clientHelloBuf.trimEnd(len);
1611       clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1612       return;
1613     }
1614
1615     sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1616     sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1617
1618     cursor.skip(4); // gmt_unix_time
1619     cursor.skip(28); // random_bytes
1620
1621     cursor.skip(cursor.read<uint8_t>()); // session_id
1622
1623     uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1624     for (int i = 0; i < cipherSuitesLength; i += 2) {
1625       sock->clientHelloInfo_->
1626         clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1627     }
1628
1629     uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1630     for (int i = 0; i < compressionMethodsLength; ++i) {
1631       sock->clientHelloInfo_->
1632         clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1633     }
1634
1635     if (cursor.totalLength() > 0) {
1636       uint16_t extensionsLength = cursor.readBE<uint16_t>();
1637       while (extensionsLength) {
1638         ssl::TLSExtension extensionType =
1639             static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>());
1640         sock->clientHelloInfo_->
1641           clientHelloExtensions_.push_back(extensionType);
1642         extensionsLength -= 2;
1643         uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1644         extensionsLength -= 2;
1645
1646         if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) {
1647           cursor.skip(2);
1648           extensionDataLength -= 2;
1649           while (extensionDataLength) {
1650             ssl::HashAlgorithm hashAlg =
1651                 static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>());
1652             ssl::SignatureAlgorithm sigAlg =
1653                 static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>());
1654             extensionDataLength -= 2;
1655             sock->clientHelloInfo_->
1656               clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1657           }
1658         } else {
1659           cursor.skip(extensionDataLength);
1660           extensionsLength -= extensionDataLength;
1661         }
1662       }
1663     }
1664   } catch (std::out_of_range& e) {
1665     // we'll use what we found and cleanup below.
1666     VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1667       << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1668   }
1669
1670   sock->resetClientHelloParsing(ssl);
1671 }
1672
1673 } // namespace