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
223 // SSL_CTX_set_mode is a Macro
224 #ifdef SSL_MODE_WRITE_IOVEC
225 SSL_CTX_set_mode(ctx,
226 SSL_CTX_get_mode(ctx)
227 | SSL_MODE_WRITE_IOVEC);
232 BIO_METHOD eorAwareBioMethod;
234 void* initEorBioMethod(void) {
235 memcpy(&eorAwareBioMethod, BIO_s_socket(), sizeof(eorAwareBioMethod));
236 // override the bwrite method for MSG_EOR support
237 eorAwareBioMethod.bwrite = AsyncSSLSocket::eorAwareBioWrite;
239 // Note that the eorAwareBioMethod.type and eorAwareBioMethod.name are not
240 // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
241 // then have specific handlings. The eorAwareBioWrite should be compatible
242 // with the one in openssl.
244 // Return something here to enable AsyncSSLSocket to call this method using
245 // a function-scoped static.
249 } // anonymous namespace
253 SSLException::SSLException(int sslError, int errno_copy):
254 AsyncSocketException(
255 AsyncSocketException::SSL_ERROR,
256 ERR_error_string(sslError, msg_),
257 sslError == SSL_ERROR_SYSCALL ? errno_copy : 0), error_(sslError) {}
260 * Create a client AsyncSSLSocket
262 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
263 EventBase* evb, bool deferSecurityNegotiation) :
266 handshakeTimeout_(this, evb) {
268 if (deferSecurityNegotiation) {
269 sslState_ = STATE_UNENCRYPTED;
274 * Create a server/client AsyncSSLSocket
276 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
277 EventBase* evb, int fd, bool server,
278 bool deferSecurityNegotiation) :
279 AsyncSocket(evb, fd),
282 handshakeTimeout_(this, evb) {
285 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
286 AsyncSSLSocket::sslInfoCallback);
288 if (deferSecurityNegotiation) {
289 sslState_ = STATE_UNENCRYPTED;
293 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
295 * Create a client AsyncSSLSocket and allow tlsext_hostname
296 * to be sent in Client Hello.
298 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
300 const std::string& serverName,
301 bool deferSecurityNegotiation) :
302 AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
303 tlsextHostname_ = serverName;
307 * Create a client AsyncSSLSocket from an already connected fd
308 * and allow tlsext_hostname to be sent in Client Hello.
310 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
311 EventBase* evb, int fd,
312 const std::string& serverName,
313 bool deferSecurityNegotiation) :
314 AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
315 tlsextHostname_ = serverName;
319 AsyncSSLSocket::~AsyncSSLSocket() {
320 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
321 << ", evb=" << eventBase_ << ", fd=" << fd_
322 << ", state=" << int(state_) << ", sslState="
323 << sslState_ << ", events=" << eventFlags_ << ")";
326 void AsyncSSLSocket::init() {
327 // Do this here to ensure we initialize this once before any use of
328 // AsyncSSLSocket instances and not as part of library load.
329 static const auto eorAwareBioMethodInitializer = initEorBioMethod();
330 setup_SSL_CTX(ctx_->getSSLCtx());
333 void AsyncSSLSocket::closeNow() {
334 // Close the SSL connection.
335 if (ssl_ != nullptr && fd_ != -1) {
336 int rc = SSL_shutdown(ssl_);
338 rc = SSL_shutdown(ssl_);
345 if (sslSession_ != nullptr) {
346 SSL_SESSION_free(sslSession_);
347 sslSession_ = nullptr;
350 sslState_ = STATE_CLOSED;
352 if (handshakeTimeout_.isScheduled()) {
353 handshakeTimeout_.cancelTimeout();
356 DestructorGuard dg(this);
358 if (handshakeCallback_) {
359 AsyncSocketException ex(AsyncSocketException::END_OF_FILE,
360 "SSL connection closed locally");
361 HandshakeCB* callback = handshakeCallback_;
362 handshakeCallback_ = nullptr;
363 callback->handshakeErr(this, ex);
366 if (ssl_ != nullptr) {
372 AsyncSocket::closeNow();
375 void AsyncSSLSocket::shutdownWrite() {
376 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
378 // (Performing a full shutdown here is more desirable than doing nothing at
379 // all. The purpose of shutdownWrite() is normally to notify the other end
380 // of the connection that no more data will be sent. If we do nothing, the
381 // other end will never know that no more data is coming, and this may result
382 // in protocol deadlock.)
386 void AsyncSSLSocket::shutdownWriteNow() {
390 bool AsyncSSLSocket::good() const {
391 return (AsyncSocket::good() &&
392 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
393 sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
396 // The TAsyncTransport definition of 'good' states that the transport is
397 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
398 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
399 // is connected but we haven't initiated the call to SSL_connect.
400 bool AsyncSSLSocket::connecting() const {
402 (AsyncSocket::connecting() ||
403 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
404 sslState_ == STATE_CONNECTING))));
407 bool AsyncSSLSocket::isEorTrackingEnabled() const {
408 const BIO *wb = SSL_get_wbio(ssl_);
409 return wb && wb->method == &eorAwareBioMethod;
412 void AsyncSSLSocket::setEorTracking(bool track) {
413 BIO *wb = SSL_get_wbio(ssl_);
415 throw AsyncSocketException(AsyncSocketException::INVALID_STATE,
416 "setting EOR tracking without an initialized "
421 if (wb->method != &eorAwareBioMethod) {
422 // only do this if we didn't
423 wb->method = &eorAwareBioMethod;
424 BIO_set_app_data(wb, this);
426 minEorRawByteNo_ = 0;
428 } else if (wb->method == &eorAwareBioMethod) {
429 wb->method = BIO_s_socket();
430 BIO_set_app_data(wb, nullptr);
432 minEorRawByteNo_ = 0;
434 CHECK(wb->method == BIO_s_socket());
438 size_t AsyncSSLSocket::getRawBytesWritten() const {
440 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
444 return BIO_number_written(b);
447 size_t AsyncSSLSocket::getRawBytesReceived() const {
449 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
453 return BIO_number_read(b);
457 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
458 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
459 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
460 << "events=" << eventFlags_ << ", server=" << short(server_) << "): "
461 << "sslAccept/Connect() called in invalid "
462 << "state, handshake callback " << handshakeCallback_ << ", new callback "
464 assert(!handshakeTimeout_.isScheduled());
465 sslState_ = STATE_ERROR;
467 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
468 "sslAccept() called with socket in invalid state");
471 callback->handshakeErr(this, ex);
474 // Check the socket state not the ssl state here.
475 if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
476 failHandshake(__func__, ex);
480 void AsyncSSLSocket::sslAccept(HandshakeCB* callback, uint32_t timeout,
481 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
482 DestructorGuard dg(this);
483 assert(eventBase_->isInEventBaseThread());
484 verifyPeer_ = verifyPeer;
486 // Make sure we're in the uninitialized state
487 if (!server_ || (sslState_ != STATE_UNINIT &&
488 sslState_ != STATE_UNENCRYPTED) ||
489 handshakeCallback_ != nullptr) {
490 return invalidState(callback);
493 sslState_ = STATE_ACCEPTING;
494 handshakeCallback_ = callback;
497 handshakeTimeout_.scheduleTimeout(timeout);
500 /* register for a read operation (waiting for CLIENT HELLO) */
501 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
504 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
505 void AsyncSSLSocket::attachSSLContext(
506 const std::shared_ptr<SSLContext>& ctx) {
508 // Check to ensure we are in client mode. Changing a server's ssl
509 // context doesn't make sense since clients of that server would likely
510 // become confused when the server's context changes.
514 DCHECK(ctx->getSSLCtx());
517 // In order to call attachSSLContext, detachSSLContext must have been
518 // previously called which sets the socket's context to the dummy
519 // context. Thus we must acquire this lock.
520 SpinLockGuard guard(dummyCtxLock);
521 SSL_set_SSL_CTX(ssl_, ctx->getSSLCtx());
524 void AsyncSSLSocket::detachSSLContext() {
527 // We aren't using the initial_ctx for now, and it can introduce race
528 // conditions in the destructor of the SSL object.
529 #ifndef OPENSSL_NO_TLSEXT
530 if (ssl_->initial_ctx) {
531 SSL_CTX_free(ssl_->initial_ctx);
532 ssl_->initial_ctx = nullptr;
535 SpinLockGuard guard(dummyCtxLock);
536 if (nullptr == dummyCtx) {
537 // We need to lazily initialize the dummy context so we don't
538 // accidentally override any programmatic settings to openssl
539 dummyCtx = new SSLContext;
541 // We must remove this socket's references to its context right now
542 // since this socket could get passed to any thread. If the context has
543 // had its locking disabled, just doing a set in attachSSLContext()
544 // would not be thread safe.
545 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
549 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
550 void AsyncSSLSocket::switchServerSSLContext(
551 const std::shared_ptr<SSLContext>& handshakeCtx) {
553 if (sslState_ != STATE_ACCEPTING) {
554 // We log it here and allow the switch.
555 // It should not affect our re-negotiation support (which
556 // is not supported now).
557 VLOG(6) << "fd=" << getFd()
558 << " renegotation detected when switching SSL_CTX";
561 setup_SSL_CTX(handshakeCtx->getSSLCtx());
562 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
563 AsyncSSLSocket::sslInfoCallback);
564 handshakeCtx_ = handshakeCtx;
565 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
568 bool AsyncSSLSocket::isServerNameMatch() const {
575 SSL_SESSION *ss = SSL_get_session(ssl_);
580 if(!ss->tlsext_hostname) {
583 return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
586 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
587 tlsextHostname_ = std::move(serverName);
592 void AsyncSSLSocket::timeoutExpired() noexcept {
593 if (state_ == StateEnum::ESTABLISHED &&
594 (sslState_ == STATE_CACHE_LOOKUP ||
595 sslState_ == STATE_RSA_ASYNC_PENDING)) {
596 sslState_ = STATE_ERROR;
597 // We are expecting a callback in restartSSLAccept. The cache lookup
598 // and rsa-call necessarily have pointers to this ssl socket, so delay
599 // the cleanup until he calls us back.
601 assert(state_ == StateEnum::ESTABLISHED &&
602 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
603 DestructorGuard dg(this);
604 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
605 (sslState_ == STATE_CONNECTING) ?
606 "SSL connect timed out" : "SSL accept timed out");
607 failHandshake(__func__, ex);
611 int AsyncSSLSocket::sslExDataIndex_ = -1;
612 std::mutex AsyncSSLSocket::mutex_;
614 int AsyncSSLSocket::getSSLExDataIndex() {
615 if (sslExDataIndex_ < 0) {
616 std::lock_guard<std::mutex> g(mutex_);
617 if (sslExDataIndex_ < 0) {
618 sslExDataIndex_ = SSL_get_ex_new_index(0,
619 (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
622 return sslExDataIndex_;
625 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
626 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
627 getSSLExDataIndex()));
630 void AsyncSSLSocket::failHandshake(const char* fn,
631 const AsyncSocketException& ex) {
634 if (handshakeTimeout_.isScheduled()) {
635 handshakeTimeout_.cancelTimeout();
637 if (handshakeCallback_ != nullptr) {
638 HandshakeCB* callback = handshakeCallback_;
639 handshakeCallback_ = nullptr;
640 callback->handshakeErr(this, ex);
646 void AsyncSSLSocket::invokeHandshakeCB() {
647 if (handshakeTimeout_.isScheduled()) {
648 handshakeTimeout_.cancelTimeout();
650 if (handshakeCallback_) {
651 HandshakeCB* callback = handshakeCallback_;
652 handshakeCallback_ = nullptr;
653 callback->handshakeSuc(this);
657 void AsyncSSLSocket::connect(ConnectCallback* callback,
658 const folly::SocketAddress& address,
660 const OptionMap &options,
661 const folly::SocketAddress& bindAddr)
664 assert(state_ == StateEnum::UNINIT);
665 assert(sslState_ == STATE_UNINIT);
666 AsyncSSLSocketConnector *connector =
667 new AsyncSSLSocketConnector(this, callback, timeout);
668 AsyncSocket::connect(connector, address, timeout, options, bindAddr);
671 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
672 // apply the settings specified in verifyPeer_
673 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
674 if(ctx_->needsPeerVerification()) {
675 SSL_set_verify(ssl, ctx_->getVerificationMode(),
676 AsyncSSLSocket::sslVerifyCallback);
679 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
680 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
681 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
682 AsyncSSLSocket::sslVerifyCallback);
687 void AsyncSSLSocket::sslConn(HandshakeCB* callback, uint64_t timeout,
688 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
689 DestructorGuard dg(this);
690 assert(eventBase_->isInEventBaseThread());
692 verifyPeer_ = verifyPeer;
694 // Make sure we're in the uninitialized state
695 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
696 STATE_UNENCRYPTED) ||
697 handshakeCallback_ != nullptr) {
698 return invalidState(callback);
701 sslState_ = STATE_CONNECTING;
702 handshakeCallback_ = callback;
705 ssl_ = ctx_->createSSL();
706 } catch (std::exception &e) {
707 sslState_ = STATE_ERROR;
708 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
709 "error calling SSLContext::createSSL()");
710 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
711 << fd_ << "): " << e.what();
712 return failHandshake(__func__, ex);
715 applyVerificationOptions(ssl_);
717 SSL_set_fd(ssl_, fd_);
718 if (sslSession_ != nullptr) {
719 SSL_set_session(ssl_, sslSession_);
720 SSL_SESSION_free(sslSession_);
721 sslSession_ = nullptr;
723 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
724 if (tlsextHostname_.size()) {
725 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
729 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
732 handshakeTimeout_.scheduleTimeout(timeout);
738 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
739 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
740 return SSL_get1_session(ssl_);
746 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
747 sslSession_ = session;
748 if (!takeOwnership && session != nullptr) {
749 // Increment the reference count
750 CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
754 void AsyncSSLSocket::getSelectedNextProtocol(const unsigned char** protoName,
755 unsigned* protoLen) const {
756 if (!getSelectedNextProtocolNoThrow(protoName, protoLen)) {
757 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
758 "NPN not supported");
762 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
763 const unsigned char** protoName,
764 unsigned* protoLen) const {
765 *protoName = nullptr;
767 #ifdef OPENSSL_NPN_NEGOTIATED
768 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
775 bool AsyncSSLSocket::getSSLSessionReused() const {
776 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
777 return SSL_session_reused(ssl_);
782 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
783 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
786 const char *AsyncSSLSocket::getSSLServerName() const {
787 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
788 return (ssl_ != nullptr) ? SSL_get_servername(ssl_, TLSEXT_NAMETYPE_host_name)
791 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
792 "SNI not supported");
796 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
798 return getSSLServerName();
799 } catch (AsyncSocketException& ex) {
804 int AsyncSSLSocket::getSSLVersion() const {
805 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
808 int AsyncSSLSocket::getSSLCertSize() const {
810 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
812 EVP_PKEY *key = X509_get_pubkey(cert);
813 certSize = EVP_PKEY_bits(key);
819 bool AsyncSSLSocket::willBlock(int ret, int *errorOut) noexcept {
820 int error = *errorOut = SSL_get_error(ssl_, ret);
821 if (error == SSL_ERROR_WANT_READ) {
822 // Register for read event if not already.
823 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
825 } else if (error == SSL_ERROR_WANT_WRITE) {
826 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
827 << ", state=" << int(state_) << ", sslState="
828 << sslState_ << ", events=" << eventFlags_ << "): "
829 << "SSL_ERROR_WANT_WRITE";
830 // Register for write event if not already.
831 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
833 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
834 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
835 // We will block but we can't register our own socket. The callback that
836 // triggered this code will re-call handleAccept at the appropriate time.
838 // We can only get here if the linked libssl.so has support for this feature
839 // as well, otherwise SSL_get_error cannot return our error code.
840 sslState_ = STATE_CACHE_LOOKUP;
842 // Unregister for all events while blocked here
843 updateEventRegistration(EventHandler::NONE,
844 EventHandler::READ | EventHandler::WRITE);
846 // The timeout (if set) keeps running here
849 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
850 } else if (error == SSL_ERROR_WANT_RSA_ASYNC_PENDING) {
851 // Our custom openssl function has kicked off an async request to do
852 // modular exponentiation. When that call returns, a callback will
853 // be invoked that will re-call handleAccept.
854 sslState_ = STATE_RSA_ASYNC_PENDING;
856 // Unregister for all events while blocked here
857 updateEventRegistration(
859 EventHandler::READ | EventHandler::WRITE
862 // The timeout (if set) keeps running here
866 // SSL_ERROR_ZERO_RETURN is processed here so we can get some detail
868 long lastError = ERR_get_error();
869 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
870 << "state=" << state_ << ", "
871 << "sslState=" << sslState_ << ", "
872 << "events=" << std::hex << eventFlags_ << "): "
873 << "SSL error: " << error << ", "
874 << "errno: " << errno << ", "
875 << "ret: " << ret << ", "
876 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
877 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
878 << "func: " << ERR_func_error_string(lastError) << ", "
879 << "reason: " << ERR_reason_error_string(lastError);
880 if (error != SSL_ERROR_SYSCALL) {
881 if (error == SSL_ERROR_SSL) {
882 *errorOut = lastError;
884 if ((unsigned long)lastError < 0x8000) {
895 void AsyncSSLSocket::checkForImmediateRead() noexcept {
896 // openssl may have buffered data that it read from the socket already.
897 // In this case we have to process it immediately, rather than waiting for
898 // the socket to become readable again.
899 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
900 AsyncSocket::handleRead();
905 AsyncSSLSocket::restartSSLAccept()
907 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this << ", fd=" << fd_
908 << ", state=" << int(state_) << ", "
909 << "sslState=" << sslState_ << ", events=" << eventFlags_;
910 DestructorGuard dg(this);
912 sslState_ == STATE_CACHE_LOOKUP ||
913 sslState_ == STATE_RSA_ASYNC_PENDING ||
914 sslState_ == STATE_ERROR ||
915 sslState_ == STATE_CLOSED
917 if (sslState_ == STATE_CLOSED) {
918 // I sure hope whoever closed this socket didn't delete it already,
919 // but this is not strictly speaking an error
922 if (sslState_ == STATE_ERROR) {
923 // go straight to fail if timeout expired during lookup
924 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
925 "SSL accept timed out");
926 failHandshake(__func__, ex);
929 sslState_ = STATE_ACCEPTING;
930 this->handleAccept();
934 AsyncSSLSocket::handleAccept() noexcept {
935 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
936 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
937 << "sslState=" << sslState_ << ", events=" << eventFlags_;
939 assert(state_ == StateEnum::ESTABLISHED &&
940 sslState_ == STATE_ACCEPTING);
942 /* lazily create the SSL structure */
944 ssl_ = ctx_->createSSL();
945 } catch (std::exception &e) {
946 sslState_ = STATE_ERROR;
947 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
948 "error calling SSLContext::createSSL()");
949 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
950 << ", fd=" << fd_ << "): " << e.what();
951 return failHandshake(__func__, ex);
953 SSL_set_fd(ssl_, fd_);
954 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
956 applyVerificationOptions(ssl_);
959 if (server_ && parseClientHello_) {
960 SSL_set_msg_callback_arg(ssl_, this);
961 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
965 int ret = SSL_accept(ssl_);
968 if (willBlock(ret, &error)) {
971 sslState_ = STATE_ERROR;
972 SSLException ex(error, errno);
973 return failHandshake(__func__, ex);
977 handshakeComplete_ = true;
978 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
980 // Move into STATE_ESTABLISHED in the normal case that we are in
982 sslState_ = STATE_ESTABLISHED;
984 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
985 << " successfully accepted; state=" << int(state_)
986 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
988 // Remember the EventBase we are attached to, before we start invoking any
989 // callbacks (since the callbacks may call detachEventBase()).
990 EventBase* originalEventBase = eventBase_;
992 // Call the accept callback.
995 // Note that the accept callback may have changed our state.
996 // (set or unset the read callback, called write(), closed the socket, etc.)
997 // The following code needs to handle these situations correctly.
999 // If the socket has been closed, readCallback_ and writeReqHead_ will
1000 // always be nullptr, so that will prevent us from trying to read or write.
1002 // The main thing to check for is if eventBase_ is still originalEventBase.
1003 // If not, we have been detached from this event base, so we shouldn't
1004 // perform any more operations.
1005 if (eventBase_ != originalEventBase) {
1009 AsyncSocket::handleInitialReadWrite();
1013 AsyncSSLSocket::handleConnect() noexcept {
1014 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1015 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1016 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1018 if (state_ < StateEnum::ESTABLISHED) {
1019 return AsyncSocket::handleConnect();
1022 assert(state_ == StateEnum::ESTABLISHED &&
1023 sslState_ == STATE_CONNECTING);
1027 int ret = SSL_connect(ssl_);
1030 if (willBlock(ret, &error)) {
1033 sslState_ = STATE_ERROR;
1034 SSLException ex(error, errno);
1035 return failHandshake(__func__, ex);
1039 handshakeComplete_ = true;
1040 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1042 // Move into STATE_ESTABLISHED in the normal case that we are in
1043 // STATE_CONNECTING.
1044 sslState_ = STATE_ESTABLISHED;
1046 VLOG(3) << "AsyncSSLSocket %p: fd %d successfully connected; "
1047 << "state=" << int(state_) << ", sslState=" << sslState_
1048 << ", events=" << eventFlags_;
1050 // Remember the EventBase we are attached to, before we start invoking any
1051 // callbacks (since the callbacks may call detachEventBase()).
1052 EventBase* originalEventBase = eventBase_;
1054 // Call the handshake callback.
1055 invokeHandshakeCB();
1057 // Note that the connect callback may have changed our state.
1058 // (set or unset the read callback, called write(), closed the socket, etc.)
1059 // The following code needs to handle these situations correctly.
1061 // If the socket has been closed, readCallback_ and writeReqHead_ will
1062 // always be nullptr, so that will prevent us from trying to read or write.
1064 // The main thing to check for is if eventBase_ is still originalEventBase.
1065 // If not, we have been detached from this event base, so we shouldn't
1066 // perform any more operations.
1067 if (eventBase_ != originalEventBase) {
1071 AsyncSocket::handleInitialReadWrite();
1075 AsyncSSLSocket::handleRead() noexcept {
1076 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1077 << ", state=" << int(state_) << ", "
1078 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1079 if (state_ < StateEnum::ESTABLISHED) {
1080 return AsyncSocket::handleRead();
1084 if (sslState_ == STATE_ACCEPTING) {
1089 else if (sslState_ == STATE_CONNECTING) {
1096 AsyncSocket::handleRead();
1100 AsyncSSLSocket::performRead(void* buf, size_t buflen) {
1101 if (sslState_ == STATE_UNENCRYPTED) {
1102 return AsyncSocket::performRead(buf, buflen);
1106 ssize_t bytes = SSL_read(ssl_, buf, buflen);
1107 if (server_ && renegotiateAttempted_) {
1108 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1109 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1110 << "): client intitiated SSL renegotiation not permitted";
1111 // We pack our own SSLerr here with a dummy function
1112 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1113 SSL_CLIENT_RENEGOTIATION_ATTEMPT);
1118 int error = SSL_get_error(ssl_, bytes);
1119 if (error == SSL_ERROR_WANT_READ) {
1120 // The caller will register for read event if not already.
1121 return READ_BLOCKING;
1122 } else if (error == SSL_ERROR_WANT_WRITE) {
1123 // TODO: Even though we are attempting to read data, SSL_read() may
1124 // need to write data if renegotiation is being performed. We currently
1125 // don't support this and just fail the read.
1126 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1127 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1128 << "): unsupported SSL renegotiation during read",
1129 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1130 SSL_INVALID_RENEGOTIATION);
1134 // TODO: Fix this code so that it can return a proper error message
1135 // to the callback, rather than relying on AsyncSocket code which
1136 // can't handle SSL errors.
1137 long lastError = ERR_get_error();
1139 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1140 << "state=" << state_ << ", "
1141 << "sslState=" << sslState_ << ", "
1142 << "events=" << std::hex << eventFlags_ << "): "
1143 << "bytes: " << bytes << ", "
1144 << "error: " << error << ", "
1145 << "errno: " << errno << ", "
1146 << "func: " << ERR_func_error_string(lastError) << ", "
1147 << "reason: " << ERR_reason_error_string(lastError);
1149 if (zero_return(error, bytes)) {
1152 if (error != SSL_ERROR_SYSCALL) {
1153 if ((unsigned long)lastError < 0x8000) {
1162 appBytesReceived_ += bytes;
1167 void AsyncSSLSocket::handleWrite() noexcept {
1168 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1169 << ", state=" << int(state_) << ", "
1170 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1171 if (state_ < StateEnum::ESTABLISHED) {
1172 return AsyncSocket::handleWrite();
1175 if (sslState_ == STATE_ACCEPTING) {
1181 if (sslState_ == STATE_CONNECTING) {
1188 AsyncSocket::handleWrite();
1191 int AsyncSSLSocket::interpretSSLError(int rc, int error) {
1192 if (error == SSL_ERROR_WANT_READ) {
1193 // TODO: Even though we are attempting to write data, SSL_write() may
1194 // need to read data if renegotiation is being performed. We currently
1195 // don't support this and just fail the write.
1196 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1197 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1198 << "): " << "unsupported SSL renegotiation during write",
1199 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1200 SSL_INVALID_RENEGOTIATION);
1204 // TODO: Fix this code so that it can return a proper error message
1205 // to the callback, rather than relying on AsyncSocket code which
1206 // can't handle SSL errors.
1207 long lastError = ERR_get_error();
1208 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1209 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1210 << "SSL error: " << error << ", errno: " << errno
1211 << ", func: " << ERR_func_error_string(lastError)
1212 << ", reason: " << ERR_reason_error_string(lastError);
1213 if (error != SSL_ERROR_SYSCALL) {
1214 if ((unsigned long)lastError < 0x8000) {
1221 if (!zero_return(error, rc)) {
1229 ssize_t AsyncSSLSocket::performWrite(const iovec* vec,
1232 uint32_t* countWritten,
1233 uint32_t* partialWritten) {
1234 if (sslState_ == STATE_UNENCRYPTED) {
1235 return AsyncSocket::performWrite(
1236 vec, count, flags, countWritten, partialWritten);
1238 if (sslState_ != STATE_ESTABLISHED) {
1239 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1240 << ", sslState=" << sslState_
1241 << ", events=" << eventFlags_ << "): "
1242 << "TODO: AsyncSSLSocket currently does not support calling "
1243 << "write() before the handshake has fully completed";
1244 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1249 bool cork = isSet(flags, WriteFlags::CORK);
1250 CorkGuard guard(fd_, count > 1, cork, &corked_);
1252 #ifdef SSL_MODE_WRITE_IOVEC
1253 if (ssl_->mode & SSL_MODE_WRITE_IOVEC) {
1254 return performWriteIovec(vec, count, flags, countWritten, partialWritten);
1258 // Declare a buffer used to hold small write requests. It could point to a
1259 // memory block either on stack or on heap. If it is on heap, we release it
1260 // manually when scope exits
1261 char* combinedBuf{nullptr};
1263 // Note, always keep this check consistent with what we do below
1264 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1265 delete[] combinedBuf;
1270 *partialWritten = 0;
1271 ssize_t totalWritten = 0;
1272 size_t bytesStolenFromNextBuffer = 0;
1273 for (uint32_t i = 0; i < count; i++) {
1274 const iovec* v = vec + i;
1275 size_t offset = bytesStolenFromNextBuffer;
1276 bytesStolenFromNextBuffer = 0;
1277 size_t len = v->iov_len - offset;
1283 buf = ((const char*)v->iov_base) + offset;
1287 uint32_t buffersStolen = 0;
1288 if ((len < minWriteSize_) && ((i + 1) < count)) {
1289 // Combine this buffer with part or all of the next buffers in
1290 // order to avoid really small-grained calls to SSL_write().
1291 // Each call to SSL_write() produces a separate record in
1292 // the egress SSL stream, and we've found that some low-end
1293 // mobile clients can't handle receiving an HTTP response
1294 // header and the first part of the response body in two
1295 // separate SSL records (even if those two records are in
1296 // the same TCP packet).
1298 if (combinedBuf == nullptr) {
1299 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1300 // Allocate the buffer on heap
1301 combinedBuf = new char[minWriteSize_];
1303 // Allocate the buffer on stack
1304 combinedBuf = (char*)alloca(minWriteSize_);
1307 assert(combinedBuf != nullptr);
1309 memcpy(combinedBuf, buf, len);
1311 // INVARIANT: i + buffersStolen == complete chunks serialized
1312 uint32_t nextIndex = i + buffersStolen + 1;
1313 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1314 minWriteSize_ - len);
1315 memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1316 bytesStolenFromNextBuffer);
1317 len += bytesStolenFromNextBuffer;
1318 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1319 // couldn't steal the whole buffer
1322 bytesStolenFromNextBuffer = 0;
1325 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1326 bytes = eorAwareSSLWrite(
1327 ssl_, combinedBuf, len,
1328 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1331 bytes = eorAwareSSLWrite(ssl_, buf, len,
1332 (isSet(flags, WriteFlags::EOR) && i + 1 == count));
1336 int error = SSL_get_error(ssl_, bytes);
1337 if (error == SSL_ERROR_WANT_WRITE) {
1338 // The caller will register for write event if not already.
1339 *partialWritten = offset;
1340 return totalWritten;
1342 int rc = interpretSSLError(bytes, error);
1345 } // else fall through to below to correctly record totalWritten
1348 totalWritten += bytes;
1350 if (bytes == (ssize_t)len) {
1351 // The full iovec is written.
1352 (*countWritten) += 1 + buffersStolen;
1356 bytes += offset; // adjust bytes to account for all of v
1357 while (bytes >= (ssize_t)v->iov_len) {
1358 // We combined this buf with part or all of the next one, and
1359 // we managed to write all of this buf but not all of the bytes
1360 // from the next one that we'd hoped to write.
1361 bytes -= v->iov_len;
1365 *partialWritten = bytes;
1366 return totalWritten;
1370 return totalWritten;
1373 #ifdef SSL_MODE_WRITE_IOVEC
1374 ssize_t AsyncSSLSocket::performWriteIovec(const iovec* vec,
1377 uint32_t* countWritten,
1378 uint32_t* partialWritten) {
1380 for (uint32_t j = 0; j < count; j++) {
1381 tot += vec[j].iov_len;
1384 ssize_t totalWritten = SSL_write_iovec(ssl_, vec, count);
1387 *partialWritten = 0;
1388 if (totalWritten <= 0) {
1389 return interpretSSLError(totalWritten, SSL_get_error(ssl_, totalWritten));
1391 ssize_t bytes = totalWritten, i = 0;
1392 while (i < count && bytes >= (ssize_t)vec[i].iov_len) {
1393 // we managed to write all of this buf
1394 bytes -= vec[i].iov_len;
1398 *partialWritten = bytes;
1400 VLOG(4) << "SSL_write_iovec() writes " << tot
1401 << ", returns " << totalWritten << " bytes"
1402 << ", max_send_fragment=" << ssl_->max_send_fragment
1403 << ", count=" << count << ", countWritten=" << *countWritten;
1405 return totalWritten;
1410 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1412 if (eor && SSL_get_wbio(ssl)->method == &eorAwareBioMethod) {
1413 if (appEorByteNo_) {
1414 // cannot track for more than one app byte EOR
1415 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1417 appEorByteNo_ = appBytesWritten_ + n;
1420 // 1. It is fine to keep updating minEorRawByteNo_.
1421 // 2. It is _min_ in the sense that SSL record will add some overhead.
1422 minEorRawByteNo_ = getRawBytesWritten() + n;
1425 n = sslWriteImpl(ssl, buf, n);
1427 appBytesWritten_ += n;
1428 if (appEorByteNo_) {
1429 if (getRawBytesWritten() >= minEorRawByteNo_) {
1430 minEorRawByteNo_ = 0;
1432 if(appBytesWritten_ == appEorByteNo_) {
1435 CHECK(appBytesWritten_ < appEorByteNo_);
1443 AsyncSSLSocket::sslInfoCallback(const SSL *ssl, int where, int ret) {
1444 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1445 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1446 sslSocket->renegotiateAttempted_ = true;
1450 int AsyncSSLSocket::eorAwareBioWrite(BIO *b, const char *in, int inl) {
1455 AsyncSSLSocket *tsslSock;
1457 iov.iov_base = const_cast<char *>(in);
1459 memset(&msg, 0, sizeof(msg));
1464 reinterpret_cast<AsyncSSLSocket*>(BIO_get_app_data(b));
1466 tsslSock->minEorRawByteNo_ &&
1467 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1472 ret = sendmsg(b->num, &msg, flags);
1473 BIO_clear_retry_flags(b);
1475 if (BIO_sock_should_retry(ret))
1476 BIO_set_retry_write(b);
1481 int AsyncSSLSocket::sslVerifyCallback(int preverifyOk,
1482 X509_STORE_CTX* x509Ctx) {
1483 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1484 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1485 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1487 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1488 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1489 return (self->handshakeCallback_) ?
1490 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1494 void AsyncSSLSocket::enableClientHelloParsing() {
1495 parseClientHello_ = true;
1496 clientHelloInfo_.reset(new ClientHelloInfo());
1499 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1500 SSL_set_msg_callback(ssl, nullptr);
1501 SSL_set_msg_callback_arg(ssl, nullptr);
1502 clientHelloInfo_->clientHelloBuf_.clear();
1506 AsyncSSLSocket::clientHelloParsingCallback(int written, int version,
1507 int contentType, const void *buf, size_t len, SSL *ssl, void *arg)
1509 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1511 sock->resetClientHelloParsing(ssl);
1514 if (contentType != SSL3_RT_HANDSHAKE) {
1515 sock->resetClientHelloParsing(ssl);
1522 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1523 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1525 Cursor cursor(clientHelloBuf.front());
1526 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1527 sock->resetClientHelloParsing(ssl);
1531 if (cursor.totalLength() < 3) {
1532 clientHelloBuf.trimEnd(len);
1533 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1537 uint32_t messageLength = cursor.read<uint8_t>();
1538 messageLength <<= 8;
1539 messageLength |= cursor.read<uint8_t>();
1540 messageLength <<= 8;
1541 messageLength |= cursor.read<uint8_t>();
1542 if (cursor.totalLength() < messageLength) {
1543 clientHelloBuf.trimEnd(len);
1544 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1548 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1549 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1551 cursor.skip(4); // gmt_unix_time
1552 cursor.skip(28); // random_bytes
1554 cursor.skip(cursor.read<uint8_t>()); // session_id
1556 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1557 for (int i = 0; i < cipherSuitesLength; i += 2) {
1558 sock->clientHelloInfo_->
1559 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1562 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1563 for (int i = 0; i < compressionMethodsLength; ++i) {
1564 sock->clientHelloInfo_->
1565 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1568 if (cursor.totalLength() > 0) {
1569 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1570 while (extensionsLength) {
1571 sock->clientHelloInfo_->
1572 clientHelloExtensions_.push_back(cursor.readBE<uint16_t>());
1573 extensionsLength -= 2;
1574 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1575 extensionsLength -= 2;
1576 cursor.skip(extensionDataLength);
1577 extensionsLength -= extensionDataLength;
1580 } catch (std::out_of_range& e) {
1581 // we'll use what we found and cleanup below.
1582 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1583 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1586 sock->resetClientHelloParsing(ssl);