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