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 ~AsyncSSLSocketConnector() override {}
90 AsyncSSLSocketConnector(AsyncSSLSocket *sslSocket,
91 AsyncSocket::ConnectCallback *callback,
93 sslSocket_(sslSocket),
96 startTime_(std::chrono::duration_cast<std::chrono::milliseconds>(
97 std::chrono::steady_clock::now().time_since_epoch()).count()) {
100 void connectSuccess() noexcept override {
101 VLOG(7) << "client socket connected";
103 int64_t timeoutLeft = 0;
105 auto curTime = std::chrono::duration_cast<std::chrono::milliseconds>(
106 std::chrono::steady_clock::now().time_since_epoch()).count();
108 timeoutLeft = timeout_ - (curTime - startTime_);
109 if (timeoutLeft <= 0) {
110 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
111 "SSL connect timed out");
117 sslSocket_->sslConn(this, timeoutLeft);
120 void connectErr(const AsyncSocketException& ex) noexcept override {
121 LOG(ERROR) << "TCP connect failed: " << ex.what();
126 void handshakeSuc(AsyncSSLSocket* sock) noexcept override {
127 VLOG(7) << "client handshake success";
129 callback_->connectSuccess();
134 void handshakeErr(AsyncSSLSocket* socket,
135 const AsyncSocketException& ex) noexcept override {
136 LOG(ERROR) << "client handshakeErr: " << ex.what();
141 void fail(const AsyncSocketException &ex) {
142 // fail is a noop if called twice
144 AsyncSSLSocket::ConnectCallback *cb = callback_;
148 sslSocket_->closeNow();
149 // closeNow can call handshakeErr if it hasn't been called already.
150 // So this may have been deleted, no member variable access beyond this
152 // Note that closeNow may invoke writeError callbacks if the socket had
153 // write data pending connection completion.
158 // XXX: implement an equivalent to corking for platforms with TCP_NOPUSH?
159 #ifdef TCP_CORK // Linux-only
161 * Utility class that corks a TCP socket upon construction or uncorks
162 * the socket upon destruction
164 class CorkGuard : private boost::noncopyable {
166 CorkGuard(int fd, bool multipleWrites, bool haveMore, bool* corked):
167 fd_(fd), haveMore_(haveMore), corked_(corked) {
169 // socket is already corked; nothing to do
172 if (multipleWrites || haveMore) {
173 // We are performing multiple writes in this performWrite() call,
174 // and/or there are more calls to performWrite() that will be invoked
175 // later, so enable corking
177 setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
184 // more data to come; don't uncork yet
188 // socket isn't corked; nothing to do
193 setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
203 class CorkGuard : private boost::noncopyable {
205 CorkGuard(int, bool, bool, bool*) {}
209 void setup_SSL_CTX(SSL_CTX *ctx) {
210 #ifdef SSL_MODE_RELEASE_BUFFERS
211 SSL_CTX_set_mode(ctx,
212 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
213 SSL_MODE_ENABLE_PARTIAL_WRITE
214 | SSL_MODE_RELEASE_BUFFERS
217 SSL_CTX_set_mode(ctx,
218 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
219 SSL_MODE_ENABLE_PARTIAL_WRITE
222 // SSL_CTX_set_mode is a Macro
223 #ifdef SSL_MODE_WRITE_IOVEC
224 SSL_CTX_set_mode(ctx,
225 SSL_CTX_get_mode(ctx)
226 | SSL_MODE_WRITE_IOVEC);
231 BIO_METHOD eorAwareBioMethod;
233 void* initEorBioMethod(void) {
234 memcpy(&eorAwareBioMethod, BIO_s_socket(), sizeof(eorAwareBioMethod));
235 // override the bwrite method for MSG_EOR support
236 eorAwareBioMethod.bwrite = AsyncSSLSocket::eorAwareBioWrite;
238 // Note that the eorAwareBioMethod.type and eorAwareBioMethod.name are not
239 // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
240 // then have specific handlings. The eorAwareBioWrite should be compatible
241 // with the one in openssl.
243 // Return something here to enable AsyncSSLSocket to call this method using
244 // a function-scoped static.
248 } // anonymous namespace
252 SSLException::SSLException(int sslError, int errno_copy):
253 AsyncSocketException(
254 AsyncSocketException::SSL_ERROR,
255 ERR_error_string(sslError, msg_),
256 sslError == SSL_ERROR_SYSCALL ? errno_copy : 0), error_(sslError) {}
259 * Create a client AsyncSSLSocket
261 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
262 EventBase* evb, bool deferSecurityNegotiation) :
265 handshakeTimeout_(this, evb) {
267 if (deferSecurityNegotiation) {
268 sslState_ = STATE_UNENCRYPTED;
273 * Create a server/client AsyncSSLSocket
275 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
276 EventBase* evb, int fd, bool server,
277 bool deferSecurityNegotiation) :
278 AsyncSocket(evb, fd),
281 handshakeTimeout_(this, evb) {
284 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
285 AsyncSSLSocket::sslInfoCallback);
287 if (deferSecurityNegotiation) {
288 sslState_ = STATE_UNENCRYPTED;
292 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
294 * Create a client AsyncSSLSocket and allow tlsext_hostname
295 * to be sent in Client Hello.
297 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
299 const std::string& serverName,
300 bool deferSecurityNegotiation) :
301 AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
302 tlsextHostname_ = serverName;
306 * Create a client AsyncSSLSocket from an already connected fd
307 * and allow tlsext_hostname to be sent in Client Hello.
309 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
310 EventBase* evb, int fd,
311 const std::string& serverName,
312 bool deferSecurityNegotiation) :
313 AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
314 tlsextHostname_ = serverName;
318 AsyncSSLSocket::~AsyncSSLSocket() {
319 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
320 << ", evb=" << eventBase_ << ", fd=" << fd_
321 << ", state=" << int(state_) << ", sslState="
322 << sslState_ << ", events=" << eventFlags_ << ")";
325 void AsyncSSLSocket::init() {
326 // Do this here to ensure we initialize this once before any use of
327 // AsyncSSLSocket instances and not as part of library load.
328 static const auto eorAwareBioMethodInitializer = initEorBioMethod();
329 (void)eorAwareBioMethodInitializer;
331 setup_SSL_CTX(ctx_->getSSLCtx());
334 void AsyncSSLSocket::closeNow() {
335 // Close the SSL connection.
336 if (ssl_ != nullptr && fd_ != -1) {
337 int rc = SSL_shutdown(ssl_);
339 rc = SSL_shutdown(ssl_);
346 if (sslSession_ != nullptr) {
347 SSL_SESSION_free(sslSession_);
348 sslSession_ = nullptr;
351 sslState_ = STATE_CLOSED;
353 if (handshakeTimeout_.isScheduled()) {
354 handshakeTimeout_.cancelTimeout();
357 DestructorGuard dg(this);
360 AsyncSocketException(
361 AsyncSocketException::END_OF_FILE,
362 "SSL connection closed locally"));
364 if (ssl_ != nullptr) {
370 AsyncSocket::closeNow();
373 void AsyncSSLSocket::shutdownWrite() {
374 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
376 // (Performing a full shutdown here is more desirable than doing nothing at
377 // all. The purpose of shutdownWrite() is normally to notify the other end
378 // of the connection that no more data will be sent. If we do nothing, the
379 // other end will never know that no more data is coming, and this may result
380 // in protocol deadlock.)
384 void AsyncSSLSocket::shutdownWriteNow() {
388 bool AsyncSSLSocket::good() const {
389 return (AsyncSocket::good() &&
390 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
391 sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
394 // The TAsyncTransport definition of 'good' states that the transport is
395 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
396 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
397 // is connected but we haven't initiated the call to SSL_connect.
398 bool AsyncSSLSocket::connecting() const {
400 (AsyncSocket::connecting() ||
401 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
402 sslState_ == STATE_CONNECTING))));
405 bool AsyncSSLSocket::isEorTrackingEnabled() const {
406 const BIO *wb = SSL_get_wbio(ssl_);
407 return wb && wb->method == &eorAwareBioMethod;
410 void AsyncSSLSocket::setEorTracking(bool track) {
411 BIO *wb = SSL_get_wbio(ssl_);
413 throw AsyncSocketException(AsyncSocketException::INVALID_STATE,
414 "setting EOR tracking without an initialized "
419 if (wb->method != &eorAwareBioMethod) {
420 // only do this if we didn't
421 wb->method = &eorAwareBioMethod;
422 BIO_set_app_data(wb, this);
424 minEorRawByteNo_ = 0;
426 } else if (wb->method == &eorAwareBioMethod) {
427 wb->method = BIO_s_socket();
428 BIO_set_app_data(wb, nullptr);
430 minEorRawByteNo_ = 0;
432 CHECK(wb->method == BIO_s_socket());
436 size_t AsyncSSLSocket::getRawBytesWritten() const {
438 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
442 return BIO_number_written(b);
445 size_t AsyncSSLSocket::getRawBytesReceived() const {
447 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
451 return BIO_number_read(b);
455 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
456 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
457 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
458 << "events=" << eventFlags_ << ", server=" << short(server_) << "): "
459 << "sslAccept/Connect() called in invalid "
460 << "state, handshake callback " << handshakeCallback_ << ", new callback "
462 assert(!handshakeTimeout_.isScheduled());
463 sslState_ = STATE_ERROR;
465 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
466 "sslAccept() called with socket in invalid state");
468 handshakeEndTime_ = std::chrono::steady_clock::now();
470 callback->handshakeErr(this, ex);
473 // Check the socket state not the ssl state here.
474 if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
475 failHandshake(__func__, ex);
479 void AsyncSSLSocket::sslAccept(HandshakeCB* callback, uint32_t timeout,
480 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
481 DestructorGuard dg(this);
482 assert(eventBase_->isInEventBaseThread());
483 verifyPeer_ = verifyPeer;
485 // Make sure we're in the uninitialized state
486 if (!server_ || (sslState_ != STATE_UNINIT &&
487 sslState_ != STATE_UNENCRYPTED) ||
488 handshakeCallback_ != nullptr) {
489 return invalidState(callback);
491 handshakeStartTime_ = std::chrono::steady_clock::now();
492 // Make end time at least >= start time.
493 handshakeEndTime_ = handshakeStartTime_;
495 sslState_ = STATE_ACCEPTING;
496 handshakeCallback_ = callback;
499 handshakeTimeout_.scheduleTimeout(timeout);
502 /* register for a read operation (waiting for CLIENT HELLO) */
503 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
506 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
507 void AsyncSSLSocket::attachSSLContext(
508 const std::shared_ptr<SSLContext>& ctx) {
510 // Check to ensure we are in client mode. Changing a server's ssl
511 // context doesn't make sense since clients of that server would likely
512 // become confused when the server's context changes.
516 DCHECK(ctx->getSSLCtx());
519 // In order to call attachSSLContext, detachSSLContext must have been
520 // previously called which sets the socket's context to the dummy
521 // context. Thus we must acquire this lock.
522 SpinLockGuard guard(dummyCtxLock);
523 SSL_set_SSL_CTX(ssl_, ctx->getSSLCtx());
526 void AsyncSSLSocket::detachSSLContext() {
529 // We aren't using the initial_ctx for now, and it can introduce race
530 // conditions in the destructor of the SSL object.
531 #ifndef OPENSSL_NO_TLSEXT
532 if (ssl_->initial_ctx) {
533 SSL_CTX_free(ssl_->initial_ctx);
534 ssl_->initial_ctx = nullptr;
537 SpinLockGuard guard(dummyCtxLock);
538 if (nullptr == dummyCtx) {
539 // We need to lazily initialize the dummy context so we don't
540 // accidentally override any programmatic settings to openssl
541 dummyCtx = new SSLContext;
543 // We must remove this socket's references to its context right now
544 // since this socket could get passed to any thread. If the context has
545 // had its locking disabled, just doing a set in attachSSLContext()
546 // would not be thread safe.
547 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
551 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
552 void AsyncSSLSocket::switchServerSSLContext(
553 const std::shared_ptr<SSLContext>& handshakeCtx) {
555 if (sslState_ != STATE_ACCEPTING) {
556 // We log it here and allow the switch.
557 // It should not affect our re-negotiation support (which
558 // is not supported now).
559 VLOG(6) << "fd=" << getFd()
560 << " renegotation detected when switching SSL_CTX";
563 setup_SSL_CTX(handshakeCtx->getSSLCtx());
564 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
565 AsyncSSLSocket::sslInfoCallback);
566 handshakeCtx_ = handshakeCtx;
567 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
570 bool AsyncSSLSocket::isServerNameMatch() const {
577 SSL_SESSION *ss = SSL_get_session(ssl_);
582 if(!ss->tlsext_hostname) {
585 return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
588 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
589 tlsextHostname_ = std::move(serverName);
594 void AsyncSSLSocket::timeoutExpired() noexcept {
595 if (state_ == StateEnum::ESTABLISHED &&
596 (sslState_ == STATE_CACHE_LOOKUP ||
597 sslState_ == STATE_RSA_ASYNC_PENDING)) {
598 sslState_ = STATE_ERROR;
599 // We are expecting a callback in restartSSLAccept. The cache lookup
600 // and rsa-call necessarily have pointers to this ssl socket, so delay
601 // the cleanup until he calls us back.
603 assert(state_ == StateEnum::ESTABLISHED &&
604 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
605 DestructorGuard dg(this);
606 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
607 (sslState_ == STATE_CONNECTING) ?
608 "SSL connect timed out" : "SSL accept timed out");
609 failHandshake(__func__, ex);
613 int AsyncSSLSocket::getSSLExDataIndex() {
614 static auto index = SSL_get_ex_new_index(
615 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
619 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
620 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
621 getSSLExDataIndex()));
624 void AsyncSSLSocket::failHandshake(const char* fn,
625 const AsyncSocketException& ex) {
627 if (handshakeTimeout_.isScheduled()) {
628 handshakeTimeout_.cancelTimeout();
630 invokeHandshakeErr(ex);
634 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
635 handshakeEndTime_ = std::chrono::steady_clock::now();
636 if (handshakeCallback_ != nullptr) {
637 HandshakeCB* callback = handshakeCallback_;
638 handshakeCallback_ = nullptr;
639 callback->handshakeErr(this, ex);
643 void AsyncSSLSocket::invokeHandshakeCB() {
644 handshakeEndTime_ = std::chrono::steady_clock::now();
645 if (handshakeTimeout_.isScheduled()) {
646 handshakeTimeout_.cancelTimeout();
648 if (handshakeCallback_) {
649 HandshakeCB* callback = handshakeCallback_;
650 handshakeCallback_ = nullptr;
651 callback->handshakeSuc(this);
655 void AsyncSSLSocket::connect(ConnectCallback* callback,
656 const folly::SocketAddress& address,
658 const OptionMap &options,
659 const folly::SocketAddress& bindAddr)
662 assert(state_ == StateEnum::UNINIT);
663 assert(sslState_ == STATE_UNINIT);
664 AsyncSSLSocketConnector *connector =
665 new AsyncSSLSocketConnector(this, callback, timeout);
666 AsyncSocket::connect(connector, address, timeout, options, bindAddr);
669 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
670 // apply the settings specified in verifyPeer_
671 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
672 if(ctx_->needsPeerVerification()) {
673 SSL_set_verify(ssl, ctx_->getVerificationMode(),
674 AsyncSSLSocket::sslVerifyCallback);
677 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
678 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
679 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
680 AsyncSSLSocket::sslVerifyCallback);
685 void AsyncSSLSocket::sslConn(HandshakeCB* callback, uint64_t timeout,
686 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
687 DestructorGuard dg(this);
688 assert(eventBase_->isInEventBaseThread());
690 verifyPeer_ = verifyPeer;
692 // Make sure we're in the uninitialized state
693 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
694 STATE_UNENCRYPTED) ||
695 handshakeCallback_ != nullptr) {
696 return invalidState(callback);
699 handshakeStartTime_ = std::chrono::steady_clock::now();
700 // Make end time at least >= start time.
701 handshakeEndTime_ = handshakeStartTime_;
703 sslState_ = STATE_CONNECTING;
704 handshakeCallback_ = callback;
707 ssl_ = ctx_->createSSL();
708 } catch (std::exception &e) {
709 sslState_ = STATE_ERROR;
710 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
711 "error calling SSLContext::createSSL()");
712 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
713 << fd_ << "): " << e.what();
714 return failHandshake(__func__, ex);
717 applyVerificationOptions(ssl_);
719 SSL_set_fd(ssl_, fd_);
720 if (sslSession_ != nullptr) {
721 SSL_set_session(ssl_, sslSession_);
722 SSL_SESSION_free(sslSession_);
723 sslSession_ = nullptr;
725 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
726 if (tlsextHostname_.size()) {
727 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
731 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
734 handshakeTimeout_.scheduleTimeout(timeout);
740 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
741 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
742 return SSL_get1_session(ssl_);
748 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
749 sslSession_ = session;
750 if (!takeOwnership && session != nullptr) {
751 // Increment the reference count
752 CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
756 void AsyncSSLSocket::getSelectedNextProtocol(const unsigned char** protoName,
757 unsigned* protoLen) const {
758 if (!getSelectedNextProtocolNoThrow(protoName, protoLen)) {
759 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
760 "NPN not supported");
764 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
765 const unsigned char** protoName,
766 unsigned* protoLen) const {
767 *protoName = nullptr;
769 #ifdef OPENSSL_NPN_NEGOTIATED
770 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
777 bool AsyncSSLSocket::getSSLSessionReused() const {
778 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
779 return SSL_session_reused(ssl_);
784 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
785 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
788 const char *AsyncSSLSocket::getSSLServerName() const {
789 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
790 return (ssl_ != nullptr) ? SSL_get_servername(ssl_, TLSEXT_NAMETYPE_host_name)
793 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
794 "SNI not supported");
798 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
800 return getSSLServerName();
801 } catch (AsyncSocketException& ex) {
806 int AsyncSSLSocket::getSSLVersion() const {
807 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
810 int AsyncSSLSocket::getSSLCertSize() const {
812 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
814 EVP_PKEY *key = X509_get_pubkey(cert);
815 certSize = EVP_PKEY_bits(key);
821 bool AsyncSSLSocket::willBlock(int ret, int *errorOut) noexcept {
822 int error = *errorOut = SSL_get_error(ssl_, ret);
823 if (error == SSL_ERROR_WANT_READ) {
824 // Register for read event if not already.
825 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
827 } else if (error == SSL_ERROR_WANT_WRITE) {
828 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
829 << ", state=" << int(state_) << ", sslState="
830 << sslState_ << ", events=" << eventFlags_ << "): "
831 << "SSL_ERROR_WANT_WRITE";
832 // Register for write event if not already.
833 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
835 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
836 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
837 // We will block but we can't register our own socket. The callback that
838 // triggered this code will re-call handleAccept at the appropriate time.
840 // We can only get here if the linked libssl.so has support for this feature
841 // as well, otherwise SSL_get_error cannot return our error code.
842 sslState_ = STATE_CACHE_LOOKUP;
844 // Unregister for all events while blocked here
845 updateEventRegistration(EventHandler::NONE,
846 EventHandler::READ | EventHandler::WRITE);
848 // The timeout (if set) keeps running here
851 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
852 } else if (error == SSL_ERROR_WANT_RSA_ASYNC_PENDING) {
853 // Our custom openssl function has kicked off an async request to do
854 // modular exponentiation. When that call returns, a callback will
855 // be invoked that will re-call handleAccept.
856 sslState_ = STATE_RSA_ASYNC_PENDING;
858 // Unregister for all events while blocked here
859 updateEventRegistration(
861 EventHandler::READ | EventHandler::WRITE
864 // The timeout (if set) keeps running here
868 // SSL_ERROR_ZERO_RETURN is processed here so we can get some detail
870 long lastError = ERR_get_error();
871 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
872 << "state=" << state_ << ", "
873 << "sslState=" << sslState_ << ", "
874 << "events=" << std::hex << eventFlags_ << "): "
875 << "SSL error: " << error << ", "
876 << "errno: " << errno << ", "
877 << "ret: " << ret << ", "
878 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
879 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
880 << "func: " << ERR_func_error_string(lastError) << ", "
881 << "reason: " << ERR_reason_error_string(lastError);
882 if (error != SSL_ERROR_SYSCALL) {
883 if (error == SSL_ERROR_SSL) {
884 *errorOut = lastError;
886 if ((unsigned long)lastError < 0x8000) {
897 void AsyncSSLSocket::checkForImmediateRead() noexcept {
898 // openssl may have buffered data that it read from the socket already.
899 // In this case we have to process it immediately, rather than waiting for
900 // the socket to become readable again.
901 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
902 AsyncSocket::handleRead();
907 AsyncSSLSocket::restartSSLAccept()
909 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this << ", fd=" << fd_
910 << ", state=" << int(state_) << ", "
911 << "sslState=" << sslState_ << ", events=" << eventFlags_;
912 DestructorGuard dg(this);
914 sslState_ == STATE_CACHE_LOOKUP ||
915 sslState_ == STATE_RSA_ASYNC_PENDING ||
916 sslState_ == STATE_ERROR ||
917 sslState_ == STATE_CLOSED
919 if (sslState_ == STATE_CLOSED) {
920 // I sure hope whoever closed this socket didn't delete it already,
921 // but this is not strictly speaking an error
924 if (sslState_ == STATE_ERROR) {
925 // go straight to fail if timeout expired during lookup
926 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
927 "SSL accept timed out");
928 failHandshake(__func__, ex);
931 sslState_ = STATE_ACCEPTING;
932 this->handleAccept();
936 AsyncSSLSocket::handleAccept() noexcept {
937 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
938 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
939 << "sslState=" << sslState_ << ", events=" << eventFlags_;
941 assert(state_ == StateEnum::ESTABLISHED &&
942 sslState_ == STATE_ACCEPTING);
944 /* lazily create the SSL structure */
946 ssl_ = ctx_->createSSL();
947 } catch (std::exception &e) {
948 sslState_ = STATE_ERROR;
949 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
950 "error calling SSLContext::createSSL()");
951 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
952 << ", fd=" << fd_ << "): " << e.what();
953 return failHandshake(__func__, ex);
955 SSL_set_fd(ssl_, fd_);
956 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
958 applyVerificationOptions(ssl_);
961 if (server_ && parseClientHello_) {
962 SSL_set_msg_callback_arg(ssl_, this);
963 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
967 int ret = SSL_accept(ssl_);
970 if (willBlock(ret, &error)) {
973 sslState_ = STATE_ERROR;
974 SSLException ex(error, errno);
975 return failHandshake(__func__, ex);
979 handshakeComplete_ = true;
980 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
982 // Move into STATE_ESTABLISHED in the normal case that we are in
984 sslState_ = STATE_ESTABLISHED;
986 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
987 << " successfully accepted; state=" << int(state_)
988 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
990 // Remember the EventBase we are attached to, before we start invoking any
991 // callbacks (since the callbacks may call detachEventBase()).
992 EventBase* originalEventBase = eventBase_;
994 // Call the accept callback.
997 // Note that the accept callback may have changed our state.
998 // (set or unset the read callback, called write(), closed the socket, etc.)
999 // The following code needs to handle these situations correctly.
1001 // If the socket has been closed, readCallback_ and writeReqHead_ will
1002 // always be nullptr, so that will prevent us from trying to read or write.
1004 // The main thing to check for is if eventBase_ is still originalEventBase.
1005 // If not, we have been detached from this event base, so we shouldn't
1006 // perform any more operations.
1007 if (eventBase_ != originalEventBase) {
1011 AsyncSocket::handleInitialReadWrite();
1015 AsyncSSLSocket::handleConnect() noexcept {
1016 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1017 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1018 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1020 if (state_ < StateEnum::ESTABLISHED) {
1021 return AsyncSocket::handleConnect();
1024 assert(state_ == StateEnum::ESTABLISHED &&
1025 sslState_ == STATE_CONNECTING);
1029 int ret = SSL_connect(ssl_);
1032 if (willBlock(ret, &error)) {
1035 sslState_ = STATE_ERROR;
1036 SSLException ex(error, errno);
1037 return failHandshake(__func__, ex);
1041 handshakeComplete_ = true;
1042 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1044 // Move into STATE_ESTABLISHED in the normal case that we are in
1045 // STATE_CONNECTING.
1046 sslState_ = STATE_ESTABLISHED;
1048 VLOG(3) << "AsyncSSLSocket %p: fd %d successfully connected; "
1049 << "state=" << int(state_) << ", sslState=" << sslState_
1050 << ", events=" << eventFlags_;
1052 // Remember the EventBase we are attached to, before we start invoking any
1053 // callbacks (since the callbacks may call detachEventBase()).
1054 EventBase* originalEventBase = eventBase_;
1056 // Call the handshake callback.
1057 invokeHandshakeCB();
1059 // Note that the connect callback may have changed our state.
1060 // (set or unset the read callback, called write(), closed the socket, etc.)
1061 // The following code needs to handle these situations correctly.
1063 // If the socket has been closed, readCallback_ and writeReqHead_ will
1064 // always be nullptr, so that will prevent us from trying to read or write.
1066 // The main thing to check for is if eventBase_ is still originalEventBase.
1067 // If not, we have been detached from this event base, so we shouldn't
1068 // perform any more operations.
1069 if (eventBase_ != originalEventBase) {
1073 AsyncSocket::handleInitialReadWrite();
1076 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1077 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1078 // turn on the buffer movable in openssl
1079 if (!isBufferMovable_ && callback != nullptr && callback->isBufferMovable()) {
1080 SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1081 isBufferMovable_ = true;
1085 AsyncSocket::setReadCB(callback);
1088 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) noexcept {
1089 CHECK(readCallback_);
1090 if (isBufferMovable_) {
1094 // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1095 readCallback_->getReadBuffer(buf, buflen);
1100 AsyncSSLSocket::handleRead() noexcept {
1101 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1102 << ", state=" << int(state_) << ", "
1103 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1104 if (state_ < StateEnum::ESTABLISHED) {
1105 return AsyncSocket::handleRead();
1109 if (sslState_ == STATE_ACCEPTING) {
1114 else if (sslState_ == STATE_CONNECTING) {
1121 AsyncSocket::handleRead();
1125 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1126 VLOG(4) << "AsyncSSLSocket::performRead() this=" << this
1127 << ", buf=" << *buf << ", buflen=" << *buflen;
1129 if (sslState_ == STATE_UNENCRYPTED) {
1130 return AsyncSocket::performRead(buf, buflen, offset);
1135 if (!isBufferMovable_) {
1136 bytes = SSL_read(ssl_, *buf, *buflen);
1138 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1140 bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1144 if (server_ && renegotiateAttempted_) {
1145 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1146 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1147 << "): client intitiated SSL renegotiation not permitted";
1148 // We pack our own SSLerr here with a dummy function
1149 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1150 SSL_CLIENT_RENEGOTIATION_ATTEMPT);
1155 int error = SSL_get_error(ssl_, bytes);
1156 if (error == SSL_ERROR_WANT_READ) {
1157 // The caller will register for read event if not already.
1158 return READ_BLOCKING;
1159 } else if (error == SSL_ERROR_WANT_WRITE) {
1160 // TODO: Even though we are attempting to read data, SSL_read() may
1161 // need to write data if renegotiation is being performed. We currently
1162 // don't support this and just fail the read.
1163 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1164 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1165 << "): unsupported SSL renegotiation during read",
1166 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1167 SSL_INVALID_RENEGOTIATION);
1171 // TODO: Fix this code so that it can return a proper error message
1172 // to the callback, rather than relying on AsyncSocket code which
1173 // can't handle SSL errors.
1174 long lastError = ERR_get_error();
1176 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1177 << "state=" << state_ << ", "
1178 << "sslState=" << sslState_ << ", "
1179 << "events=" << std::hex << eventFlags_ << "): "
1180 << "bytes: " << bytes << ", "
1181 << "error: " << error << ", "
1182 << "errno: " << errno << ", "
1183 << "func: " << ERR_func_error_string(lastError) << ", "
1184 << "reason: " << ERR_reason_error_string(lastError);
1186 if (zero_return(error, bytes)) {
1189 if (error != SSL_ERROR_SYSCALL) {
1190 if ((unsigned long)lastError < 0x8000) {
1199 appBytesReceived_ += bytes;
1204 void AsyncSSLSocket::handleWrite() noexcept {
1205 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1206 << ", state=" << int(state_) << ", "
1207 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1208 if (state_ < StateEnum::ESTABLISHED) {
1209 return AsyncSocket::handleWrite();
1212 if (sslState_ == STATE_ACCEPTING) {
1218 if (sslState_ == STATE_CONNECTING) {
1225 AsyncSocket::handleWrite();
1228 int AsyncSSLSocket::interpretSSLError(int rc, int error) {
1229 if (error == SSL_ERROR_WANT_READ) {
1230 // TODO: Even though we are attempting to write data, SSL_write() may
1231 // need to read data if renegotiation is being performed. We currently
1232 // don't support this and just fail the write.
1233 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1234 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1235 << "): " << "unsupported SSL renegotiation during write",
1236 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1237 SSL_INVALID_RENEGOTIATION);
1241 // TODO: Fix this code so that it can return a proper error message
1242 // to the callback, rather than relying on AsyncSocket code which
1243 // can't handle SSL errors.
1244 long lastError = ERR_get_error();
1245 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1246 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1247 << "SSL error: " << error << ", errno: " << errno
1248 << ", func: " << ERR_func_error_string(lastError)
1249 << ", reason: " << ERR_reason_error_string(lastError);
1250 if (error != SSL_ERROR_SYSCALL) {
1251 if ((unsigned long)lastError < 0x8000) {
1258 if (!zero_return(error, rc)) {
1266 ssize_t AsyncSSLSocket::performWrite(const iovec* vec,
1269 uint32_t* countWritten,
1270 uint32_t* partialWritten) {
1271 if (sslState_ == STATE_UNENCRYPTED) {
1272 return AsyncSocket::performWrite(
1273 vec, count, flags, countWritten, partialWritten);
1275 if (sslState_ != STATE_ESTABLISHED) {
1276 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1277 << ", sslState=" << sslState_
1278 << ", events=" << eventFlags_ << "): "
1279 << "TODO: AsyncSSLSocket currently does not support calling "
1280 << "write() before the handshake has fully completed";
1281 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1286 bool cork = isSet(flags, WriteFlags::CORK);
1287 CorkGuard guard(fd_, count > 1, cork, &corked_);
1290 //#ifdef SSL_MODE_WRITE_IOVEC
1291 if (ssl_->expand == nullptr &&
1292 ssl_->compress == nullptr &&
1293 (ssl_->mode & SSL_MODE_WRITE_IOVEC)) {
1294 return performWriteIovec(vec, count, flags, countWritten, partialWritten);
1298 // Declare a buffer used to hold small write requests. It could point to a
1299 // memory block either on stack or on heap. If it is on heap, we release it
1300 // manually when scope exits
1301 char* combinedBuf{nullptr};
1303 // Note, always keep this check consistent with what we do below
1304 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1305 delete[] combinedBuf;
1310 *partialWritten = 0;
1311 ssize_t totalWritten = 0;
1312 size_t bytesStolenFromNextBuffer = 0;
1313 for (uint32_t i = 0; i < count; i++) {
1314 const iovec* v = vec + i;
1315 size_t offset = bytesStolenFromNextBuffer;
1316 bytesStolenFromNextBuffer = 0;
1317 size_t len = v->iov_len - offset;
1323 buf = ((const char*)v->iov_base) + offset;
1327 uint32_t buffersStolen = 0;
1328 if ((len < minWriteSize_) && ((i + 1) < count)) {
1329 // Combine this buffer with part or all of the next buffers in
1330 // order to avoid really small-grained calls to SSL_write().
1331 // Each call to SSL_write() produces a separate record in
1332 // the egress SSL stream, and we've found that some low-end
1333 // mobile clients can't handle receiving an HTTP response
1334 // header and the first part of the response body in two
1335 // separate SSL records (even if those two records are in
1336 // the same TCP packet).
1338 if (combinedBuf == nullptr) {
1339 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1340 // Allocate the buffer on heap
1341 combinedBuf = new char[minWriteSize_];
1343 // Allocate the buffer on stack
1344 combinedBuf = (char*)alloca(minWriteSize_);
1347 assert(combinedBuf != nullptr);
1349 memcpy(combinedBuf, buf, len);
1351 // INVARIANT: i + buffersStolen == complete chunks serialized
1352 uint32_t nextIndex = i + buffersStolen + 1;
1353 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1354 minWriteSize_ - len);
1355 memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1356 bytesStolenFromNextBuffer);
1357 len += bytesStolenFromNextBuffer;
1358 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1359 // couldn't steal the whole buffer
1362 bytesStolenFromNextBuffer = 0;
1365 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1366 bytes = eorAwareSSLWrite(
1367 ssl_, combinedBuf, len,
1368 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1371 bytes = eorAwareSSLWrite(ssl_, buf, len,
1372 (isSet(flags, WriteFlags::EOR) && i + 1 == count));
1376 int error = SSL_get_error(ssl_, bytes);
1377 if (error == SSL_ERROR_WANT_WRITE) {
1378 // The caller will register for write event if not already.
1379 *partialWritten = offset;
1380 return totalWritten;
1382 int rc = interpretSSLError(bytes, error);
1385 } // else fall through to below to correctly record totalWritten
1388 totalWritten += bytes;
1390 if (bytes == (ssize_t)len) {
1391 // The full iovec is written.
1392 (*countWritten) += 1 + buffersStolen;
1396 bytes += offset; // adjust bytes to account for all of v
1397 while (bytes >= (ssize_t)v->iov_len) {
1398 // We combined this buf with part or all of the next one, and
1399 // we managed to write all of this buf but not all of the bytes
1400 // from the next one that we'd hoped to write.
1401 bytes -= v->iov_len;
1405 *partialWritten = bytes;
1406 return totalWritten;
1410 return totalWritten;
1414 //#ifdef SSL_MODE_WRITE_IOVEC
1415 ssize_t AsyncSSLSocket::performWriteIovec(const iovec* vec,
1418 uint32_t* countWritten,
1419 uint32_t* partialWritten) {
1421 for (uint32_t j = 0; j < count; j++) {
1422 tot += vec[j].iov_len;
1425 ssize_t totalWritten = SSL_write_iovec(ssl_, vec, count);
1428 *partialWritten = 0;
1429 if (totalWritten <= 0) {
1430 return interpretSSLError(totalWritten, SSL_get_error(ssl_, totalWritten));
1432 ssize_t bytes = totalWritten, i = 0;
1433 while (i < count && bytes >= (ssize_t)vec[i].iov_len) {
1434 // we managed to write all of this buf
1435 bytes -= vec[i].iov_len;
1439 *partialWritten = bytes;
1441 VLOG(4) << "SSL_write_iovec() writes " << tot
1442 << ", returns " << totalWritten << " bytes"
1443 << ", max_send_fragment=" << ssl_->max_send_fragment
1444 << ", count=" << count << ", countWritten=" << *countWritten;
1446 return totalWritten;
1451 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1453 if (eor && SSL_get_wbio(ssl)->method == &eorAwareBioMethod) {
1454 if (appEorByteNo_) {
1455 // cannot track for more than one app byte EOR
1456 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1458 appEorByteNo_ = appBytesWritten_ + n;
1461 // 1. It is fine to keep updating minEorRawByteNo_.
1462 // 2. It is _min_ in the sense that SSL record will add some overhead.
1463 minEorRawByteNo_ = getRawBytesWritten() + n;
1466 n = sslWriteImpl(ssl, buf, n);
1468 appBytesWritten_ += n;
1469 if (appEorByteNo_) {
1470 if (getRawBytesWritten() >= minEorRawByteNo_) {
1471 minEorRawByteNo_ = 0;
1473 if(appBytesWritten_ == appEorByteNo_) {
1476 CHECK(appBytesWritten_ < appEorByteNo_);
1484 AsyncSSLSocket::sslInfoCallback(const SSL *ssl, int where, int ret) {
1485 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1486 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1487 sslSocket->renegotiateAttempted_ = true;
1491 int AsyncSSLSocket::eorAwareBioWrite(BIO *b, const char *in, int inl) {
1496 AsyncSSLSocket *tsslSock;
1498 iov.iov_base = const_cast<char *>(in);
1500 memset(&msg, 0, sizeof(msg));
1505 reinterpret_cast<AsyncSSLSocket*>(BIO_get_app_data(b));
1507 tsslSock->minEorRawByteNo_ &&
1508 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1513 ret = sendmsg(b->num, &msg, flags);
1514 BIO_clear_retry_flags(b);
1516 if (BIO_sock_should_retry(ret))
1517 BIO_set_retry_write(b);
1522 int AsyncSSLSocket::sslVerifyCallback(int preverifyOk,
1523 X509_STORE_CTX* x509Ctx) {
1524 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1525 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1526 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1528 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1529 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1530 return (self->handshakeCallback_) ?
1531 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1535 void AsyncSSLSocket::enableClientHelloParsing() {
1536 parseClientHello_ = true;
1537 clientHelloInfo_.reset(new ClientHelloInfo());
1540 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1541 SSL_set_msg_callback(ssl, nullptr);
1542 SSL_set_msg_callback_arg(ssl, nullptr);
1543 clientHelloInfo_->clientHelloBuf_.clear();
1547 AsyncSSLSocket::clientHelloParsingCallback(int written, int version,
1548 int contentType, const void *buf, size_t len, SSL *ssl, void *arg)
1550 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1552 sock->resetClientHelloParsing(ssl);
1555 if (contentType != SSL3_RT_HANDSHAKE) {
1556 sock->resetClientHelloParsing(ssl);
1563 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1564 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1566 Cursor cursor(clientHelloBuf.front());
1567 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1568 sock->resetClientHelloParsing(ssl);
1572 if (cursor.totalLength() < 3) {
1573 clientHelloBuf.trimEnd(len);
1574 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1578 uint32_t messageLength = cursor.read<uint8_t>();
1579 messageLength <<= 8;
1580 messageLength |= cursor.read<uint8_t>();
1581 messageLength <<= 8;
1582 messageLength |= cursor.read<uint8_t>();
1583 if (cursor.totalLength() < messageLength) {
1584 clientHelloBuf.trimEnd(len);
1585 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1589 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1590 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1592 cursor.skip(4); // gmt_unix_time
1593 cursor.skip(28); // random_bytes
1595 cursor.skip(cursor.read<uint8_t>()); // session_id
1597 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1598 for (int i = 0; i < cipherSuitesLength; i += 2) {
1599 sock->clientHelloInfo_->
1600 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1603 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1604 for (int i = 0; i < compressionMethodsLength; ++i) {
1605 sock->clientHelloInfo_->
1606 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1609 if (cursor.totalLength() > 0) {
1610 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1611 while (extensionsLength) {
1612 TLSExtension extensionType = static_cast<TLSExtension>(
1613 cursor.readBE<uint16_t>());
1614 sock->clientHelloInfo_->
1615 clientHelloExtensions_.push_back(extensionType);
1616 extensionsLength -= 2;
1617 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1618 extensionsLength -= 2;
1620 if (extensionType == TLSExtension::SIGNATURE_ALGORITHMS) {
1622 extensionDataLength -= 2;
1623 while (extensionDataLength) {
1624 HashAlgorithm hashAlg = static_cast<HashAlgorithm>(
1625 cursor.readBE<uint8_t>());
1626 SignatureAlgorithm sigAlg = static_cast<SignatureAlgorithm>(
1627 cursor.readBE<uint8_t>());
1628 extensionDataLength -= 2;
1629 sock->clientHelloInfo_->
1630 clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1633 cursor.skip(extensionDataLength);
1634 extensionsLength -= extensionDataLength;
1638 } catch (std::out_of_range& e) {
1639 // we'll use what we found and cleanup below.
1640 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1641 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1644 sock->resetClientHelloParsing(ssl);