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 std::string AsyncSSLSocket::getApplicationProtocol() noexcept {
406 const unsigned char* protoName = nullptr;
407 unsigned protoLength;
408 if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) {
409 return std::string(reinterpret_cast<const char*>(protoName), protoLength);
414 bool AsyncSSLSocket::isEorTrackingEnabled() const {
415 if (ssl_ == nullptr) {
418 const BIO *wb = SSL_get_wbio(ssl_);
419 return wb && wb->method == &eorAwareBioMethod;
422 void AsyncSSLSocket::setEorTracking(bool track) {
423 BIO *wb = SSL_get_wbio(ssl_);
425 throw AsyncSocketException(AsyncSocketException::INVALID_STATE,
426 "setting EOR tracking without an initialized "
431 if (wb->method != &eorAwareBioMethod) {
432 // only do this if we didn't
433 wb->method = &eorAwareBioMethod;
434 BIO_set_app_data(wb, this);
436 minEorRawByteNo_ = 0;
438 } else if (wb->method == &eorAwareBioMethod) {
439 wb->method = BIO_s_socket();
440 BIO_set_app_data(wb, nullptr);
442 minEorRawByteNo_ = 0;
444 CHECK(wb->method == BIO_s_socket());
448 size_t AsyncSSLSocket::getRawBytesWritten() const {
450 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
454 return BIO_number_written(b);
457 size_t AsyncSSLSocket::getRawBytesReceived() const {
459 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
463 return BIO_number_read(b);
467 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
468 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
469 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
470 << "events=" << eventFlags_ << ", server=" << short(server_) << "): "
471 << "sslAccept/Connect() called in invalid "
472 << "state, handshake callback " << handshakeCallback_ << ", new callback "
474 assert(!handshakeTimeout_.isScheduled());
475 sslState_ = STATE_ERROR;
477 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
478 "sslAccept() called with socket in invalid state");
480 handshakeEndTime_ = std::chrono::steady_clock::now();
482 callback->handshakeErr(this, ex);
485 // Check the socket state not the ssl state here.
486 if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
487 failHandshake(__func__, ex);
491 void AsyncSSLSocket::sslAccept(HandshakeCB* callback, uint32_t timeout,
492 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
493 DestructorGuard dg(this);
494 assert(eventBase_->isInEventBaseThread());
495 verifyPeer_ = verifyPeer;
497 // Make sure we're in the uninitialized state
498 if (!server_ || (sslState_ != STATE_UNINIT &&
499 sslState_ != STATE_UNENCRYPTED) ||
500 handshakeCallback_ != nullptr) {
501 return invalidState(callback);
503 handshakeStartTime_ = std::chrono::steady_clock::now();
504 // Make end time at least >= start time.
505 handshakeEndTime_ = handshakeStartTime_;
507 sslState_ = STATE_ACCEPTING;
508 handshakeCallback_ = callback;
511 handshakeTimeout_.scheduleTimeout(timeout);
514 /* register for a read operation (waiting for CLIENT HELLO) */
515 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
518 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
519 void AsyncSSLSocket::attachSSLContext(
520 const std::shared_ptr<SSLContext>& ctx) {
522 // Check to ensure we are in client mode. Changing a server's ssl
523 // context doesn't make sense since clients of that server would likely
524 // become confused when the server's context changes.
528 DCHECK(ctx->getSSLCtx());
531 // In order to call attachSSLContext, detachSSLContext must have been
532 // previously called which sets the socket's context to the dummy
533 // context. Thus we must acquire this lock.
534 SpinLockGuard guard(dummyCtxLock);
535 SSL_set_SSL_CTX(ssl_, ctx->getSSLCtx());
538 void AsyncSSLSocket::detachSSLContext() {
541 // We aren't using the initial_ctx for now, and it can introduce race
542 // conditions in the destructor of the SSL object.
543 #ifndef OPENSSL_NO_TLSEXT
544 if (ssl_->initial_ctx) {
545 SSL_CTX_free(ssl_->initial_ctx);
546 ssl_->initial_ctx = nullptr;
549 SpinLockGuard guard(dummyCtxLock);
550 if (nullptr == dummyCtx) {
551 // We need to lazily initialize the dummy context so we don't
552 // accidentally override any programmatic settings to openssl
553 dummyCtx = new SSLContext;
555 // We must remove this socket's references to its context right now
556 // since this socket could get passed to any thread. If the context has
557 // had its locking disabled, just doing a set in attachSSLContext()
558 // would not be thread safe.
559 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
563 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
564 void AsyncSSLSocket::switchServerSSLContext(
565 const std::shared_ptr<SSLContext>& handshakeCtx) {
567 if (sslState_ != STATE_ACCEPTING) {
568 // We log it here and allow the switch.
569 // It should not affect our re-negotiation support (which
570 // is not supported now).
571 VLOG(6) << "fd=" << getFd()
572 << " renegotation detected when switching SSL_CTX";
575 setup_SSL_CTX(handshakeCtx->getSSLCtx());
576 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
577 AsyncSSLSocket::sslInfoCallback);
578 handshakeCtx_ = handshakeCtx;
579 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
582 bool AsyncSSLSocket::isServerNameMatch() const {
589 SSL_SESSION *ss = SSL_get_session(ssl_);
594 if(!ss->tlsext_hostname) {
597 return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
600 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
601 tlsextHostname_ = std::move(serverName);
606 void AsyncSSLSocket::timeoutExpired() noexcept {
607 if (state_ == StateEnum::ESTABLISHED &&
608 (sslState_ == STATE_CACHE_LOOKUP ||
609 sslState_ == STATE_RSA_ASYNC_PENDING)) {
610 sslState_ = STATE_ERROR;
611 // We are expecting a callback in restartSSLAccept. The cache lookup
612 // and rsa-call necessarily have pointers to this ssl socket, so delay
613 // the cleanup until he calls us back.
615 assert(state_ == StateEnum::ESTABLISHED &&
616 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
617 DestructorGuard dg(this);
618 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
619 (sslState_ == STATE_CONNECTING) ?
620 "SSL connect timed out" : "SSL accept timed out");
621 failHandshake(__func__, ex);
625 int AsyncSSLSocket::getSSLExDataIndex() {
626 static auto index = SSL_get_ex_new_index(
627 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
631 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
632 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
633 getSSLExDataIndex()));
636 void AsyncSSLSocket::failHandshake(const char* fn,
637 const AsyncSocketException& ex) {
639 if (handshakeTimeout_.isScheduled()) {
640 handshakeTimeout_.cancelTimeout();
642 invokeHandshakeErr(ex);
646 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
647 handshakeEndTime_ = std::chrono::steady_clock::now();
648 if (handshakeCallback_ != nullptr) {
649 HandshakeCB* callback = handshakeCallback_;
650 handshakeCallback_ = nullptr;
651 callback->handshakeErr(this, ex);
655 void AsyncSSLSocket::invokeHandshakeCB() {
656 handshakeEndTime_ = std::chrono::steady_clock::now();
657 if (handshakeTimeout_.isScheduled()) {
658 handshakeTimeout_.cancelTimeout();
660 if (handshakeCallback_) {
661 HandshakeCB* callback = handshakeCallback_;
662 handshakeCallback_ = nullptr;
663 callback->handshakeSuc(this);
667 void AsyncSSLSocket::connect(ConnectCallback* callback,
668 const folly::SocketAddress& address,
670 const OptionMap &options,
671 const folly::SocketAddress& bindAddr)
674 assert(state_ == StateEnum::UNINIT);
675 assert(sslState_ == STATE_UNINIT);
676 AsyncSSLSocketConnector *connector =
677 new AsyncSSLSocketConnector(this, callback, timeout);
678 AsyncSocket::connect(connector, address, timeout, options, bindAddr);
681 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
682 // apply the settings specified in verifyPeer_
683 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
684 if(ctx_->needsPeerVerification()) {
685 SSL_set_verify(ssl, ctx_->getVerificationMode(),
686 AsyncSSLSocket::sslVerifyCallback);
689 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
690 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
691 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
692 AsyncSSLSocket::sslVerifyCallback);
697 void AsyncSSLSocket::sslConn(HandshakeCB* callback, uint64_t timeout,
698 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
699 DestructorGuard dg(this);
700 assert(eventBase_->isInEventBaseThread());
702 verifyPeer_ = verifyPeer;
704 // Make sure we're in the uninitialized state
705 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
706 STATE_UNENCRYPTED) ||
707 handshakeCallback_ != nullptr) {
708 return invalidState(callback);
711 handshakeStartTime_ = std::chrono::steady_clock::now();
712 // Make end time at least >= start time.
713 handshakeEndTime_ = handshakeStartTime_;
715 sslState_ = STATE_CONNECTING;
716 handshakeCallback_ = callback;
719 ssl_ = ctx_->createSSL();
720 } catch (std::exception &e) {
721 sslState_ = STATE_ERROR;
722 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
723 "error calling SSLContext::createSSL()");
724 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
725 << fd_ << "): " << e.what();
726 return failHandshake(__func__, ex);
729 applyVerificationOptions(ssl_);
731 SSL_set_fd(ssl_, fd_);
732 if (sslSession_ != nullptr) {
733 SSL_set_session(ssl_, sslSession_);
734 SSL_SESSION_free(sslSession_);
735 sslSession_ = nullptr;
737 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
738 if (tlsextHostname_.size()) {
739 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
743 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
746 handshakeTimeout_.scheduleTimeout(timeout);
752 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
753 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
754 return SSL_get1_session(ssl_);
760 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
761 sslSession_ = session;
762 if (!takeOwnership && session != nullptr) {
763 // Increment the reference count
764 CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
768 void AsyncSSLSocket::getSelectedNextProtocol(const unsigned char** protoName,
769 unsigned* protoLen) const {
770 if (!getSelectedNextProtocolNoThrow(protoName, protoLen)) {
771 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
772 "NPN not supported");
776 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
777 const unsigned char** protoName,
778 unsigned* protoLen) const {
779 *protoName = nullptr;
781 #ifdef OPENSSL_NPN_NEGOTIATED
782 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
789 bool AsyncSSLSocket::getSSLSessionReused() const {
790 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
791 return SSL_session_reused(ssl_);
796 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
797 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
800 const char *AsyncSSLSocket::getSSLServerName() const {
801 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
802 return (ssl_ != nullptr) ? SSL_get_servername(ssl_, TLSEXT_NAMETYPE_host_name)
805 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
806 "SNI not supported");
810 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
812 return getSSLServerName();
813 } catch (AsyncSocketException& ex) {
818 int AsyncSSLSocket::getSSLVersion() const {
819 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
822 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
823 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
825 int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
826 return OBJ_nid2ln(nid);
831 int AsyncSSLSocket::getSSLCertSize() const {
833 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
835 EVP_PKEY *key = X509_get_pubkey(cert);
836 certSize = EVP_PKEY_bits(key);
842 bool AsyncSSLSocket::willBlock(int ret, int *errorOut) noexcept {
843 int error = *errorOut = SSL_get_error(ssl_, ret);
844 if (error == SSL_ERROR_WANT_READ) {
845 // Register for read event if not already.
846 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
848 } else if (error == SSL_ERROR_WANT_WRITE) {
849 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
850 << ", state=" << int(state_) << ", sslState="
851 << sslState_ << ", events=" << eventFlags_ << "): "
852 << "SSL_ERROR_WANT_WRITE";
853 // Register for write event if not already.
854 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
856 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
857 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
858 // We will block but we can't register our own socket. The callback that
859 // triggered this code will re-call handleAccept at the appropriate time.
861 // We can only get here if the linked libssl.so has support for this feature
862 // as well, otherwise SSL_get_error cannot return our error code.
863 sslState_ = STATE_CACHE_LOOKUP;
865 // Unregister for all events while blocked here
866 updateEventRegistration(EventHandler::NONE,
867 EventHandler::READ | EventHandler::WRITE);
869 // The timeout (if set) keeps running here
872 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
873 } else if (error == SSL_ERROR_WANT_RSA_ASYNC_PENDING) {
874 // Our custom openssl function has kicked off an async request to do
875 // modular exponentiation. When that call returns, a callback will
876 // be invoked that will re-call handleAccept.
877 sslState_ = STATE_RSA_ASYNC_PENDING;
879 // Unregister for all events while blocked here
880 updateEventRegistration(
882 EventHandler::READ | EventHandler::WRITE
885 // The timeout (if set) keeps running here
889 // SSL_ERROR_ZERO_RETURN is processed here so we can get some detail
891 long lastError = ERR_get_error();
892 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
893 << "state=" << state_ << ", "
894 << "sslState=" << sslState_ << ", "
895 << "events=" << std::hex << eventFlags_ << "): "
896 << "SSL error: " << error << ", "
897 << "errno: " << errno << ", "
898 << "ret: " << ret << ", "
899 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
900 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
901 << "func: " << ERR_func_error_string(lastError) << ", "
902 << "reason: " << ERR_reason_error_string(lastError);
903 if (error != SSL_ERROR_SYSCALL) {
904 if (error == SSL_ERROR_SSL) {
905 *errorOut = lastError;
907 if ((unsigned long)lastError < 0x8000) {
918 void AsyncSSLSocket::checkForImmediateRead() noexcept {
919 // openssl may have buffered data that it read from the socket already.
920 // In this case we have to process it immediately, rather than waiting for
921 // the socket to become readable again.
922 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
923 AsyncSocket::handleRead();
928 AsyncSSLSocket::restartSSLAccept()
930 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this << ", fd=" << fd_
931 << ", state=" << int(state_) << ", "
932 << "sslState=" << sslState_ << ", events=" << eventFlags_;
933 DestructorGuard dg(this);
935 sslState_ == STATE_CACHE_LOOKUP ||
936 sslState_ == STATE_RSA_ASYNC_PENDING ||
937 sslState_ == STATE_ERROR ||
938 sslState_ == STATE_CLOSED
940 if (sslState_ == STATE_CLOSED) {
941 // I sure hope whoever closed this socket didn't delete it already,
942 // but this is not strictly speaking an error
945 if (sslState_ == STATE_ERROR) {
946 // go straight to fail if timeout expired during lookup
947 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
948 "SSL accept timed out");
949 failHandshake(__func__, ex);
952 sslState_ = STATE_ACCEPTING;
953 this->handleAccept();
957 AsyncSSLSocket::handleAccept() noexcept {
958 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
959 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
960 << "sslState=" << sslState_ << ", events=" << eventFlags_;
962 assert(state_ == StateEnum::ESTABLISHED &&
963 sslState_ == STATE_ACCEPTING);
965 /* lazily create the SSL structure */
967 ssl_ = ctx_->createSSL();
968 } catch (std::exception &e) {
969 sslState_ = STATE_ERROR;
970 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
971 "error calling SSLContext::createSSL()");
972 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
973 << ", fd=" << fd_ << "): " << e.what();
974 return failHandshake(__func__, ex);
976 SSL_set_fd(ssl_, fd_);
977 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
979 applyVerificationOptions(ssl_);
982 if (server_ && parseClientHello_) {
983 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
984 SSL_set_msg_callback_arg(ssl_, this);
988 int ret = SSL_accept(ssl_);
991 if (willBlock(ret, &error)) {
994 sslState_ = STATE_ERROR;
995 SSLException ex(error, errno);
996 return failHandshake(__func__, ex);
1000 handshakeComplete_ = true;
1001 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1003 // Move into STATE_ESTABLISHED in the normal case that we are in
1005 sslState_ = STATE_ESTABLISHED;
1007 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1008 << " successfully accepted; state=" << int(state_)
1009 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1011 // Remember the EventBase we are attached to, before we start invoking any
1012 // callbacks (since the callbacks may call detachEventBase()).
1013 EventBase* originalEventBase = eventBase_;
1015 // Call the accept callback.
1016 invokeHandshakeCB();
1018 // Note that the accept callback may have changed our state.
1019 // (set or unset the read callback, called write(), closed the socket, etc.)
1020 // The following code needs to handle these situations correctly.
1022 // If the socket has been closed, readCallback_ and writeReqHead_ will
1023 // always be nullptr, so that will prevent us from trying to read or write.
1025 // The main thing to check for is if eventBase_ is still originalEventBase.
1026 // If not, we have been detached from this event base, so we shouldn't
1027 // perform any more operations.
1028 if (eventBase_ != originalEventBase) {
1032 AsyncSocket::handleInitialReadWrite();
1036 AsyncSSLSocket::handleConnect() noexcept {
1037 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1038 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1039 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1041 if (state_ < StateEnum::ESTABLISHED) {
1042 return AsyncSocket::handleConnect();
1045 assert(state_ == StateEnum::ESTABLISHED &&
1046 sslState_ == STATE_CONNECTING);
1050 int ret = SSL_connect(ssl_);
1053 if (willBlock(ret, &error)) {
1056 sslState_ = STATE_ERROR;
1057 SSLException ex(error, errno);
1058 return failHandshake(__func__, ex);
1062 handshakeComplete_ = true;
1063 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1065 // Move into STATE_ESTABLISHED in the normal case that we are in
1066 // STATE_CONNECTING.
1067 sslState_ = STATE_ESTABLISHED;
1069 VLOG(3) << "AsyncSSLSocket %p: fd %d successfully connected; "
1070 << "state=" << int(state_) << ", sslState=" << sslState_
1071 << ", events=" << eventFlags_;
1073 // Remember the EventBase we are attached to, before we start invoking any
1074 // callbacks (since the callbacks may call detachEventBase()).
1075 EventBase* originalEventBase = eventBase_;
1077 // Call the handshake callback.
1078 invokeHandshakeCB();
1080 // Note that the connect callback may have changed our state.
1081 // (set or unset the read callback, called write(), closed the socket, etc.)
1082 // The following code needs to handle these situations correctly.
1084 // If the socket has been closed, readCallback_ and writeReqHead_ will
1085 // always be nullptr, so that will prevent us from trying to read or write.
1087 // The main thing to check for is if eventBase_ is still originalEventBase.
1088 // If not, we have been detached from this event base, so we shouldn't
1089 // perform any more operations.
1090 if (eventBase_ != originalEventBase) {
1094 AsyncSocket::handleInitialReadWrite();
1097 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1098 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1099 // turn on the buffer movable in openssl
1100 if (ssl_ != nullptr && !isBufferMovable_ &&
1101 callback != nullptr && callback->isBufferMovable()) {
1102 SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1103 isBufferMovable_ = true;
1107 AsyncSocket::setReadCB(callback);
1110 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) noexcept {
1111 CHECK(readCallback_);
1112 if (isBufferMovable_) {
1116 // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1117 readCallback_->getReadBuffer(buf, buflen);
1122 AsyncSSLSocket::handleRead() noexcept {
1123 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1124 << ", state=" << int(state_) << ", "
1125 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1126 if (state_ < StateEnum::ESTABLISHED) {
1127 return AsyncSocket::handleRead();
1131 if (sslState_ == STATE_ACCEPTING) {
1136 else if (sslState_ == STATE_CONNECTING) {
1143 AsyncSocket::handleRead();
1147 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1148 VLOG(4) << "AsyncSSLSocket::performRead() this=" << this
1149 << ", buf=" << *buf << ", buflen=" << *buflen;
1151 if (sslState_ == STATE_UNENCRYPTED) {
1152 return AsyncSocket::performRead(buf, buflen, offset);
1157 if (!isBufferMovable_) {
1158 bytes = SSL_read(ssl_, *buf, *buflen);
1160 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1162 bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1166 if (server_ && renegotiateAttempted_) {
1167 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1168 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1169 << "): client intitiated SSL renegotiation not permitted";
1170 // We pack our own SSLerr here with a dummy function
1171 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1172 SSL_CLIENT_RENEGOTIATION_ATTEMPT);
1177 int error = SSL_get_error(ssl_, bytes);
1178 if (error == SSL_ERROR_WANT_READ) {
1179 // The caller will register for read event if not already.
1180 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1181 return READ_BLOCKING;
1185 } else if (error == SSL_ERROR_WANT_WRITE) {
1186 // TODO: Even though we are attempting to read data, SSL_read() may
1187 // need to write data if renegotiation is being performed. We currently
1188 // don't support this and just fail the read.
1189 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1190 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1191 << "): unsupported SSL renegotiation during read",
1192 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1193 SSL_INVALID_RENEGOTIATION);
1197 // TODO: Fix this code so that it can return a proper error message
1198 // to the callback, rather than relying on AsyncSocket code which
1199 // can't handle SSL errors.
1200 long lastError = ERR_get_error();
1202 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1203 << "state=" << state_ << ", "
1204 << "sslState=" << sslState_ << ", "
1205 << "events=" << std::hex << eventFlags_ << "): "
1206 << "bytes: " << bytes << ", "
1207 << "error: " << error << ", "
1208 << "errno: " << errno << ", "
1209 << "func: " << ERR_func_error_string(lastError) << ", "
1210 << "reason: " << ERR_reason_error_string(lastError);
1212 if (zero_return(error, bytes)) {
1215 if (error != SSL_ERROR_SYSCALL) {
1216 if ((unsigned long)lastError < 0x8000) {
1225 appBytesReceived_ += bytes;
1230 void AsyncSSLSocket::handleWrite() noexcept {
1231 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1232 << ", state=" << int(state_) << ", "
1233 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1234 if (state_ < StateEnum::ESTABLISHED) {
1235 return AsyncSocket::handleWrite();
1238 if (sslState_ == STATE_ACCEPTING) {
1244 if (sslState_ == STATE_CONNECTING) {
1251 AsyncSocket::handleWrite();
1254 int AsyncSSLSocket::interpretSSLError(int rc, int error) {
1255 if (error == SSL_ERROR_WANT_READ) {
1256 // TODO: Even though we are attempting to write data, SSL_write() may
1257 // need to read data if renegotiation is being performed. We currently
1258 // don't support this and just fail the write.
1259 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1260 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1261 << "): " << "unsupported SSL renegotiation during write",
1262 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1263 SSL_INVALID_RENEGOTIATION);
1267 // TODO: Fix this code so that it can return a proper error message
1268 // to the callback, rather than relying on AsyncSocket code which
1269 // can't handle SSL errors.
1270 long lastError = ERR_get_error();
1271 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1272 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1273 << "SSL error: " << error << ", errno: " << errno
1274 << ", func: " << ERR_func_error_string(lastError)
1275 << ", reason: " << ERR_reason_error_string(lastError);
1276 if (error != SSL_ERROR_SYSCALL) {
1277 if ((unsigned long)lastError < 0x8000) {
1284 if (!zero_return(error, rc)) {
1292 ssize_t AsyncSSLSocket::performWrite(const iovec* vec,
1295 uint32_t* countWritten,
1296 uint32_t* partialWritten) {
1297 if (sslState_ == STATE_UNENCRYPTED) {
1298 return AsyncSocket::performWrite(
1299 vec, count, flags, countWritten, partialWritten);
1301 if (sslState_ != STATE_ESTABLISHED) {
1302 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1303 << ", sslState=" << sslState_
1304 << ", events=" << eventFlags_ << "): "
1305 << "TODO: AsyncSSLSocket currently does not support calling "
1306 << "write() before the handshake has fully completed";
1307 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1312 bool cork = isSet(flags, WriteFlags::CORK) || persistentCork_;
1313 CorkGuard guard(fd_, count > 1, cork, &corked_);
1316 //#ifdef SSL_MODE_WRITE_IOVEC
1317 if (ssl_->expand == nullptr &&
1318 ssl_->compress == nullptr &&
1319 (ssl_->mode & SSL_MODE_WRITE_IOVEC)) {
1320 return performWriteIovec(vec, count, flags, countWritten, partialWritten);
1324 // Declare a buffer used to hold small write requests. It could point to a
1325 // memory block either on stack or on heap. If it is on heap, we release it
1326 // manually when scope exits
1327 char* combinedBuf{nullptr};
1329 // Note, always keep this check consistent with what we do below
1330 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1331 delete[] combinedBuf;
1336 *partialWritten = 0;
1337 ssize_t totalWritten = 0;
1338 size_t bytesStolenFromNextBuffer = 0;
1339 for (uint32_t i = 0; i < count; i++) {
1340 const iovec* v = vec + i;
1341 size_t offset = bytesStolenFromNextBuffer;
1342 bytesStolenFromNextBuffer = 0;
1343 size_t len = v->iov_len - offset;
1349 buf = ((const char*)v->iov_base) + offset;
1353 uint32_t buffersStolen = 0;
1354 if ((len < minWriteSize_) && ((i + 1) < count)) {
1355 // Combine this buffer with part or all of the next buffers in
1356 // order to avoid really small-grained calls to SSL_write().
1357 // Each call to SSL_write() produces a separate record in
1358 // the egress SSL stream, and we've found that some low-end
1359 // mobile clients can't handle receiving an HTTP response
1360 // header and the first part of the response body in two
1361 // separate SSL records (even if those two records are in
1362 // the same TCP packet).
1364 if (combinedBuf == nullptr) {
1365 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1366 // Allocate the buffer on heap
1367 combinedBuf = new char[minWriteSize_];
1369 // Allocate the buffer on stack
1370 combinedBuf = (char*)alloca(minWriteSize_);
1373 assert(combinedBuf != nullptr);
1375 memcpy(combinedBuf, buf, len);
1377 // INVARIANT: i + buffersStolen == complete chunks serialized
1378 uint32_t nextIndex = i + buffersStolen + 1;
1379 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1380 minWriteSize_ - len);
1381 memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1382 bytesStolenFromNextBuffer);
1383 len += bytesStolenFromNextBuffer;
1384 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1385 // couldn't steal the whole buffer
1388 bytesStolenFromNextBuffer = 0;
1391 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1392 bytes = eorAwareSSLWrite(
1393 ssl_, combinedBuf, len,
1394 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1397 bytes = eorAwareSSLWrite(ssl_, buf, len,
1398 (isSet(flags, WriteFlags::EOR) && i + 1 == count));
1402 int error = SSL_get_error(ssl_, bytes);
1403 if (error == SSL_ERROR_WANT_WRITE) {
1404 // The caller will register for write event if not already.
1405 *partialWritten = offset;
1406 return totalWritten;
1408 int rc = interpretSSLError(bytes, error);
1411 } // else fall through to below to correctly record totalWritten
1414 totalWritten += bytes;
1416 if (bytes == (ssize_t)len) {
1417 // The full iovec is written.
1418 (*countWritten) += 1 + buffersStolen;
1422 bytes += offset; // adjust bytes to account for all of v
1423 while (bytes >= (ssize_t)v->iov_len) {
1424 // We combined this buf with part or all of the next one, and
1425 // we managed to write all of this buf but not all of the bytes
1426 // from the next one that we'd hoped to write.
1427 bytes -= v->iov_len;
1431 *partialWritten = bytes;
1432 return totalWritten;
1436 return totalWritten;
1440 //#ifdef SSL_MODE_WRITE_IOVEC
1441 ssize_t AsyncSSLSocket::performWriteIovec(const iovec* vec,
1444 uint32_t* countWritten,
1445 uint32_t* partialWritten) {
1447 for (uint32_t j = 0; j < count; j++) {
1448 tot += vec[j].iov_len;
1451 ssize_t totalWritten = SSL_write_iovec(ssl_, vec, count);
1454 *partialWritten = 0;
1455 if (totalWritten <= 0) {
1456 return interpretSSLError(totalWritten, SSL_get_error(ssl_, totalWritten));
1458 ssize_t bytes = totalWritten, i = 0;
1459 while (i < count && bytes >= (ssize_t)vec[i].iov_len) {
1460 // we managed to write all of this buf
1461 bytes -= vec[i].iov_len;
1465 *partialWritten = bytes;
1467 VLOG(4) << "SSL_write_iovec() writes " << tot
1468 << ", returns " << totalWritten << " bytes"
1469 << ", max_send_fragment=" << ssl_->max_send_fragment
1470 << ", count=" << count << ", countWritten=" << *countWritten;
1472 return totalWritten;
1477 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1479 if (eor && SSL_get_wbio(ssl)->method == &eorAwareBioMethod) {
1480 if (appEorByteNo_) {
1481 // cannot track for more than one app byte EOR
1482 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1484 appEorByteNo_ = appBytesWritten_ + n;
1487 // 1. It is fine to keep updating minEorRawByteNo_.
1488 // 2. It is _min_ in the sense that SSL record will add some overhead.
1489 minEorRawByteNo_ = getRawBytesWritten() + n;
1492 n = sslWriteImpl(ssl, buf, n);
1494 appBytesWritten_ += n;
1495 if (appEorByteNo_) {
1496 if (getRawBytesWritten() >= minEorRawByteNo_) {
1497 minEorRawByteNo_ = 0;
1499 if(appBytesWritten_ == appEorByteNo_) {
1502 CHECK(appBytesWritten_ < appEorByteNo_);
1510 AsyncSSLSocket::sslInfoCallback(const SSL *ssl, int where, int ret) {
1511 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1512 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1513 sslSocket->renegotiateAttempted_ = true;
1517 int AsyncSSLSocket::eorAwareBioWrite(BIO *b, const char *in, int inl) {
1522 AsyncSSLSocket *tsslSock;
1524 iov.iov_base = const_cast<char *>(in);
1526 memset(&msg, 0, sizeof(msg));
1531 reinterpret_cast<AsyncSSLSocket*>(BIO_get_app_data(b));
1533 tsslSock->minEorRawByteNo_ &&
1534 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1539 ret = sendmsg(b->num, &msg, flags);
1540 BIO_clear_retry_flags(b);
1542 if (BIO_sock_should_retry(ret))
1543 BIO_set_retry_write(b);
1548 int AsyncSSLSocket::sslVerifyCallback(int preverifyOk,
1549 X509_STORE_CTX* x509Ctx) {
1550 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1551 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1552 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1554 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1555 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1556 return (self->handshakeCallback_) ?
1557 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1561 void AsyncSSLSocket::enableClientHelloParsing() {
1562 parseClientHello_ = true;
1563 clientHelloInfo_.reset(new ClientHelloInfo());
1566 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1567 SSL_set_msg_callback(ssl, nullptr);
1568 SSL_set_msg_callback_arg(ssl, nullptr);
1569 clientHelloInfo_->clientHelloBuf_.clear();
1573 AsyncSSLSocket::clientHelloParsingCallback(int written, int version,
1574 int contentType, const void *buf, size_t len, SSL *ssl, void *arg)
1576 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1578 sock->resetClientHelloParsing(ssl);
1581 if (contentType != SSL3_RT_HANDSHAKE) {
1588 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1589 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1591 Cursor cursor(clientHelloBuf.front());
1592 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1593 sock->resetClientHelloParsing(ssl);
1597 if (cursor.totalLength() < 3) {
1598 clientHelloBuf.trimEnd(len);
1599 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1603 uint32_t messageLength = cursor.read<uint8_t>();
1604 messageLength <<= 8;
1605 messageLength |= cursor.read<uint8_t>();
1606 messageLength <<= 8;
1607 messageLength |= cursor.read<uint8_t>();
1608 if (cursor.totalLength() < messageLength) {
1609 clientHelloBuf.trimEnd(len);
1610 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1614 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1615 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1617 cursor.skip(4); // gmt_unix_time
1618 cursor.skip(28); // random_bytes
1620 cursor.skip(cursor.read<uint8_t>()); // session_id
1622 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1623 for (int i = 0; i < cipherSuitesLength; i += 2) {
1624 sock->clientHelloInfo_->
1625 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1628 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1629 for (int i = 0; i < compressionMethodsLength; ++i) {
1630 sock->clientHelloInfo_->
1631 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1634 if (cursor.totalLength() > 0) {
1635 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1636 while (extensionsLength) {
1637 TLSExtension extensionType = static_cast<TLSExtension>(
1638 cursor.readBE<uint16_t>());
1639 sock->clientHelloInfo_->
1640 clientHelloExtensions_.push_back(extensionType);
1641 extensionsLength -= 2;
1642 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1643 extensionsLength -= 2;
1645 if (extensionType == TLSExtension::SIGNATURE_ALGORITHMS) {
1647 extensionDataLength -= 2;
1648 while (extensionDataLength) {
1649 HashAlgorithm hashAlg = static_cast<HashAlgorithm>(
1650 cursor.readBE<uint8_t>());
1651 SignatureAlgorithm sigAlg = static_cast<SignatureAlgorithm>(
1652 cursor.readBE<uint8_t>());
1653 extensionDataLength -= 2;
1654 sock->clientHelloInfo_->
1655 clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1658 cursor.skip(extensionDataLength);
1659 extensionsLength -= extensionDataLength;
1663 } catch (std::out_of_range& e) {
1664 // we'll use what we found and cleanup below.
1665 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1666 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1669 sock->resetClientHelloParsing(ssl);