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 __attribute__((__constructor__))
228 void initEorBioMethod(void) {
229 memcpy(&eorAwareBioMethod, BIO_s_socket(), sizeof(eorAwareBioMethod));
230 // override the bwrite method for MSG_EOR support
231 eorAwareBioMethod.bwrite = AsyncSSLSocket::eorAwareBioWrite;
233 // Note that the eorAwareBioMethod.type and eorAwareBioMethod.name are not
234 // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
235 // then have specific handlings. The eorAwareBioWrite should be compatible
236 // with the one in openssl.
239 } // anonymous namespace
243 SSLException::SSLException(int sslError, int errno_copy):
244 AsyncSocketException(
245 AsyncSocketException::SSL_ERROR,
246 ERR_error_string(sslError, msg_),
247 sslError == SSL_ERROR_SYSCALL ? errno_copy : 0), error_(sslError) {}
250 * Create a client AsyncSSLSocket
252 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
256 handshakeTimeout_(this, evb) {
257 setup_SSL_CTX(ctx_->getSSLCtx());
261 * Create a server/client AsyncSSLSocket
263 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
264 EventBase* evb, int fd, bool server) :
265 AsyncSocket(evb, fd),
268 handshakeTimeout_(this, evb) {
269 setup_SSL_CTX(ctx_->getSSLCtx());
271 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
272 AsyncSSLSocket::sslInfoCallback);
276 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
278 * Create a client AsyncSSLSocket and allow tlsext_hostname
279 * to be sent in Client Hello.
281 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
283 const std::string& serverName) :
286 handshakeTimeout_(this, evb),
287 tlsextHostname_(serverName) {
288 setup_SSL_CTX(ctx_->getSSLCtx());
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 AsyncSocket(evb, fd),
300 handshakeTimeout_(this, evb),
301 tlsextHostname_(serverName) {
302 setup_SSL_CTX(ctx_->getSSLCtx());
306 AsyncSSLSocket::~AsyncSSLSocket() {
307 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
308 << ", evb=" << eventBase_ << ", fd=" << fd_
309 << ", state=" << int(state_) << ", sslState="
310 << sslState_ << ", events=" << eventFlags_ << ")";
313 void AsyncSSLSocket::closeNow() {
314 // Close the SSL connection.
315 if (ssl_ != nullptr && fd_ != -1) {
316 int rc = SSL_shutdown(ssl_);
318 rc = SSL_shutdown(ssl_);
325 if (sslSession_ != nullptr) {
326 SSL_SESSION_free(sslSession_);
327 sslSession_ = nullptr;
330 sslState_ = STATE_CLOSED;
332 if (handshakeTimeout_.isScheduled()) {
333 handshakeTimeout_.cancelTimeout();
336 DestructorGuard dg(this);
338 if (handshakeCallback_) {
339 AsyncSocketException ex(AsyncSocketException::END_OF_FILE,
340 "SSL connection closed locally");
341 HandshakeCB* callback = handshakeCallback_;
342 handshakeCallback_ = nullptr;
343 callback->handshakeErr(this, ex);
346 if (ssl_ != nullptr) {
352 AsyncSocket::closeNow();
355 void AsyncSSLSocket::shutdownWrite() {
356 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
358 // (Performing a full shutdown here is more desirable than doing nothing at
359 // all. The purpose of shutdownWrite() is normally to notify the other end
360 // of the connection that no more data will be sent. If we do nothing, the
361 // other end will never know that no more data is coming, and this may result
362 // in protocol deadlock.)
366 void AsyncSSLSocket::shutdownWriteNow() {
370 bool AsyncSSLSocket::good() const {
371 return (AsyncSocket::good() &&
372 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
373 sslState_ == STATE_ESTABLISHED));
376 // The TAsyncTransport definition of 'good' states that the transport is
377 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
378 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
379 // is connected but we haven't initiated the call to SSL_connect.
380 bool AsyncSSLSocket::connecting() const {
382 (AsyncSocket::connecting() ||
383 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
384 sslState_ == STATE_CONNECTING))));
387 bool AsyncSSLSocket::isEorTrackingEnabled() const {
388 const BIO *wb = SSL_get_wbio(ssl_);
389 return wb && wb->method == &eorAwareBioMethod;
392 void AsyncSSLSocket::setEorTracking(bool track) {
393 BIO *wb = SSL_get_wbio(ssl_);
395 throw AsyncSocketException(AsyncSocketException::INVALID_STATE,
396 "setting EOR tracking without an initialized "
401 if (wb->method != &eorAwareBioMethod) {
402 // only do this if we didn't
403 wb->method = &eorAwareBioMethod;
404 BIO_set_app_data(wb, this);
406 minEorRawByteNo_ = 0;
408 } else if (wb->method == &eorAwareBioMethod) {
409 wb->method = BIO_s_socket();
410 BIO_set_app_data(wb, nullptr);
412 minEorRawByteNo_ = 0;
414 CHECK(wb->method == BIO_s_socket());
418 size_t AsyncSSLSocket::getRawBytesWritten() const {
420 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
424 return BIO_number_written(b);
427 size_t AsyncSSLSocket::getRawBytesReceived() const {
429 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
433 return BIO_number_read(b);
437 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
438 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
439 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
440 << "events=" << eventFlags_ << ", server=" << short(server_) << "): "
441 << "sslAccept/Connect() called in invalid "
442 << "state, handshake callback " << handshakeCallback_ << ", new callback "
444 assert(!handshakeTimeout_.isScheduled());
445 sslState_ = STATE_ERROR;
447 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
448 "sslAccept() called with socket in invalid state");
451 callback->handshakeErr(this, ex);
454 // Check the socket state not the ssl state here.
455 if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
456 failHandshake(__func__, ex);
460 void AsyncSSLSocket::sslAccept(HandshakeCB* callback, uint32_t timeout,
461 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
462 DestructorGuard dg(this);
463 assert(eventBase_->isInEventBaseThread());
464 verifyPeer_ = verifyPeer;
466 // Make sure we're in the uninitialized state
467 if (!server_ || sslState_ != STATE_UNINIT || handshakeCallback_ != nullptr) {
468 return invalidState(callback);
471 sslState_ = STATE_ACCEPTING;
472 handshakeCallback_ = callback;
475 handshakeTimeout_.scheduleTimeout(timeout);
478 /* register for a read operation (waiting for CLIENT HELLO) */
479 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
482 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
483 void AsyncSSLSocket::attachSSLContext(
484 const std::shared_ptr<SSLContext>& ctx) {
486 // Check to ensure we are in client mode. Changing a server's ssl
487 // context doesn't make sense since clients of that server would likely
488 // become confused when the server's context changes.
492 DCHECK(ctx->getSSLCtx());
495 // In order to call attachSSLContext, detachSSLContext must have been
496 // previously called which sets the socket's context to the dummy
497 // context. Thus we must acquire this lock.
498 SpinLockGuard guard(dummyCtxLock);
499 SSL_set_SSL_CTX(ssl_, ctx->getSSLCtx());
502 void AsyncSSLSocket::detachSSLContext() {
505 // We aren't using the initial_ctx for now, and it can introduce race
506 // conditions in the destructor of the SSL object.
507 #ifndef OPENSSL_NO_TLSEXT
508 if (ssl_->initial_ctx) {
509 SSL_CTX_free(ssl_->initial_ctx);
510 ssl_->initial_ctx = nullptr;
513 SpinLockGuard guard(dummyCtxLock);
514 if (nullptr == dummyCtx) {
515 // We need to lazily initialize the dummy context so we don't
516 // accidentally override any programmatic settings to openssl
517 dummyCtx = new SSLContext;
519 // We must remove this socket's references to its context right now
520 // since this socket could get passed to any thread. If the context has
521 // had its locking disabled, just doing a set in attachSSLContext()
522 // would not be thread safe.
523 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
527 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
528 void AsyncSSLSocket::switchServerSSLContext(
529 const std::shared_ptr<SSLContext>& handshakeCtx) {
531 if (sslState_ != STATE_ACCEPTING) {
532 // We log it here and allow the switch.
533 // It should not affect our re-negotiation support (which
534 // is not supported now).
535 VLOG(6) << "fd=" << getFd()
536 << " renegotation detected when switching SSL_CTX";
539 setup_SSL_CTX(handshakeCtx->getSSLCtx());
540 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
541 AsyncSSLSocket::sslInfoCallback);
542 handshakeCtx_ = handshakeCtx;
543 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
546 bool AsyncSSLSocket::isServerNameMatch() const {
553 SSL_SESSION *ss = SSL_get_session(ssl_);
558 return (ss->tlsext_hostname ? true : false);
561 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
562 tlsextHostname_ = std::move(serverName);
567 void AsyncSSLSocket::timeoutExpired() noexcept {
568 if (state_ == StateEnum::ESTABLISHED &&
569 (sslState_ == STATE_CACHE_LOOKUP ||
570 sslState_ == STATE_RSA_ASYNC_PENDING)) {
571 sslState_ = STATE_ERROR;
572 // We are expecting a callback in restartSSLAccept. The cache lookup
573 // and rsa-call necessarily have pointers to this ssl socket, so delay
574 // the cleanup until he calls us back.
576 assert(state_ == StateEnum::ESTABLISHED &&
577 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
578 DestructorGuard dg(this);
579 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
580 (sslState_ == STATE_CONNECTING) ?
581 "SSL connect timed out" : "SSL accept timed out");
582 failHandshake(__func__, ex);
586 int AsyncSSLSocket::sslExDataIndex_ = -1;
587 std::mutex AsyncSSLSocket::mutex_;
589 int AsyncSSLSocket::getSSLExDataIndex() {
590 if (sslExDataIndex_ < 0) {
591 std::lock_guard<std::mutex> g(mutex_);
592 if (sslExDataIndex_ < 0) {
593 sslExDataIndex_ = SSL_get_ex_new_index(0,
594 (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
597 return sslExDataIndex_;
600 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
601 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
602 getSSLExDataIndex()));
605 void AsyncSSLSocket::failHandshake(const char* fn,
606 const AsyncSocketException& ex) {
609 if (handshakeTimeout_.isScheduled()) {
610 handshakeTimeout_.cancelTimeout();
612 if (handshakeCallback_ != nullptr) {
613 HandshakeCB* callback = handshakeCallback_;
614 handshakeCallback_ = nullptr;
615 callback->handshakeErr(this, ex);
621 void AsyncSSLSocket::invokeHandshakeCB() {
622 if (handshakeTimeout_.isScheduled()) {
623 handshakeTimeout_.cancelTimeout();
625 if (handshakeCallback_) {
626 HandshakeCB* callback = handshakeCallback_;
627 handshakeCallback_ = nullptr;
628 callback->handshakeSuc(this);
632 void AsyncSSLSocket::connect(ConnectCallback* callback,
633 const folly::SocketAddress& address,
635 const OptionMap &options,
636 const folly::SocketAddress& bindAddr)
639 assert(state_ == StateEnum::UNINIT);
640 assert(sslState_ == STATE_UNINIT);
641 AsyncSSLSocketConnector *connector =
642 new AsyncSSLSocketConnector(this, callback, timeout);
643 AsyncSocket::connect(connector, address, timeout, options, bindAddr);
646 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
647 // apply the settings specified in verifyPeer_
648 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
649 if(ctx_->needsPeerVerification()) {
650 SSL_set_verify(ssl, ctx_->getVerificationMode(),
651 AsyncSSLSocket::sslVerifyCallback);
654 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
655 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
656 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
657 AsyncSSLSocket::sslVerifyCallback);
662 void AsyncSSLSocket::sslConn(HandshakeCB* callback, uint64_t timeout,
663 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
664 DestructorGuard dg(this);
665 assert(eventBase_->isInEventBaseThread());
667 verifyPeer_ = verifyPeer;
669 // Make sure we're in the uninitialized state
670 if (server_ || sslState_ != STATE_UNINIT || handshakeCallback_ != nullptr) {
671 return invalidState(callback);
674 sslState_ = STATE_CONNECTING;
675 handshakeCallback_ = callback;
678 ssl_ = ctx_->createSSL();
679 } catch (std::exception &e) {
680 sslState_ = STATE_ERROR;
681 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
682 "error calling SSLContext::createSSL()");
683 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
684 << fd_ << "): " << e.what();
685 return failHandshake(__func__, ex);
688 applyVerificationOptions(ssl_);
690 SSL_set_fd(ssl_, fd_);
691 if (sslSession_ != nullptr) {
692 SSL_set_session(ssl_, sslSession_);
693 SSL_SESSION_free(sslSession_);
694 sslSession_ = nullptr;
696 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
697 if (tlsextHostname_.size()) {
698 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
702 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
705 handshakeTimeout_.scheduleTimeout(timeout);
711 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
712 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
713 return SSL_get1_session(ssl_);
719 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
720 sslSession_ = session;
721 if (!takeOwnership && session != nullptr) {
722 // Increment the reference count
723 CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
727 void AsyncSSLSocket::getSelectedNextProtocol(const unsigned char** protoName,
728 unsigned* protoLen) const {
729 if (!getSelectedNextProtocolNoThrow(protoName, protoLen)) {
730 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
731 "NPN not supported");
735 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
736 const unsigned char** protoName,
737 unsigned* protoLen) const {
738 *protoName = nullptr;
740 #ifdef OPENSSL_NPN_NEGOTIATED
741 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
748 bool AsyncSSLSocket::getSSLSessionReused() const {
749 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
750 return SSL_session_reused(ssl_);
755 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
756 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
759 const char *AsyncSSLSocket::getSSLServerName() const {
760 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
761 return (ssl_ != nullptr) ? SSL_get_servername(ssl_, TLSEXT_NAMETYPE_host_name)
764 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
765 "SNI not supported");
769 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
771 return getSSLServerName();
772 } catch (AsyncSocketException& ex) {
777 int AsyncSSLSocket::getSSLVersion() const {
778 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
781 int AsyncSSLSocket::getSSLCertSize() const {
783 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
785 EVP_PKEY *key = X509_get_pubkey(cert);
786 certSize = EVP_PKEY_bits(key);
792 bool AsyncSSLSocket::willBlock(int ret, int *errorOut) noexcept {
793 int error = *errorOut = SSL_get_error(ssl_, ret);
794 if (error == SSL_ERROR_WANT_READ) {
795 // Register for read event if not already.
796 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
798 } else if (error == SSL_ERROR_WANT_WRITE) {
799 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
800 << ", state=" << int(state_) << ", sslState="
801 << sslState_ << ", events=" << eventFlags_ << "): "
802 << "SSL_ERROR_WANT_WRITE";
803 // Register for write event if not already.
804 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
806 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
807 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
808 // We will block but we can't register our own socket. The callback that
809 // triggered this code will re-call handleAccept at the appropriate time.
811 // We can only get here if the linked libssl.so has support for this feature
812 // as well, otherwise SSL_get_error cannot return our error code.
813 sslState_ = STATE_CACHE_LOOKUP;
815 // Unregister for all events while blocked here
816 updateEventRegistration(EventHandler::NONE,
817 EventHandler::READ | EventHandler::WRITE);
819 // The timeout (if set) keeps running here
822 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
823 } else if (error == SSL_ERROR_WANT_RSA_ASYNC_PENDING) {
824 // Our custom openssl function has kicked off an async request to do
825 // modular exponentiation. When that call returns, a callback will
826 // be invoked that will re-call handleAccept.
827 sslState_ = STATE_RSA_ASYNC_PENDING;
829 // Unregister for all events while blocked here
830 updateEventRegistration(
832 EventHandler::READ | EventHandler::WRITE
835 // The timeout (if set) keeps running here
839 // SSL_ERROR_ZERO_RETURN is processed here so we can get some detail
841 long lastError = ERR_get_error();
842 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
843 << "state=" << state_ << ", "
844 << "sslState=" << sslState_ << ", "
845 << "events=" << std::hex << eventFlags_ << "): "
846 << "SSL error: " << error << ", "
847 << "errno: " << errno << ", "
848 << "ret: " << ret << ", "
849 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
850 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
851 << "func: " << ERR_func_error_string(lastError) << ", "
852 << "reason: " << ERR_reason_error_string(lastError);
853 if (error != SSL_ERROR_SYSCALL) {
854 if (error == SSL_ERROR_SSL) {
855 *errorOut = lastError;
857 if ((unsigned long)lastError < 0x8000) {
868 void AsyncSSLSocket::checkForImmediateRead() noexcept {
869 // openssl may have buffered data that it read from the socket already.
870 // In this case we have to process it immediately, rather than waiting for
871 // the socket to become readable again.
872 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
873 AsyncSocket::handleRead();
878 AsyncSSLSocket::restartSSLAccept()
880 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this << ", fd=" << fd_
881 << ", state=" << int(state_) << ", "
882 << "sslState=" << sslState_ << ", events=" << eventFlags_;
883 DestructorGuard dg(this);
885 sslState_ == STATE_CACHE_LOOKUP ||
886 sslState_ == STATE_RSA_ASYNC_PENDING ||
887 sslState_ == STATE_ERROR ||
888 sslState_ == STATE_CLOSED
890 if (sslState_ == STATE_CLOSED) {
891 // I sure hope whoever closed this socket didn't delete it already,
892 // but this is not strictly speaking an error
895 if (sslState_ == STATE_ERROR) {
896 // go straight to fail if timeout expired during lookup
897 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
898 "SSL accept timed out");
899 failHandshake(__func__, ex);
902 sslState_ = STATE_ACCEPTING;
903 this->handleAccept();
907 AsyncSSLSocket::handleAccept() noexcept {
908 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
909 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
910 << "sslState=" << sslState_ << ", events=" << eventFlags_;
912 assert(state_ == StateEnum::ESTABLISHED &&
913 sslState_ == STATE_ACCEPTING);
915 /* lazily create the SSL structure */
917 ssl_ = ctx_->createSSL();
918 } catch (std::exception &e) {
919 sslState_ = STATE_ERROR;
920 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
921 "error calling SSLContext::createSSL()");
922 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
923 << ", fd=" << fd_ << "): " << e.what();
924 return failHandshake(__func__, ex);
926 SSL_set_fd(ssl_, fd_);
927 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
929 applyVerificationOptions(ssl_);
932 if (server_ && parseClientHello_) {
933 SSL_set_msg_callback_arg(ssl_, this);
934 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
938 int ret = SSL_accept(ssl_);
941 if (willBlock(ret, &error)) {
944 sslState_ = STATE_ERROR;
945 SSLException ex(error, errno);
946 return failHandshake(__func__, ex);
950 handshakeComplete_ = true;
951 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
953 // Move into STATE_ESTABLISHED in the normal case that we are in
955 sslState_ = STATE_ESTABLISHED;
957 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
958 << " successfully accepted; state=" << int(state_)
959 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
961 // Remember the EventBase we are attached to, before we start invoking any
962 // callbacks (since the callbacks may call detachEventBase()).
963 EventBase* originalEventBase = eventBase_;
965 // Call the accept callback.
968 // Note that the accept callback may have changed our state.
969 // (set or unset the read callback, called write(), closed the socket, etc.)
970 // The following code needs to handle these situations correctly.
972 // If the socket has been closed, readCallback_ and writeReqHead_ will
973 // always be nullptr, so that will prevent us from trying to read or write.
975 // The main thing to check for is if eventBase_ is still originalEventBase.
976 // If not, we have been detached from this event base, so we shouldn't
977 // perform any more operations.
978 if (eventBase_ != originalEventBase) {
982 AsyncSocket::handleInitialReadWrite();
986 AsyncSSLSocket::handleConnect() noexcept {
987 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
988 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
989 << "sslState=" << sslState_ << ", events=" << eventFlags_;
991 if (state_ < StateEnum::ESTABLISHED) {
992 return AsyncSocket::handleConnect();
995 assert(state_ == StateEnum::ESTABLISHED &&
996 sslState_ == STATE_CONNECTING);
1000 int ret = SSL_connect(ssl_);
1003 if (willBlock(ret, &error)) {
1006 sslState_ = STATE_ERROR;
1007 SSLException ex(error, errno);
1008 return failHandshake(__func__, ex);
1012 handshakeComplete_ = true;
1013 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1015 // Move into STATE_ESTABLISHED in the normal case that we are in
1016 // STATE_CONNECTING.
1017 sslState_ = STATE_ESTABLISHED;
1019 VLOG(3) << "AsyncSSLSocket %p: fd %d successfully connected; "
1020 << "state=" << int(state_) << ", sslState=" << sslState_
1021 << ", events=" << eventFlags_;
1023 // Remember the EventBase we are attached to, before we start invoking any
1024 // callbacks (since the callbacks may call detachEventBase()).
1025 EventBase* originalEventBase = eventBase_;
1027 // Call the handshake callback.
1028 invokeHandshakeCB();
1030 // Note that the connect callback may have changed our state.
1031 // (set or unset the read callback, called write(), closed the socket, etc.)
1032 // The following code needs to handle these situations correctly.
1034 // If the socket has been closed, readCallback_ and writeReqHead_ will
1035 // always be nullptr, so that will prevent us from trying to read or write.
1037 // The main thing to check for is if eventBase_ is still originalEventBase.
1038 // If not, we have been detached from this event base, so we shouldn't
1039 // perform any more operations.
1040 if (eventBase_ != originalEventBase) {
1044 AsyncSocket::handleInitialReadWrite();
1048 AsyncSSLSocket::handleRead() noexcept {
1049 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1050 << ", state=" << int(state_) << ", "
1051 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1052 if (state_ < StateEnum::ESTABLISHED) {
1053 return AsyncSocket::handleRead();
1057 if (sslState_ == STATE_ACCEPTING) {
1062 else if (sslState_ == STATE_CONNECTING) {
1069 AsyncSocket::handleRead();
1073 AsyncSSLSocket::performRead(void* buf, size_t buflen) {
1075 ssize_t bytes = SSL_read(ssl_, buf, buflen);
1076 if (server_ && renegotiateAttempted_) {
1077 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1078 << ", sslstate=" << sslState_ << ", events=" << eventFlags_ << "): "
1079 << "client intitiated SSL renegotiation not permitted";
1080 // We pack our own SSLerr here with a dummy function
1081 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1082 SSL_CLIENT_RENEGOTIATION_ATTEMPT);
1087 int error = SSL_get_error(ssl_, bytes);
1088 if (error == SSL_ERROR_WANT_READ) {
1089 // The caller will register for read event if not already.
1090 return READ_BLOCKING;
1091 } else if (error == SSL_ERROR_WANT_WRITE) {
1092 // TODO: Even though we are attempting to read data, SSL_read() may
1093 // need to write data if renegotiation is being performed. We currently
1094 // don't support this and just fail the read.
1095 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1096 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1097 << "unsupported SSL renegotiation during read",
1098 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1099 SSL_INVALID_RENEGOTIATION);
1103 // TODO: Fix this code so that it can return a proper error message
1104 // to the callback, rather than relying on AsyncSocket code which
1105 // can't handle SSL errors.
1106 long lastError = ERR_get_error();
1108 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1109 << "state=" << state_ << ", "
1110 << "sslState=" << sslState_ << ", "
1111 << "events=" << std::hex << eventFlags_ << "): "
1112 << "bytes: " << bytes << ", "
1113 << "error: " << error << ", "
1114 << "errno: " << errno << ", "
1115 << "func: " << ERR_func_error_string(lastError) << ", "
1116 << "reason: " << ERR_reason_error_string(lastError);
1118 if (zero_return(error, bytes)) {
1121 if (error != SSL_ERROR_SYSCALL) {
1122 if ((unsigned long)lastError < 0x8000) {
1131 appBytesReceived_ += bytes;
1136 void AsyncSSLSocket::handleWrite() noexcept {
1137 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1138 << ", state=" << int(state_) << ", "
1139 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1140 if (state_ < StateEnum::ESTABLISHED) {
1141 return AsyncSocket::handleWrite();
1144 if (sslState_ == STATE_ACCEPTING) {
1150 if (sslState_ == STATE_CONNECTING) {
1157 AsyncSocket::handleWrite();
1160 ssize_t AsyncSSLSocket::performWrite(const iovec* vec,
1163 uint32_t* countWritten,
1164 uint32_t* partialWritten) {
1165 if (sslState_ != STATE_ESTABLISHED) {
1166 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1167 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1168 << "TODO: AsyncSSLSocket currently does not support calling "
1169 << "write() before the handshake has fully completed";
1170 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1175 bool cork = isSet(flags, WriteFlags::CORK);
1176 CorkGuard guard(fd_, count > 1, cork, &corked_);
1178 // Declare a buffer used to hold small write requests. It could point to a
1179 // memory block either on stack or on heap. If it is on heap, we release it
1180 // manually when scope exits
1181 char* combinedBuf{nullptr};
1183 // Note, always keep this check consistent with what we do below
1184 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1185 delete[] combinedBuf;
1190 *partialWritten = 0;
1191 ssize_t totalWritten = 0;
1192 size_t bytesStolenFromNextBuffer = 0;
1193 for (uint32_t i = 0; i < count; i++) {
1194 const iovec* v = vec + i;
1195 size_t offset = bytesStolenFromNextBuffer;
1196 bytesStolenFromNextBuffer = 0;
1197 size_t len = v->iov_len - offset;
1203 buf = ((const char*)v->iov_base) + offset;
1207 uint32_t buffersStolen = 0;
1208 if ((len < minWriteSize_) && ((i + 1) < count)) {
1209 // Combine this buffer with part or all of the next buffers in
1210 // order to avoid really small-grained calls to SSL_write().
1211 // Each call to SSL_write() produces a separate record in
1212 // the egress SSL stream, and we've found that some low-end
1213 // mobile clients can't handle receiving an HTTP response
1214 // header and the first part of the response body in two
1215 // separate SSL records (even if those two records are in
1216 // the same TCP packet).
1218 if (combinedBuf == nullptr) {
1219 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1220 // Allocate the buffer on heap
1221 combinedBuf = new char[minWriteSize_];
1223 // Allocate the buffer on stack
1224 combinedBuf = (char*)alloca(minWriteSize_);
1227 assert(combinedBuf != nullptr);
1229 memcpy(combinedBuf, buf, len);
1231 // INVARIANT: i + buffersStolen == complete chunks serialized
1232 uint32_t nextIndex = i + buffersStolen + 1;
1233 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1234 minWriteSize_ - len);
1235 memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1236 bytesStolenFromNextBuffer);
1237 len += bytesStolenFromNextBuffer;
1238 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1239 // couldn't steal the whole buffer
1242 bytesStolenFromNextBuffer = 0;
1245 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1246 bytes = eorAwareSSLWrite(
1247 ssl_, combinedBuf, len,
1248 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1251 bytes = eorAwareSSLWrite(ssl_, buf, len,
1252 (isSet(flags, WriteFlags::EOR) && i + 1 == count));
1256 int error = SSL_get_error(ssl_, bytes);
1257 if (error == SSL_ERROR_WANT_WRITE) {
1258 // The caller will register for write event if not already.
1259 *partialWritten = offset;
1260 return totalWritten;
1261 } else if (error == SSL_ERROR_WANT_READ) {
1262 // TODO: Even though we are attempting to write data, SSL_write() may
1263 // need to read data if renegotiation is being performed. We currently
1264 // don't support this and just fail the write.
1265 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1266 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1267 << "unsupported SSL renegotiation during write",
1268 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1269 SSL_INVALID_RENEGOTIATION);
1273 // TODO: Fix this code so that it can return a proper error message
1274 // to the callback, rather than relying on AsyncSocket code which
1275 // can't handle SSL errors.
1276 long lastError = ERR_get_error();
1278 "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1279 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1280 << "SSL error: " << error << ", errno: " << errno
1281 << ", func: " << ERR_func_error_string(lastError)
1282 << ", reason: " << ERR_reason_error_string(lastError);
1283 if (error != SSL_ERROR_SYSCALL) {
1284 if ((unsigned long)lastError < 0x8000) {
1291 if (!zero_return(error, bytes)) {
1293 } // else fall through to below to correctly record totalWritten
1297 totalWritten += bytes;
1299 if (bytes == (ssize_t)len) {
1300 // The full iovec is written.
1301 (*countWritten) += 1 + buffersStolen;
1305 bytes += offset; // adjust bytes to account for all of v
1306 while (bytes >= (ssize_t)v->iov_len) {
1307 // We combined this buf with part or all of the next one, and
1308 // we managed to write all of this buf but not all of the bytes
1309 // from the next one that we'd hoped to write.
1310 bytes -= v->iov_len;
1314 *partialWritten = bytes;
1315 return totalWritten;
1319 return totalWritten;
1322 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1324 if (eor && SSL_get_wbio(ssl)->method == &eorAwareBioMethod) {
1325 if (appEorByteNo_) {
1326 // cannot track for more than one app byte EOR
1327 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1329 appEorByteNo_ = appBytesWritten_ + n;
1332 // 1. It is fine to keep updating minEorRawByteNo_.
1333 // 2. It is _min_ in the sense that SSL record will add some overhead.
1334 minEorRawByteNo_ = getRawBytesWritten() + n;
1337 n = sslWriteImpl(ssl, buf, n);
1339 appBytesWritten_ += n;
1340 if (appEorByteNo_) {
1341 if (getRawBytesWritten() >= minEorRawByteNo_) {
1342 minEorRawByteNo_ = 0;
1344 if(appBytesWritten_ == appEorByteNo_) {
1347 CHECK(appBytesWritten_ < appEorByteNo_);
1355 AsyncSSLSocket::sslInfoCallback(const SSL *ssl, int where, int ret) {
1356 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1357 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1358 sslSocket->renegotiateAttempted_ = true;
1362 int AsyncSSLSocket::eorAwareBioWrite(BIO *b, const char *in, int inl) {
1367 AsyncSSLSocket *tsslSock;
1369 iov.iov_base = const_cast<char *>(in);
1371 memset(&msg, 0, sizeof(msg));
1376 reinterpret_cast<AsyncSSLSocket*>(BIO_get_app_data(b));
1378 tsslSock->minEorRawByteNo_ &&
1379 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1384 ret = sendmsg(b->num, &msg, flags);
1385 BIO_clear_retry_flags(b);
1387 if (BIO_sock_should_retry(ret))
1388 BIO_set_retry_write(b);
1393 int AsyncSSLSocket::sslVerifyCallback(int preverifyOk,
1394 X509_STORE_CTX* x509Ctx) {
1395 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1396 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1397 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1399 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1400 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1401 return (self->handshakeCallback_) ?
1402 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1406 void AsyncSSLSocket::enableClientHelloParsing() {
1407 parseClientHello_ = true;
1408 clientHelloInfo_.reset(new ClientHelloInfo());
1411 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1412 SSL_set_msg_callback(ssl, nullptr);
1413 SSL_set_msg_callback_arg(ssl, nullptr);
1414 clientHelloInfo_->clientHelloBuf_.clear();
1418 AsyncSSLSocket::clientHelloParsingCallback(int written, int version,
1419 int contentType, const void *buf, size_t len, SSL *ssl, void *arg)
1421 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1423 sock->resetClientHelloParsing(ssl);
1426 if (contentType != SSL3_RT_HANDSHAKE) {
1427 sock->resetClientHelloParsing(ssl);
1434 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1435 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1437 Cursor cursor(clientHelloBuf.front());
1438 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1439 sock->resetClientHelloParsing(ssl);
1443 if (cursor.totalLength() < 3) {
1444 clientHelloBuf.trimEnd(len);
1445 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1449 uint32_t messageLength = cursor.read<uint8_t>();
1450 messageLength <<= 8;
1451 messageLength |= cursor.read<uint8_t>();
1452 messageLength <<= 8;
1453 messageLength |= cursor.read<uint8_t>();
1454 if (cursor.totalLength() < messageLength) {
1455 clientHelloBuf.trimEnd(len);
1456 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1460 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1461 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1463 cursor.skip(4); // gmt_unix_time
1464 cursor.skip(28); // random_bytes
1466 cursor.skip(cursor.read<uint8_t>()); // session_id
1468 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1469 for (int i = 0; i < cipherSuitesLength; i += 2) {
1470 sock->clientHelloInfo_->
1471 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1474 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1475 for (int i = 0; i < compressionMethodsLength; ++i) {
1476 sock->clientHelloInfo_->
1477 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1480 if (cursor.totalLength() > 0) {
1481 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1482 while (extensionsLength) {
1483 sock->clientHelloInfo_->
1484 clientHelloExtensions_.push_back(cursor.readBE<uint16_t>());
1485 extensionsLength -= 2;
1486 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1487 extensionsLength -= 2;
1488 cursor.skip(extensionDataLength);
1489 extensionsLength -= extensionDataLength;
1492 } catch (std::out_of_range& e) {
1493 // we'll use what we found and cleanup below.
1494 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1495 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1498 sock->resetClientHelloParsing(ssl);