2 * Copyright 2015 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/io/async/AsyncSSLSocket.h>
19 #include <folly/io/async/EventBase.h>
21 #include <boost/noncopyable.hpp>
24 #include <netinet/in.h>
25 #include <netinet/tcp.h>
26 #include <openssl/err.h>
27 #include <openssl/asn1.h>
28 #include <openssl/ssl.h>
29 #include <sys/types.h>
30 #include <sys/socket.h>
34 #include <folly/Bits.h>
35 #include <folly/SocketAddress.h>
36 #include <folly/SpinLock.h>
37 #include <folly/io/IOBuf.h>
38 #include <folly/io/Cursor.h>
40 using folly::SocketAddress;
41 using folly::SSLContext;
43 using std::shared_ptr;
47 using folly::SpinLock;
48 using folly::SpinLockGuard;
49 using folly::io::Cursor;
50 using std::unique_ptr;
54 using folly::AsyncSocket;
55 using folly::AsyncSocketException;
56 using folly::AsyncSSLSocket;
57 using folly::Optional;
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;
64 // Numbers chosen as to not collide with functions in ssl.h
65 const uint8_t TASYNCSSLSOCKET_F_PERFORM_READ = 90;
66 const uint8_t TASYNCSSLSOCKET_F_PERFORM_WRITE = 91;
68 // If given min write size is less than this, buffer will be allocated on
69 // stack, otherwise it is allocated on heap
70 const size_t MAX_STACK_BUF_SIZE = 2048;
72 // This converts "illegal" shutdowns into ZERO_RETURN
73 inline bool zero_return(int error, int rc) {
74 return (error == SSL_ERROR_ZERO_RETURN || (rc == 0 && errno == 0));
77 class AsyncSSLSocketConnector: public AsyncSocket::ConnectCallback,
78 public AsyncSSLSocket::HandshakeCB {
81 AsyncSSLSocket *sslSocket_;
82 AsyncSSLSocket::ConnectCallback *callback_;
87 virtual ~AsyncSSLSocketConnector() {
91 AsyncSSLSocketConnector(AsyncSSLSocket *sslSocket,
92 AsyncSocket::ConnectCallback *callback,
94 sslSocket_(sslSocket),
97 startTime_(std::chrono::duration_cast<std::chrono::milliseconds>(
98 std::chrono::steady_clock::now().time_since_epoch()).count()) {
101 virtual void connectSuccess() noexcept {
102 VLOG(7) << "client socket connected";
104 int64_t timeoutLeft = 0;
106 auto curTime = std::chrono::duration_cast<std::chrono::milliseconds>(
107 std::chrono::steady_clock::now().time_since_epoch()).count();
109 timeoutLeft = timeout_ - (curTime - startTime_);
110 if (timeoutLeft <= 0) {
111 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
112 "SSL connect timed out");
118 sslSocket_->sslConn(this, timeoutLeft);
121 virtual void connectErr(const AsyncSocketException& ex) noexcept {
122 LOG(ERROR) << "TCP connect failed: " << ex.what();
127 virtual void handshakeSuc(AsyncSSLSocket *sock) noexcept {
128 VLOG(7) << "client handshake success";
130 callback_->connectSuccess();
135 virtual void handshakeErr(AsyncSSLSocket *socket,
136 const AsyncSocketException& ex) noexcept {
137 LOG(ERROR) << "client handshakeErr: " << ex.what();
142 void fail(const AsyncSocketException &ex) {
143 // fail is a noop if called twice
145 AsyncSSLSocket::ConnectCallback *cb = callback_;
149 sslSocket_->closeNow();
150 // closeNow can call handshakeErr if it hasn't been called already.
151 // So this may have been deleted, no member variable access beyond this
153 // Note that closeNow may invoke writeError callbacks if the socket had
154 // write data pending connection completion.
159 // XXX: implement an equivalent to corking for platforms with TCP_NOPUSH?
160 #ifdef TCP_CORK // Linux-only
162 * Utility class that corks a TCP socket upon construction or uncorks
163 * the socket upon destruction
165 class CorkGuard : private boost::noncopyable {
167 CorkGuard(int fd, bool multipleWrites, bool haveMore, bool* corked):
168 fd_(fd), haveMore_(haveMore), corked_(corked) {
170 // socket is already corked; nothing to do
173 if (multipleWrites || haveMore) {
174 // We are performing multiple writes in this performWrite() call,
175 // and/or there are more calls to performWrite() that will be invoked
176 // later, so enable corking
178 setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
185 // more data to come; don't uncork yet
189 // socket isn't corked; nothing to do
194 setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
204 class CorkGuard : private boost::noncopyable {
206 CorkGuard(int, bool, bool, bool*) {}
210 void setup_SSL_CTX(SSL_CTX *ctx) {
211 #ifdef SSL_MODE_RELEASE_BUFFERS
212 SSL_CTX_set_mode(ctx,
213 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
214 SSL_MODE_ENABLE_PARTIAL_WRITE
215 | SSL_MODE_RELEASE_BUFFERS
218 SSL_CTX_set_mode(ctx,
219 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
220 SSL_MODE_ENABLE_PARTIAL_WRITE
225 BIO_METHOD eorAwareBioMethod;
227 void* initEorBioMethod(void) {
228 memcpy(&eorAwareBioMethod, BIO_s_socket(), sizeof(eorAwareBioMethod));
229 // override the bwrite method for MSG_EOR support
230 eorAwareBioMethod.bwrite = AsyncSSLSocket::eorAwareBioWrite;
232 // Note that the eorAwareBioMethod.type and eorAwareBioMethod.name are not
233 // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
234 // then have specific handlings. The eorAwareBioWrite should be compatible
235 // with the one in openssl.
237 // Return something here to enable AsyncSSLSocket to call this method using
238 // a function-scoped static.
242 } // anonymous namespace
246 SSLException::SSLException(int sslError, int errno_copy):
247 AsyncSocketException(
248 AsyncSocketException::SSL_ERROR,
249 ERR_error_string(sslError, msg_),
250 sslError == SSL_ERROR_SYSCALL ? errno_copy : 0), error_(sslError) {}
253 * Create a client AsyncSSLSocket
255 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
259 handshakeTimeout_(this, evb) {
264 * Create a server/client AsyncSSLSocket
266 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
267 EventBase* evb, int fd, bool server) :
268 AsyncSocket(evb, fd),
271 handshakeTimeout_(this, evb) {
274 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
275 AsyncSSLSocket::sslInfoCallback);
279 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
281 * Create a client AsyncSSLSocket and allow tlsext_hostname
282 * to be sent in Client Hello.
284 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
286 const std::string& serverName) :
287 AsyncSSLSocket(ctx, evb) {
288 tlsextHostname_ = serverName;
292 * Create a client AsyncSSLSocket from an already connected fd
293 * and allow tlsext_hostname to be sent in Client Hello.
295 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
296 EventBase* evb, int fd,
297 const std::string& serverName) :
298 AsyncSSLSocket(ctx, evb, fd, false) {
299 tlsextHostname_ = serverName;
303 AsyncSSLSocket::~AsyncSSLSocket() {
304 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
305 << ", evb=" << eventBase_ << ", fd=" << fd_
306 << ", state=" << int(state_) << ", sslState="
307 << sslState_ << ", events=" << eventFlags_ << ")";
310 void AsyncSSLSocket::init() {
311 // Do this here to ensure we initialize this once before any use of
312 // AsyncSSLSocket instances and not as part of library load.
313 static const auto eorAwareBioMethodInitializer = initEorBioMethod();
314 setup_SSL_CTX(ctx_->getSSLCtx());
317 void AsyncSSLSocket::closeNow() {
318 // Close the SSL connection.
319 if (ssl_ != nullptr && fd_ != -1) {
320 int rc = SSL_shutdown(ssl_);
322 rc = SSL_shutdown(ssl_);
329 if (sslSession_ != nullptr) {
330 SSL_SESSION_free(sslSession_);
331 sslSession_ = nullptr;
334 sslState_ = STATE_CLOSED;
336 if (handshakeTimeout_.isScheduled()) {
337 handshakeTimeout_.cancelTimeout();
340 DestructorGuard dg(this);
342 if (handshakeCallback_) {
343 AsyncSocketException ex(AsyncSocketException::END_OF_FILE,
344 "SSL connection closed locally");
345 HandshakeCB* callback = handshakeCallback_;
346 handshakeCallback_ = nullptr;
347 callback->handshakeErr(this, ex);
350 if (ssl_ != nullptr) {
356 AsyncSocket::closeNow();
359 void AsyncSSLSocket::shutdownWrite() {
360 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
362 // (Performing a full shutdown here is more desirable than doing nothing at
363 // all. The purpose of shutdownWrite() is normally to notify the other end
364 // of the connection that no more data will be sent. If we do nothing, the
365 // other end will never know that no more data is coming, and this may result
366 // in protocol deadlock.)
370 void AsyncSSLSocket::shutdownWriteNow() {
374 bool AsyncSSLSocket::good() const {
375 return (AsyncSocket::good() &&
376 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
377 sslState_ == STATE_ESTABLISHED));
380 // The TAsyncTransport definition of 'good' states that the transport is
381 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
382 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
383 // is connected but we haven't initiated the call to SSL_connect.
384 bool AsyncSSLSocket::connecting() const {
386 (AsyncSocket::connecting() ||
387 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
388 sslState_ == STATE_CONNECTING))));
391 bool AsyncSSLSocket::isEorTrackingEnabled() const {
392 const BIO *wb = SSL_get_wbio(ssl_);
393 return wb && wb->method == &eorAwareBioMethod;
396 void AsyncSSLSocket::setEorTracking(bool track) {
397 BIO *wb = SSL_get_wbio(ssl_);
399 throw AsyncSocketException(AsyncSocketException::INVALID_STATE,
400 "setting EOR tracking without an initialized "
405 if (wb->method != &eorAwareBioMethod) {
406 // only do this if we didn't
407 wb->method = &eorAwareBioMethod;
408 BIO_set_app_data(wb, this);
410 minEorRawByteNo_ = 0;
412 } else if (wb->method == &eorAwareBioMethod) {
413 wb->method = BIO_s_socket();
414 BIO_set_app_data(wb, nullptr);
416 minEorRawByteNo_ = 0;
418 CHECK(wb->method == BIO_s_socket());
422 size_t AsyncSSLSocket::getRawBytesWritten() const {
424 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
428 return BIO_number_written(b);
431 size_t AsyncSSLSocket::getRawBytesReceived() const {
433 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
437 return BIO_number_read(b);
441 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
442 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
443 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
444 << "events=" << eventFlags_ << ", server=" << short(server_) << "): "
445 << "sslAccept/Connect() called in invalid "
446 << "state, handshake callback " << handshakeCallback_ << ", new callback "
448 assert(!handshakeTimeout_.isScheduled());
449 sslState_ = STATE_ERROR;
451 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
452 "sslAccept() called with socket in invalid state");
455 callback->handshakeErr(this, ex);
458 // Check the socket state not the ssl state here.
459 if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
460 failHandshake(__func__, ex);
464 void AsyncSSLSocket::sslAccept(HandshakeCB* callback, uint32_t timeout,
465 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
466 DestructorGuard dg(this);
467 assert(eventBase_->isInEventBaseThread());
468 verifyPeer_ = verifyPeer;
470 // Make sure we're in the uninitialized state
471 if (!server_ || sslState_ != STATE_UNINIT || handshakeCallback_ != nullptr) {
472 return invalidState(callback);
475 sslState_ = STATE_ACCEPTING;
476 handshakeCallback_ = callback;
479 handshakeTimeout_.scheduleTimeout(timeout);
482 /* register for a read operation (waiting for CLIENT HELLO) */
483 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
486 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
487 void AsyncSSLSocket::attachSSLContext(
488 const std::shared_ptr<SSLContext>& ctx) {
490 // Check to ensure we are in client mode. Changing a server's ssl
491 // context doesn't make sense since clients of that server would likely
492 // become confused when the server's context changes.
496 DCHECK(ctx->getSSLCtx());
499 // In order to call attachSSLContext, detachSSLContext must have been
500 // previously called which sets the socket's context to the dummy
501 // context. Thus we must acquire this lock.
502 SpinLockGuard guard(dummyCtxLock);
503 SSL_set_SSL_CTX(ssl_, ctx->getSSLCtx());
506 void AsyncSSLSocket::detachSSLContext() {
509 // We aren't using the initial_ctx for now, and it can introduce race
510 // conditions in the destructor of the SSL object.
511 #ifndef OPENSSL_NO_TLSEXT
512 if (ssl_->initial_ctx) {
513 SSL_CTX_free(ssl_->initial_ctx);
514 ssl_->initial_ctx = nullptr;
517 SpinLockGuard guard(dummyCtxLock);
518 if (nullptr == dummyCtx) {
519 // We need to lazily initialize the dummy context so we don't
520 // accidentally override any programmatic settings to openssl
521 dummyCtx = new SSLContext;
523 // We must remove this socket's references to its context right now
524 // since this socket could get passed to any thread. If the context has
525 // had its locking disabled, just doing a set in attachSSLContext()
526 // would not be thread safe.
527 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
531 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
532 void AsyncSSLSocket::switchServerSSLContext(
533 const std::shared_ptr<SSLContext>& handshakeCtx) {
535 if (sslState_ != STATE_ACCEPTING) {
536 // We log it here and allow the switch.
537 // It should not affect our re-negotiation support (which
538 // is not supported now).
539 VLOG(6) << "fd=" << getFd()
540 << " renegotation detected when switching SSL_CTX";
543 setup_SSL_CTX(handshakeCtx->getSSLCtx());
544 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
545 AsyncSSLSocket::sslInfoCallback);
546 handshakeCtx_ = handshakeCtx;
547 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
550 bool AsyncSSLSocket::isServerNameMatch() const {
557 SSL_SESSION *ss = SSL_get_session(ssl_);
562 return (ss->tlsext_hostname ? true : false);
565 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
566 tlsextHostname_ = std::move(serverName);
571 void AsyncSSLSocket::timeoutExpired() noexcept {
572 if (state_ == StateEnum::ESTABLISHED &&
573 (sslState_ == STATE_CACHE_LOOKUP ||
574 sslState_ == STATE_RSA_ASYNC_PENDING)) {
575 sslState_ = STATE_ERROR;
576 // We are expecting a callback in restartSSLAccept. The cache lookup
577 // and rsa-call necessarily have pointers to this ssl socket, so delay
578 // the cleanup until he calls us back.
580 assert(state_ == StateEnum::ESTABLISHED &&
581 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
582 DestructorGuard dg(this);
583 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
584 (sslState_ == STATE_CONNECTING) ?
585 "SSL connect timed out" : "SSL accept timed out");
586 failHandshake(__func__, ex);
590 int AsyncSSLSocket::sslExDataIndex_ = -1;
591 std::mutex AsyncSSLSocket::mutex_;
593 int AsyncSSLSocket::getSSLExDataIndex() {
594 if (sslExDataIndex_ < 0) {
595 std::lock_guard<std::mutex> g(mutex_);
596 if (sslExDataIndex_ < 0) {
597 sslExDataIndex_ = SSL_get_ex_new_index(0,
598 (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
601 return sslExDataIndex_;
604 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
605 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
606 getSSLExDataIndex()));
609 void AsyncSSLSocket::failHandshake(const char* fn,
610 const AsyncSocketException& ex) {
613 if (handshakeTimeout_.isScheduled()) {
614 handshakeTimeout_.cancelTimeout();
616 if (handshakeCallback_ != nullptr) {
617 HandshakeCB* callback = handshakeCallback_;
618 handshakeCallback_ = nullptr;
619 callback->handshakeErr(this, ex);
625 void AsyncSSLSocket::invokeHandshakeCB() {
626 if (handshakeTimeout_.isScheduled()) {
627 handshakeTimeout_.cancelTimeout();
629 if (handshakeCallback_) {
630 HandshakeCB* callback = handshakeCallback_;
631 handshakeCallback_ = nullptr;
632 callback->handshakeSuc(this);
636 void AsyncSSLSocket::connect(ConnectCallback* callback,
637 const folly::SocketAddress& address,
639 const OptionMap &options,
640 const folly::SocketAddress& bindAddr)
643 assert(state_ == StateEnum::UNINIT);
644 assert(sslState_ == STATE_UNINIT);
645 AsyncSSLSocketConnector *connector =
646 new AsyncSSLSocketConnector(this, callback, timeout);
647 AsyncSocket::connect(connector, address, timeout, options, bindAddr);
650 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
651 // apply the settings specified in verifyPeer_
652 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
653 if(ctx_->needsPeerVerification()) {
654 SSL_set_verify(ssl, ctx_->getVerificationMode(),
655 AsyncSSLSocket::sslVerifyCallback);
658 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
659 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
660 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
661 AsyncSSLSocket::sslVerifyCallback);
666 void AsyncSSLSocket::sslConn(HandshakeCB* callback, uint64_t timeout,
667 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
668 DestructorGuard dg(this);
669 assert(eventBase_->isInEventBaseThread());
671 verifyPeer_ = verifyPeer;
673 // Make sure we're in the uninitialized state
674 if (server_ || sslState_ != STATE_UNINIT || handshakeCallback_ != nullptr) {
675 return invalidState(callback);
678 sslState_ = STATE_CONNECTING;
679 handshakeCallback_ = callback;
682 ssl_ = ctx_->createSSL();
683 } catch (std::exception &e) {
684 sslState_ = STATE_ERROR;
685 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
686 "error calling SSLContext::createSSL()");
687 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
688 << fd_ << "): " << e.what();
689 return failHandshake(__func__, ex);
692 applyVerificationOptions(ssl_);
694 SSL_set_fd(ssl_, fd_);
695 if (sslSession_ != nullptr) {
696 SSL_set_session(ssl_, sslSession_);
697 SSL_SESSION_free(sslSession_);
698 sslSession_ = nullptr;
700 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
701 if (tlsextHostname_.size()) {
702 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
706 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
709 handshakeTimeout_.scheduleTimeout(timeout);
715 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
716 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
717 return SSL_get1_session(ssl_);
723 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
724 sslSession_ = session;
725 if (!takeOwnership && session != nullptr) {
726 // Increment the reference count
727 CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
731 void AsyncSSLSocket::getSelectedNextProtocol(const unsigned char** protoName,
732 unsigned* protoLen) const {
733 if (!getSelectedNextProtocolNoThrow(protoName, protoLen)) {
734 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
735 "NPN not supported");
739 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
740 const unsigned char** protoName,
741 unsigned* protoLen) const {
742 *protoName = nullptr;
744 #ifdef OPENSSL_NPN_NEGOTIATED
745 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
752 bool AsyncSSLSocket::getSSLSessionReused() const {
753 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
754 return SSL_session_reused(ssl_);
759 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
760 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
763 const char *AsyncSSLSocket::getSSLServerName() const {
764 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
765 return (ssl_ != nullptr) ? SSL_get_servername(ssl_, TLSEXT_NAMETYPE_host_name)
768 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
769 "SNI not supported");
773 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
775 return getSSLServerName();
776 } catch (AsyncSocketException& ex) {
781 int AsyncSSLSocket::getSSLVersion() const {
782 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
785 int AsyncSSLSocket::getSSLCertSize() const {
787 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
789 EVP_PKEY *key = X509_get_pubkey(cert);
790 certSize = EVP_PKEY_bits(key);
796 bool AsyncSSLSocket::willBlock(int ret, int *errorOut) noexcept {
797 int error = *errorOut = SSL_get_error(ssl_, ret);
798 if (error == SSL_ERROR_WANT_READ) {
799 // Register for read event if not already.
800 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
802 } else if (error == SSL_ERROR_WANT_WRITE) {
803 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
804 << ", state=" << int(state_) << ", sslState="
805 << sslState_ << ", events=" << eventFlags_ << "): "
806 << "SSL_ERROR_WANT_WRITE";
807 // Register for write event if not already.
808 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
810 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
811 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
812 // We will block but we can't register our own socket. The callback that
813 // triggered this code will re-call handleAccept at the appropriate time.
815 // We can only get here if the linked libssl.so has support for this feature
816 // as well, otherwise SSL_get_error cannot return our error code.
817 sslState_ = STATE_CACHE_LOOKUP;
819 // Unregister for all events while blocked here
820 updateEventRegistration(EventHandler::NONE,
821 EventHandler::READ | EventHandler::WRITE);
823 // The timeout (if set) keeps running here
826 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
827 } else if (error == SSL_ERROR_WANT_RSA_ASYNC_PENDING) {
828 // Our custom openssl function has kicked off an async request to do
829 // modular exponentiation. When that call returns, a callback will
830 // be invoked that will re-call handleAccept.
831 sslState_ = STATE_RSA_ASYNC_PENDING;
833 // Unregister for all events while blocked here
834 updateEventRegistration(
836 EventHandler::READ | EventHandler::WRITE
839 // The timeout (if set) keeps running here
843 // SSL_ERROR_ZERO_RETURN is processed here so we can get some detail
845 long lastError = ERR_get_error();
846 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
847 << "state=" << state_ << ", "
848 << "sslState=" << sslState_ << ", "
849 << "events=" << std::hex << eventFlags_ << "): "
850 << "SSL error: " << error << ", "
851 << "errno: " << errno << ", "
852 << "ret: " << ret << ", "
853 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
854 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
855 << "func: " << ERR_func_error_string(lastError) << ", "
856 << "reason: " << ERR_reason_error_string(lastError);
857 if (error != SSL_ERROR_SYSCALL) {
858 if (error == SSL_ERROR_SSL) {
859 *errorOut = lastError;
861 if ((unsigned long)lastError < 0x8000) {
872 void AsyncSSLSocket::checkForImmediateRead() noexcept {
873 // openssl may have buffered data that it read from the socket already.
874 // In this case we have to process it immediately, rather than waiting for
875 // the socket to become readable again.
876 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
877 AsyncSocket::handleRead();
882 AsyncSSLSocket::restartSSLAccept()
884 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this << ", fd=" << fd_
885 << ", state=" << int(state_) << ", "
886 << "sslState=" << sslState_ << ", events=" << eventFlags_;
887 DestructorGuard dg(this);
889 sslState_ == STATE_CACHE_LOOKUP ||
890 sslState_ == STATE_RSA_ASYNC_PENDING ||
891 sslState_ == STATE_ERROR ||
892 sslState_ == STATE_CLOSED
894 if (sslState_ == STATE_CLOSED) {
895 // I sure hope whoever closed this socket didn't delete it already,
896 // but this is not strictly speaking an error
899 if (sslState_ == STATE_ERROR) {
900 // go straight to fail if timeout expired during lookup
901 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
902 "SSL accept timed out");
903 failHandshake(__func__, ex);
906 sslState_ = STATE_ACCEPTING;
907 this->handleAccept();
911 AsyncSSLSocket::handleAccept() noexcept {
912 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
913 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
914 << "sslState=" << sslState_ << ", events=" << eventFlags_;
916 assert(state_ == StateEnum::ESTABLISHED &&
917 sslState_ == STATE_ACCEPTING);
919 /* lazily create the SSL structure */
921 ssl_ = ctx_->createSSL();
922 } catch (std::exception &e) {
923 sslState_ = STATE_ERROR;
924 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
925 "error calling SSLContext::createSSL()");
926 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
927 << ", fd=" << fd_ << "): " << e.what();
928 return failHandshake(__func__, ex);
930 SSL_set_fd(ssl_, fd_);
931 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
933 applyVerificationOptions(ssl_);
936 if (server_ && parseClientHello_) {
937 SSL_set_msg_callback_arg(ssl_, this);
938 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
942 int ret = SSL_accept(ssl_);
945 if (willBlock(ret, &error)) {
948 sslState_ = STATE_ERROR;
949 SSLException ex(error, errno);
950 return failHandshake(__func__, ex);
954 handshakeComplete_ = true;
955 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
957 // Move into STATE_ESTABLISHED in the normal case that we are in
959 sslState_ = STATE_ESTABLISHED;
961 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
962 << " successfully accepted; state=" << int(state_)
963 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
965 // Remember the EventBase we are attached to, before we start invoking any
966 // callbacks (since the callbacks may call detachEventBase()).
967 EventBase* originalEventBase = eventBase_;
969 // Call the accept callback.
972 // Note that the accept callback may have changed our state.
973 // (set or unset the read callback, called write(), closed the socket, etc.)
974 // The following code needs to handle these situations correctly.
976 // If the socket has been closed, readCallback_ and writeReqHead_ will
977 // always be nullptr, so that will prevent us from trying to read or write.
979 // The main thing to check for is if eventBase_ is still originalEventBase.
980 // If not, we have been detached from this event base, so we shouldn't
981 // perform any more operations.
982 if (eventBase_ != originalEventBase) {
986 AsyncSocket::handleInitialReadWrite();
990 AsyncSSLSocket::handleConnect() noexcept {
991 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
992 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
993 << "sslState=" << sslState_ << ", events=" << eventFlags_;
995 if (state_ < StateEnum::ESTABLISHED) {
996 return AsyncSocket::handleConnect();
999 assert(state_ == StateEnum::ESTABLISHED &&
1000 sslState_ == STATE_CONNECTING);
1004 int ret = SSL_connect(ssl_);
1007 if (willBlock(ret, &error)) {
1010 sslState_ = STATE_ERROR;
1011 SSLException ex(error, errno);
1012 return failHandshake(__func__, ex);
1016 handshakeComplete_ = true;
1017 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1019 // Move into STATE_ESTABLISHED in the normal case that we are in
1020 // STATE_CONNECTING.
1021 sslState_ = STATE_ESTABLISHED;
1023 VLOG(3) << "AsyncSSLSocket %p: fd %d successfully connected; "
1024 << "state=" << int(state_) << ", sslState=" << sslState_
1025 << ", events=" << eventFlags_;
1027 // Remember the EventBase we are attached to, before we start invoking any
1028 // callbacks (since the callbacks may call detachEventBase()).
1029 EventBase* originalEventBase = eventBase_;
1031 // Call the handshake callback.
1032 invokeHandshakeCB();
1034 // Note that the connect callback may have changed our state.
1035 // (set or unset the read callback, called write(), closed the socket, etc.)
1036 // The following code needs to handle these situations correctly.
1038 // If the socket has been closed, readCallback_ and writeReqHead_ will
1039 // always be nullptr, so that will prevent us from trying to read or write.
1041 // The main thing to check for is if eventBase_ is still originalEventBase.
1042 // If not, we have been detached from this event base, so we shouldn't
1043 // perform any more operations.
1044 if (eventBase_ != originalEventBase) {
1048 AsyncSocket::handleInitialReadWrite();
1052 AsyncSSLSocket::handleRead() noexcept {
1053 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1054 << ", state=" << int(state_) << ", "
1055 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1056 if (state_ < StateEnum::ESTABLISHED) {
1057 return AsyncSocket::handleRead();
1061 if (sslState_ == STATE_ACCEPTING) {
1066 else if (sslState_ == STATE_CONNECTING) {
1073 AsyncSocket::handleRead();
1077 AsyncSSLSocket::performRead(void* buf, size_t buflen) {
1079 ssize_t bytes = SSL_read(ssl_, buf, buflen);
1080 if (server_ && renegotiateAttempted_) {
1081 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1082 << ", sslstate=" << sslState_ << ", events=" << eventFlags_ << "): "
1083 << "client intitiated SSL renegotiation not permitted";
1084 // We pack our own SSLerr here with a dummy function
1085 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1086 SSL_CLIENT_RENEGOTIATION_ATTEMPT);
1091 int error = SSL_get_error(ssl_, bytes);
1092 if (error == SSL_ERROR_WANT_READ) {
1093 // The caller will register for read event if not already.
1094 return READ_BLOCKING;
1095 } else if (error == SSL_ERROR_WANT_WRITE) {
1096 // TODO: Even though we are attempting to read data, SSL_read() may
1097 // need to write data if renegotiation is being performed. We currently
1098 // don't support this and just fail the read.
1099 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1100 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1101 << "unsupported SSL renegotiation during read",
1102 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1103 SSL_INVALID_RENEGOTIATION);
1107 // TODO: Fix this code so that it can return a proper error message
1108 // to the callback, rather than relying on AsyncSocket code which
1109 // can't handle SSL errors.
1110 long lastError = ERR_get_error();
1112 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1113 << "state=" << state_ << ", "
1114 << "sslState=" << sslState_ << ", "
1115 << "events=" << std::hex << eventFlags_ << "): "
1116 << "bytes: " << bytes << ", "
1117 << "error: " << error << ", "
1118 << "errno: " << errno << ", "
1119 << "func: " << ERR_func_error_string(lastError) << ", "
1120 << "reason: " << ERR_reason_error_string(lastError);
1122 if (zero_return(error, bytes)) {
1125 if (error != SSL_ERROR_SYSCALL) {
1126 if ((unsigned long)lastError < 0x8000) {
1135 appBytesReceived_ += bytes;
1140 void AsyncSSLSocket::handleWrite() noexcept {
1141 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1142 << ", state=" << int(state_) << ", "
1143 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1144 if (state_ < StateEnum::ESTABLISHED) {
1145 return AsyncSocket::handleWrite();
1148 if (sslState_ == STATE_ACCEPTING) {
1154 if (sslState_ == STATE_CONNECTING) {
1161 AsyncSocket::handleWrite();
1164 ssize_t AsyncSSLSocket::performWrite(const iovec* vec,
1167 uint32_t* countWritten,
1168 uint32_t* partialWritten) {
1169 if (sslState_ != STATE_ESTABLISHED) {
1170 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1171 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1172 << "TODO: AsyncSSLSocket currently does not support calling "
1173 << "write() before the handshake has fully completed";
1174 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1179 bool cork = isSet(flags, WriteFlags::CORK);
1180 CorkGuard guard(fd_, count > 1, cork, &corked_);
1182 // Declare a buffer used to hold small write requests. It could point to a
1183 // memory block either on stack or on heap. If it is on heap, we release it
1184 // manually when scope exits
1185 char* combinedBuf{nullptr};
1187 // Note, always keep this check consistent with what we do below
1188 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1189 delete[] combinedBuf;
1194 *partialWritten = 0;
1195 ssize_t totalWritten = 0;
1196 size_t bytesStolenFromNextBuffer = 0;
1197 for (uint32_t i = 0; i < count; i++) {
1198 const iovec* v = vec + i;
1199 size_t offset = bytesStolenFromNextBuffer;
1200 bytesStolenFromNextBuffer = 0;
1201 size_t len = v->iov_len - offset;
1207 buf = ((const char*)v->iov_base) + offset;
1211 uint32_t buffersStolen = 0;
1212 if ((len < minWriteSize_) && ((i + 1) < count)) {
1213 // Combine this buffer with part or all of the next buffers in
1214 // order to avoid really small-grained calls to SSL_write().
1215 // Each call to SSL_write() produces a separate record in
1216 // the egress SSL stream, and we've found that some low-end
1217 // mobile clients can't handle receiving an HTTP response
1218 // header and the first part of the response body in two
1219 // separate SSL records (even if those two records are in
1220 // the same TCP packet).
1222 if (combinedBuf == nullptr) {
1223 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1224 // Allocate the buffer on heap
1225 combinedBuf = new char[minWriteSize_];
1227 // Allocate the buffer on stack
1228 combinedBuf = (char*)alloca(minWriteSize_);
1231 assert(combinedBuf != nullptr);
1233 memcpy(combinedBuf, buf, len);
1235 // INVARIANT: i + buffersStolen == complete chunks serialized
1236 uint32_t nextIndex = i + buffersStolen + 1;
1237 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1238 minWriteSize_ - len);
1239 memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1240 bytesStolenFromNextBuffer);
1241 len += bytesStolenFromNextBuffer;
1242 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1243 // couldn't steal the whole buffer
1246 bytesStolenFromNextBuffer = 0;
1249 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1250 bytes = eorAwareSSLWrite(
1251 ssl_, combinedBuf, len,
1252 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1255 bytes = eorAwareSSLWrite(ssl_, buf, len,
1256 (isSet(flags, WriteFlags::EOR) && i + 1 == count));
1260 int error = SSL_get_error(ssl_, bytes);
1261 if (error == SSL_ERROR_WANT_WRITE) {
1262 // The caller will register for write event if not already.
1263 *partialWritten = offset;
1264 return totalWritten;
1265 } else if (error == SSL_ERROR_WANT_READ) {
1266 // TODO: Even though we are attempting to write data, SSL_write() may
1267 // need to read data if renegotiation is being performed. We currently
1268 // don't support this and just fail the write.
1269 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1270 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1271 << "unsupported SSL renegotiation during write",
1272 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1273 SSL_INVALID_RENEGOTIATION);
1277 // TODO: Fix this code so that it can return a proper error message
1278 // to the callback, rather than relying on AsyncSocket code which
1279 // can't handle SSL errors.
1280 long lastError = ERR_get_error();
1282 "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1283 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1284 << "SSL error: " << error << ", errno: " << errno
1285 << ", func: " << ERR_func_error_string(lastError)
1286 << ", reason: " << ERR_reason_error_string(lastError);
1287 if (error != SSL_ERROR_SYSCALL) {
1288 if ((unsigned long)lastError < 0x8000) {
1295 if (!zero_return(error, bytes)) {
1297 } // else fall through to below to correctly record totalWritten
1301 totalWritten += bytes;
1303 if (bytes == (ssize_t)len) {
1304 // The full iovec is written.
1305 (*countWritten) += 1 + buffersStolen;
1309 bytes += offset; // adjust bytes to account for all of v
1310 while (bytes >= (ssize_t)v->iov_len) {
1311 // We combined this buf with part or all of the next one, and
1312 // we managed to write all of this buf but not all of the bytes
1313 // from the next one that we'd hoped to write.
1314 bytes -= v->iov_len;
1318 *partialWritten = bytes;
1319 return totalWritten;
1323 return totalWritten;
1326 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1328 if (eor && SSL_get_wbio(ssl)->method == &eorAwareBioMethod) {
1329 if (appEorByteNo_) {
1330 // cannot track for more than one app byte EOR
1331 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1333 appEorByteNo_ = appBytesWritten_ + n;
1336 // 1. It is fine to keep updating minEorRawByteNo_.
1337 // 2. It is _min_ in the sense that SSL record will add some overhead.
1338 minEorRawByteNo_ = getRawBytesWritten() + n;
1341 n = sslWriteImpl(ssl, buf, n);
1343 appBytesWritten_ += n;
1344 if (appEorByteNo_) {
1345 if (getRawBytesWritten() >= minEorRawByteNo_) {
1346 minEorRawByteNo_ = 0;
1348 if(appBytesWritten_ == appEorByteNo_) {
1351 CHECK(appBytesWritten_ < appEorByteNo_);
1359 AsyncSSLSocket::sslInfoCallback(const SSL *ssl, int where, int ret) {
1360 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1361 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1362 sslSocket->renegotiateAttempted_ = true;
1366 int AsyncSSLSocket::eorAwareBioWrite(BIO *b, const char *in, int inl) {
1371 AsyncSSLSocket *tsslSock;
1373 iov.iov_base = const_cast<char *>(in);
1375 memset(&msg, 0, sizeof(msg));
1380 reinterpret_cast<AsyncSSLSocket*>(BIO_get_app_data(b));
1382 tsslSock->minEorRawByteNo_ &&
1383 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1388 ret = sendmsg(b->num, &msg, flags);
1389 BIO_clear_retry_flags(b);
1391 if (BIO_sock_should_retry(ret))
1392 BIO_set_retry_write(b);
1397 int AsyncSSLSocket::sslVerifyCallback(int preverifyOk,
1398 X509_STORE_CTX* x509Ctx) {
1399 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1400 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1401 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1403 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1404 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1405 return (self->handshakeCallback_) ?
1406 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1410 void AsyncSSLSocket::enableClientHelloParsing() {
1411 parseClientHello_ = true;
1412 clientHelloInfo_.reset(new ClientHelloInfo());
1415 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1416 SSL_set_msg_callback(ssl, nullptr);
1417 SSL_set_msg_callback_arg(ssl, nullptr);
1418 clientHelloInfo_->clientHelloBuf_.clear();
1422 AsyncSSLSocket::clientHelloParsingCallback(int written, int version,
1423 int contentType, const void *buf, size_t len, SSL *ssl, void *arg)
1425 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1427 sock->resetClientHelloParsing(ssl);
1430 if (contentType != SSL3_RT_HANDSHAKE) {
1431 sock->resetClientHelloParsing(ssl);
1438 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1439 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1441 Cursor cursor(clientHelloBuf.front());
1442 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1443 sock->resetClientHelloParsing(ssl);
1447 if (cursor.totalLength() < 3) {
1448 clientHelloBuf.trimEnd(len);
1449 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1453 uint32_t messageLength = cursor.read<uint8_t>();
1454 messageLength <<= 8;
1455 messageLength |= cursor.read<uint8_t>();
1456 messageLength <<= 8;
1457 messageLength |= cursor.read<uint8_t>();
1458 if (cursor.totalLength() < messageLength) {
1459 clientHelloBuf.trimEnd(len);
1460 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1464 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1465 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1467 cursor.skip(4); // gmt_unix_time
1468 cursor.skip(28); // random_bytes
1470 cursor.skip(cursor.read<uint8_t>()); // session_id
1472 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1473 for (int i = 0; i < cipherSuitesLength; i += 2) {
1474 sock->clientHelloInfo_->
1475 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1478 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1479 for (int i = 0; i < compressionMethodsLength; ++i) {
1480 sock->clientHelloInfo_->
1481 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1484 if (cursor.totalLength() > 0) {
1485 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1486 while (extensionsLength) {
1487 sock->clientHelloInfo_->
1488 clientHelloExtensions_.push_back(cursor.readBE<uint16_t>());
1489 extensionsLength -= 2;
1490 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1491 extensionsLength -= 2;
1492 cursor.skip(extensionDataLength);
1493 extensionsLength -= extensionDataLength;
1496 } catch (std::out_of_range& e) {
1497 // we'll use what we found and cleanup below.
1498 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1499 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1502 sock->resetClientHelloParsing(ssl);