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 const BIO *wb = SSL_get_wbio(ssl_);
416 return wb && wb->method == &eorAwareBioMethod;
419 void AsyncSSLSocket::setEorTracking(bool track) {
420 BIO *wb = SSL_get_wbio(ssl_);
422 throw AsyncSocketException(AsyncSocketException::INVALID_STATE,
423 "setting EOR tracking without an initialized "
428 if (wb->method != &eorAwareBioMethod) {
429 // only do this if we didn't
430 wb->method = &eorAwareBioMethod;
431 BIO_set_app_data(wb, this);
433 minEorRawByteNo_ = 0;
435 } else if (wb->method == &eorAwareBioMethod) {
436 wb->method = BIO_s_socket();
437 BIO_set_app_data(wb, nullptr);
439 minEorRawByteNo_ = 0;
441 CHECK(wb->method == BIO_s_socket());
445 size_t AsyncSSLSocket::getRawBytesWritten() const {
447 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
451 return BIO_number_written(b);
454 size_t AsyncSSLSocket::getRawBytesReceived() const {
456 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
460 return BIO_number_read(b);
464 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
465 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
466 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
467 << "events=" << eventFlags_ << ", server=" << short(server_) << "): "
468 << "sslAccept/Connect() called in invalid "
469 << "state, handshake callback " << handshakeCallback_ << ", new callback "
471 assert(!handshakeTimeout_.isScheduled());
472 sslState_ = STATE_ERROR;
474 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
475 "sslAccept() called with socket in invalid state");
477 handshakeEndTime_ = std::chrono::steady_clock::now();
479 callback->handshakeErr(this, ex);
482 // Check the socket state not the ssl state here.
483 if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
484 failHandshake(__func__, ex);
488 void AsyncSSLSocket::sslAccept(HandshakeCB* callback, uint32_t timeout,
489 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
490 DestructorGuard dg(this);
491 assert(eventBase_->isInEventBaseThread());
492 verifyPeer_ = verifyPeer;
494 // Make sure we're in the uninitialized state
495 if (!server_ || (sslState_ != STATE_UNINIT &&
496 sslState_ != STATE_UNENCRYPTED) ||
497 handshakeCallback_ != nullptr) {
498 return invalidState(callback);
500 handshakeStartTime_ = std::chrono::steady_clock::now();
501 // Make end time at least >= start time.
502 handshakeEndTime_ = handshakeStartTime_;
504 sslState_ = STATE_ACCEPTING;
505 handshakeCallback_ = callback;
508 handshakeTimeout_.scheduleTimeout(timeout);
511 /* register for a read operation (waiting for CLIENT HELLO) */
512 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
515 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
516 void AsyncSSLSocket::attachSSLContext(
517 const std::shared_ptr<SSLContext>& ctx) {
519 // Check to ensure we are in client mode. Changing a server's ssl
520 // context doesn't make sense since clients of that server would likely
521 // become confused when the server's context changes.
525 DCHECK(ctx->getSSLCtx());
528 // In order to call attachSSLContext, detachSSLContext must have been
529 // previously called which sets the socket's context to the dummy
530 // context. Thus we must acquire this lock.
531 SpinLockGuard guard(dummyCtxLock);
532 SSL_set_SSL_CTX(ssl_, ctx->getSSLCtx());
535 void AsyncSSLSocket::detachSSLContext() {
538 // We aren't using the initial_ctx for now, and it can introduce race
539 // conditions in the destructor of the SSL object.
540 #ifndef OPENSSL_NO_TLSEXT
541 if (ssl_->initial_ctx) {
542 SSL_CTX_free(ssl_->initial_ctx);
543 ssl_->initial_ctx = nullptr;
546 SpinLockGuard guard(dummyCtxLock);
547 if (nullptr == dummyCtx) {
548 // We need to lazily initialize the dummy context so we don't
549 // accidentally override any programmatic settings to openssl
550 dummyCtx = new SSLContext;
552 // We must remove this socket's references to its context right now
553 // since this socket could get passed to any thread. If the context has
554 // had its locking disabled, just doing a set in attachSSLContext()
555 // would not be thread safe.
556 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
560 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
561 void AsyncSSLSocket::switchServerSSLContext(
562 const std::shared_ptr<SSLContext>& handshakeCtx) {
564 if (sslState_ != STATE_ACCEPTING) {
565 // We log it here and allow the switch.
566 // It should not affect our re-negotiation support (which
567 // is not supported now).
568 VLOG(6) << "fd=" << getFd()
569 << " renegotation detected when switching SSL_CTX";
572 setup_SSL_CTX(handshakeCtx->getSSLCtx());
573 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
574 AsyncSSLSocket::sslInfoCallback);
575 handshakeCtx_ = handshakeCtx;
576 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
579 bool AsyncSSLSocket::isServerNameMatch() const {
586 SSL_SESSION *ss = SSL_get_session(ssl_);
591 if(!ss->tlsext_hostname) {
594 return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
597 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
598 tlsextHostname_ = std::move(serverName);
603 void AsyncSSLSocket::timeoutExpired() noexcept {
604 if (state_ == StateEnum::ESTABLISHED &&
605 (sslState_ == STATE_CACHE_LOOKUP ||
606 sslState_ == STATE_RSA_ASYNC_PENDING)) {
607 sslState_ = STATE_ERROR;
608 // We are expecting a callback in restartSSLAccept. The cache lookup
609 // and rsa-call necessarily have pointers to this ssl socket, so delay
610 // the cleanup until he calls us back.
612 assert(state_ == StateEnum::ESTABLISHED &&
613 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
614 DestructorGuard dg(this);
615 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
616 (sslState_ == STATE_CONNECTING) ?
617 "SSL connect timed out" : "SSL accept timed out");
618 failHandshake(__func__, ex);
622 int AsyncSSLSocket::getSSLExDataIndex() {
623 static auto index = SSL_get_ex_new_index(
624 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
628 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
629 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
630 getSSLExDataIndex()));
633 void AsyncSSLSocket::failHandshake(const char* fn,
634 const AsyncSocketException& ex) {
636 if (handshakeTimeout_.isScheduled()) {
637 handshakeTimeout_.cancelTimeout();
639 invokeHandshakeErr(ex);
643 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
644 handshakeEndTime_ = std::chrono::steady_clock::now();
645 if (handshakeCallback_ != nullptr) {
646 HandshakeCB* callback = handshakeCallback_;
647 handshakeCallback_ = nullptr;
648 callback->handshakeErr(this, ex);
652 void AsyncSSLSocket::invokeHandshakeCB() {
653 handshakeEndTime_ = std::chrono::steady_clock::now();
654 if (handshakeTimeout_.isScheduled()) {
655 handshakeTimeout_.cancelTimeout();
657 if (handshakeCallback_) {
658 HandshakeCB* callback = handshakeCallback_;
659 handshakeCallback_ = nullptr;
660 callback->handshakeSuc(this);
664 void AsyncSSLSocket::connect(ConnectCallback* callback,
665 const folly::SocketAddress& address,
667 const OptionMap &options,
668 const folly::SocketAddress& bindAddr)
671 assert(state_ == StateEnum::UNINIT);
672 assert(sslState_ == STATE_UNINIT);
673 AsyncSSLSocketConnector *connector =
674 new AsyncSSLSocketConnector(this, callback, timeout);
675 AsyncSocket::connect(connector, address, timeout, options, bindAddr);
678 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
679 // apply the settings specified in verifyPeer_
680 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
681 if(ctx_->needsPeerVerification()) {
682 SSL_set_verify(ssl, ctx_->getVerificationMode(),
683 AsyncSSLSocket::sslVerifyCallback);
686 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
687 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
688 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
689 AsyncSSLSocket::sslVerifyCallback);
694 void AsyncSSLSocket::sslConn(HandshakeCB* callback, uint64_t timeout,
695 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
696 DestructorGuard dg(this);
697 assert(eventBase_->isInEventBaseThread());
699 verifyPeer_ = verifyPeer;
701 // Make sure we're in the uninitialized state
702 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
703 STATE_UNENCRYPTED) ||
704 handshakeCallback_ != nullptr) {
705 return invalidState(callback);
708 handshakeStartTime_ = std::chrono::steady_clock::now();
709 // Make end time at least >= start time.
710 handshakeEndTime_ = handshakeStartTime_;
712 sslState_ = STATE_CONNECTING;
713 handshakeCallback_ = callback;
716 ssl_ = ctx_->createSSL();
717 } catch (std::exception &e) {
718 sslState_ = STATE_ERROR;
719 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
720 "error calling SSLContext::createSSL()");
721 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
722 << fd_ << "): " << e.what();
723 return failHandshake(__func__, ex);
726 applyVerificationOptions(ssl_);
728 SSL_set_fd(ssl_, fd_);
729 if (sslSession_ != nullptr) {
730 SSL_set_session(ssl_, sslSession_);
731 SSL_SESSION_free(sslSession_);
732 sslSession_ = nullptr;
734 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
735 if (tlsextHostname_.size()) {
736 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
740 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
743 handshakeTimeout_.scheduleTimeout(timeout);
749 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
750 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
751 return SSL_get1_session(ssl_);
757 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
758 sslSession_ = session;
759 if (!takeOwnership && session != nullptr) {
760 // Increment the reference count
761 CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
765 void AsyncSSLSocket::getSelectedNextProtocol(const unsigned char** protoName,
766 unsigned* protoLen) const {
767 if (!getSelectedNextProtocolNoThrow(protoName, protoLen)) {
768 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
769 "NPN not supported");
773 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
774 const unsigned char** protoName,
775 unsigned* protoLen) const {
776 *protoName = nullptr;
778 #ifdef OPENSSL_NPN_NEGOTIATED
779 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
786 bool AsyncSSLSocket::getSSLSessionReused() const {
787 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
788 return SSL_session_reused(ssl_);
793 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
794 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
797 const char *AsyncSSLSocket::getSSLServerName() const {
798 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
799 return (ssl_ != nullptr) ? SSL_get_servername(ssl_, TLSEXT_NAMETYPE_host_name)
802 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
803 "SNI not supported");
807 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
809 return getSSLServerName();
810 } catch (AsyncSocketException& ex) {
815 int AsyncSSLSocket::getSSLVersion() const {
816 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
819 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
820 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
822 int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
823 return OBJ_nid2ln(nid);
828 int AsyncSSLSocket::getSSLCertSize() const {
830 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
832 EVP_PKEY *key = X509_get_pubkey(cert);
833 certSize = EVP_PKEY_bits(key);
839 bool AsyncSSLSocket::willBlock(int ret, int *errorOut) noexcept {
840 int error = *errorOut = SSL_get_error(ssl_, ret);
841 if (error == SSL_ERROR_WANT_READ) {
842 // Register for read event if not already.
843 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
845 } else if (error == SSL_ERROR_WANT_WRITE) {
846 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
847 << ", state=" << int(state_) << ", sslState="
848 << sslState_ << ", events=" << eventFlags_ << "): "
849 << "SSL_ERROR_WANT_WRITE";
850 // Register for write event if not already.
851 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
853 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
854 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
855 // We will block but we can't register our own socket. The callback that
856 // triggered this code will re-call handleAccept at the appropriate time.
858 // We can only get here if the linked libssl.so has support for this feature
859 // as well, otherwise SSL_get_error cannot return our error code.
860 sslState_ = STATE_CACHE_LOOKUP;
862 // Unregister for all events while blocked here
863 updateEventRegistration(EventHandler::NONE,
864 EventHandler::READ | EventHandler::WRITE);
866 // The timeout (if set) keeps running here
869 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
870 } else if (error == SSL_ERROR_WANT_RSA_ASYNC_PENDING) {
871 // Our custom openssl function has kicked off an async request to do
872 // modular exponentiation. When that call returns, a callback will
873 // be invoked that will re-call handleAccept.
874 sslState_ = STATE_RSA_ASYNC_PENDING;
876 // Unregister for all events while blocked here
877 updateEventRegistration(
879 EventHandler::READ | EventHandler::WRITE
882 // The timeout (if set) keeps running here
886 // SSL_ERROR_ZERO_RETURN is processed here so we can get some detail
888 long lastError = ERR_get_error();
889 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
890 << "state=" << state_ << ", "
891 << "sslState=" << sslState_ << ", "
892 << "events=" << std::hex << eventFlags_ << "): "
893 << "SSL error: " << error << ", "
894 << "errno: " << errno << ", "
895 << "ret: " << ret << ", "
896 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
897 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
898 << "func: " << ERR_func_error_string(lastError) << ", "
899 << "reason: " << ERR_reason_error_string(lastError);
900 if (error != SSL_ERROR_SYSCALL) {
901 if (error == SSL_ERROR_SSL) {
902 *errorOut = lastError;
904 if ((unsigned long)lastError < 0x8000) {
915 void AsyncSSLSocket::checkForImmediateRead() noexcept {
916 // openssl may have buffered data that it read from the socket already.
917 // In this case we have to process it immediately, rather than waiting for
918 // the socket to become readable again.
919 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
920 AsyncSocket::handleRead();
925 AsyncSSLSocket::restartSSLAccept()
927 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this << ", fd=" << fd_
928 << ", state=" << int(state_) << ", "
929 << "sslState=" << sslState_ << ", events=" << eventFlags_;
930 DestructorGuard dg(this);
932 sslState_ == STATE_CACHE_LOOKUP ||
933 sslState_ == STATE_RSA_ASYNC_PENDING ||
934 sslState_ == STATE_ERROR ||
935 sslState_ == STATE_CLOSED
937 if (sslState_ == STATE_CLOSED) {
938 // I sure hope whoever closed this socket didn't delete it already,
939 // but this is not strictly speaking an error
942 if (sslState_ == STATE_ERROR) {
943 // go straight to fail if timeout expired during lookup
944 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
945 "SSL accept timed out");
946 failHandshake(__func__, ex);
949 sslState_ = STATE_ACCEPTING;
950 this->handleAccept();
954 AsyncSSLSocket::handleAccept() noexcept {
955 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
956 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
957 << "sslState=" << sslState_ << ", events=" << eventFlags_;
959 assert(state_ == StateEnum::ESTABLISHED &&
960 sslState_ == STATE_ACCEPTING);
962 /* lazily create the SSL structure */
964 ssl_ = ctx_->createSSL();
965 } catch (std::exception &e) {
966 sslState_ = STATE_ERROR;
967 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
968 "error calling SSLContext::createSSL()");
969 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
970 << ", fd=" << fd_ << "): " << e.what();
971 return failHandshake(__func__, ex);
973 SSL_set_fd(ssl_, fd_);
974 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
976 applyVerificationOptions(ssl_);
979 if (server_ && parseClientHello_) {
980 SSL_set_msg_callback_arg(ssl_, this);
981 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
985 int ret = SSL_accept(ssl_);
988 if (willBlock(ret, &error)) {
991 sslState_ = STATE_ERROR;
992 SSLException ex(error, errno);
993 return failHandshake(__func__, ex);
997 handshakeComplete_ = true;
998 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1000 // Move into STATE_ESTABLISHED in the normal case that we are in
1002 sslState_ = STATE_ESTABLISHED;
1004 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1005 << " successfully accepted; state=" << int(state_)
1006 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1008 // Remember the EventBase we are attached to, before we start invoking any
1009 // callbacks (since the callbacks may call detachEventBase()).
1010 EventBase* originalEventBase = eventBase_;
1012 // Call the accept callback.
1013 invokeHandshakeCB();
1015 // Note that the accept callback may have changed our state.
1016 // (set or unset the read callback, called write(), closed the socket, etc.)
1017 // The following code needs to handle these situations correctly.
1019 // If the socket has been closed, readCallback_ and writeReqHead_ will
1020 // always be nullptr, so that will prevent us from trying to read or write.
1022 // The main thing to check for is if eventBase_ is still originalEventBase.
1023 // If not, we have been detached from this event base, so we shouldn't
1024 // perform any more operations.
1025 if (eventBase_ != originalEventBase) {
1029 AsyncSocket::handleInitialReadWrite();
1033 AsyncSSLSocket::handleConnect() noexcept {
1034 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1035 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1036 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1038 if (state_ < StateEnum::ESTABLISHED) {
1039 return AsyncSocket::handleConnect();
1042 assert(state_ == StateEnum::ESTABLISHED &&
1043 sslState_ == STATE_CONNECTING);
1047 int ret = SSL_connect(ssl_);
1050 if (willBlock(ret, &error)) {
1053 sslState_ = STATE_ERROR;
1054 SSLException ex(error, errno);
1055 return failHandshake(__func__, ex);
1059 handshakeComplete_ = true;
1060 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1062 // Move into STATE_ESTABLISHED in the normal case that we are in
1063 // STATE_CONNECTING.
1064 sslState_ = STATE_ESTABLISHED;
1066 VLOG(3) << "AsyncSSLSocket %p: fd %d successfully connected; "
1067 << "state=" << int(state_) << ", sslState=" << sslState_
1068 << ", events=" << eventFlags_;
1070 // Remember the EventBase we are attached to, before we start invoking any
1071 // callbacks (since the callbacks may call detachEventBase()).
1072 EventBase* originalEventBase = eventBase_;
1074 // Call the handshake callback.
1075 invokeHandshakeCB();
1077 // Note that the connect callback may have changed our state.
1078 // (set or unset the read callback, called write(), closed the socket, etc.)
1079 // The following code needs to handle these situations correctly.
1081 // If the socket has been closed, readCallback_ and writeReqHead_ will
1082 // always be nullptr, so that will prevent us from trying to read or write.
1084 // The main thing to check for is if eventBase_ is still originalEventBase.
1085 // If not, we have been detached from this event base, so we shouldn't
1086 // perform any more operations.
1087 if (eventBase_ != originalEventBase) {
1091 AsyncSocket::handleInitialReadWrite();
1094 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1095 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1096 // turn on the buffer movable in openssl
1097 if (!isBufferMovable_ && callback != nullptr && callback->isBufferMovable()) {
1098 SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1099 isBufferMovable_ = true;
1103 AsyncSocket::setReadCB(callback);
1106 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) noexcept {
1107 CHECK(readCallback_);
1108 if (isBufferMovable_) {
1112 // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1113 readCallback_->getReadBuffer(buf, buflen);
1118 AsyncSSLSocket::handleRead() noexcept {
1119 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1120 << ", state=" << int(state_) << ", "
1121 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1122 if (state_ < StateEnum::ESTABLISHED) {
1123 return AsyncSocket::handleRead();
1127 if (sslState_ == STATE_ACCEPTING) {
1132 else if (sslState_ == STATE_CONNECTING) {
1139 AsyncSocket::handleRead();
1143 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1144 VLOG(4) << "AsyncSSLSocket::performRead() this=" << this
1145 << ", buf=" << *buf << ", buflen=" << *buflen;
1147 if (sslState_ == STATE_UNENCRYPTED) {
1148 return AsyncSocket::performRead(buf, buflen, offset);
1153 if (!isBufferMovable_) {
1154 bytes = SSL_read(ssl_, *buf, *buflen);
1156 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1158 bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1162 if (server_ && renegotiateAttempted_) {
1163 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1164 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1165 << "): client intitiated SSL renegotiation not permitted";
1166 // We pack our own SSLerr here with a dummy function
1167 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1168 SSL_CLIENT_RENEGOTIATION_ATTEMPT);
1173 int error = SSL_get_error(ssl_, bytes);
1174 if (error == SSL_ERROR_WANT_READ) {
1175 // The caller will register for read event if not already.
1176 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1177 return READ_BLOCKING;
1181 } else if (error == SSL_ERROR_WANT_WRITE) {
1182 // TODO: Even though we are attempting to read data, SSL_read() may
1183 // need to write data if renegotiation is being performed. We currently
1184 // don't support this and just fail the read.
1185 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1186 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1187 << "): unsupported SSL renegotiation during read",
1188 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1189 SSL_INVALID_RENEGOTIATION);
1193 // TODO: Fix this code so that it can return a proper error message
1194 // to the callback, rather than relying on AsyncSocket code which
1195 // can't handle SSL errors.
1196 long lastError = ERR_get_error();
1198 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1199 << "state=" << state_ << ", "
1200 << "sslState=" << sslState_ << ", "
1201 << "events=" << std::hex << eventFlags_ << "): "
1202 << "bytes: " << bytes << ", "
1203 << "error: " << error << ", "
1204 << "errno: " << errno << ", "
1205 << "func: " << ERR_func_error_string(lastError) << ", "
1206 << "reason: " << ERR_reason_error_string(lastError);
1208 if (zero_return(error, bytes)) {
1211 if (error != SSL_ERROR_SYSCALL) {
1212 if ((unsigned long)lastError < 0x8000) {
1221 appBytesReceived_ += bytes;
1226 void AsyncSSLSocket::handleWrite() noexcept {
1227 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1228 << ", state=" << int(state_) << ", "
1229 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1230 if (state_ < StateEnum::ESTABLISHED) {
1231 return AsyncSocket::handleWrite();
1234 if (sslState_ == STATE_ACCEPTING) {
1240 if (sslState_ == STATE_CONNECTING) {
1247 AsyncSocket::handleWrite();
1250 int AsyncSSLSocket::interpretSSLError(int rc, int error) {
1251 if (error == SSL_ERROR_WANT_READ) {
1252 // TODO: Even though we are attempting to write data, SSL_write() may
1253 // need to read data if renegotiation is being performed. We currently
1254 // don't support this and just fail the write.
1255 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1256 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1257 << "): " << "unsupported SSL renegotiation during write",
1258 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1259 SSL_INVALID_RENEGOTIATION);
1263 // TODO: Fix this code so that it can return a proper error message
1264 // to the callback, rather than relying on AsyncSocket code which
1265 // can't handle SSL errors.
1266 long lastError = ERR_get_error();
1267 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1268 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1269 << "SSL error: " << error << ", errno: " << errno
1270 << ", func: " << ERR_func_error_string(lastError)
1271 << ", reason: " << ERR_reason_error_string(lastError);
1272 if (error != SSL_ERROR_SYSCALL) {
1273 if ((unsigned long)lastError < 0x8000) {
1280 if (!zero_return(error, rc)) {
1288 ssize_t AsyncSSLSocket::performWrite(const iovec* vec,
1291 uint32_t* countWritten,
1292 uint32_t* partialWritten) {
1293 if (sslState_ == STATE_UNENCRYPTED) {
1294 return AsyncSocket::performWrite(
1295 vec, count, flags, countWritten, partialWritten);
1297 if (sslState_ != STATE_ESTABLISHED) {
1298 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1299 << ", sslState=" << sslState_
1300 << ", events=" << eventFlags_ << "): "
1301 << "TODO: AsyncSSLSocket currently does not support calling "
1302 << "write() before the handshake has fully completed";
1303 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1308 bool cork = isSet(flags, WriteFlags::CORK);
1309 CorkGuard guard(fd_, count > 1, cork, &corked_);
1312 //#ifdef SSL_MODE_WRITE_IOVEC
1313 if (ssl_->expand == nullptr &&
1314 ssl_->compress == nullptr &&
1315 (ssl_->mode & SSL_MODE_WRITE_IOVEC)) {
1316 return performWriteIovec(vec, count, flags, countWritten, partialWritten);
1320 // Declare a buffer used to hold small write requests. It could point to a
1321 // memory block either on stack or on heap. If it is on heap, we release it
1322 // manually when scope exits
1323 char* combinedBuf{nullptr};
1325 // Note, always keep this check consistent with what we do below
1326 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1327 delete[] combinedBuf;
1332 *partialWritten = 0;
1333 ssize_t totalWritten = 0;
1334 size_t bytesStolenFromNextBuffer = 0;
1335 for (uint32_t i = 0; i < count; i++) {
1336 const iovec* v = vec + i;
1337 size_t offset = bytesStolenFromNextBuffer;
1338 bytesStolenFromNextBuffer = 0;
1339 size_t len = v->iov_len - offset;
1345 buf = ((const char*)v->iov_base) + offset;
1349 uint32_t buffersStolen = 0;
1350 if ((len < minWriteSize_) && ((i + 1) < count)) {
1351 // Combine this buffer with part or all of the next buffers in
1352 // order to avoid really small-grained calls to SSL_write().
1353 // Each call to SSL_write() produces a separate record in
1354 // the egress SSL stream, and we've found that some low-end
1355 // mobile clients can't handle receiving an HTTP response
1356 // header and the first part of the response body in two
1357 // separate SSL records (even if those two records are in
1358 // the same TCP packet).
1360 if (combinedBuf == nullptr) {
1361 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1362 // Allocate the buffer on heap
1363 combinedBuf = new char[minWriteSize_];
1365 // Allocate the buffer on stack
1366 combinedBuf = (char*)alloca(minWriteSize_);
1369 assert(combinedBuf != nullptr);
1371 memcpy(combinedBuf, buf, len);
1373 // INVARIANT: i + buffersStolen == complete chunks serialized
1374 uint32_t nextIndex = i + buffersStolen + 1;
1375 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1376 minWriteSize_ - len);
1377 memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1378 bytesStolenFromNextBuffer);
1379 len += bytesStolenFromNextBuffer;
1380 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1381 // couldn't steal the whole buffer
1384 bytesStolenFromNextBuffer = 0;
1387 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1388 bytes = eorAwareSSLWrite(
1389 ssl_, combinedBuf, len,
1390 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1393 bytes = eorAwareSSLWrite(ssl_, buf, len,
1394 (isSet(flags, WriteFlags::EOR) && i + 1 == count));
1398 int error = SSL_get_error(ssl_, bytes);
1399 if (error == SSL_ERROR_WANT_WRITE) {
1400 // The caller will register for write event if not already.
1401 *partialWritten = offset;
1402 return totalWritten;
1404 int rc = interpretSSLError(bytes, error);
1407 } // else fall through to below to correctly record totalWritten
1410 totalWritten += bytes;
1412 if (bytes == (ssize_t)len) {
1413 // The full iovec is written.
1414 (*countWritten) += 1 + buffersStolen;
1418 bytes += offset; // adjust bytes to account for all of v
1419 while (bytes >= (ssize_t)v->iov_len) {
1420 // We combined this buf with part or all of the next one, and
1421 // we managed to write all of this buf but not all of the bytes
1422 // from the next one that we'd hoped to write.
1423 bytes -= v->iov_len;
1427 *partialWritten = bytes;
1428 return totalWritten;
1432 return totalWritten;
1436 //#ifdef SSL_MODE_WRITE_IOVEC
1437 ssize_t AsyncSSLSocket::performWriteIovec(const iovec* vec,
1440 uint32_t* countWritten,
1441 uint32_t* partialWritten) {
1443 for (uint32_t j = 0; j < count; j++) {
1444 tot += vec[j].iov_len;
1447 ssize_t totalWritten = SSL_write_iovec(ssl_, vec, count);
1450 *partialWritten = 0;
1451 if (totalWritten <= 0) {
1452 return interpretSSLError(totalWritten, SSL_get_error(ssl_, totalWritten));
1454 ssize_t bytes = totalWritten, i = 0;
1455 while (i < count && bytes >= (ssize_t)vec[i].iov_len) {
1456 // we managed to write all of this buf
1457 bytes -= vec[i].iov_len;
1461 *partialWritten = bytes;
1463 VLOG(4) << "SSL_write_iovec() writes " << tot
1464 << ", returns " << totalWritten << " bytes"
1465 << ", max_send_fragment=" << ssl_->max_send_fragment
1466 << ", count=" << count << ", countWritten=" << *countWritten;
1468 return totalWritten;
1473 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1475 if (eor && SSL_get_wbio(ssl)->method == &eorAwareBioMethod) {
1476 if (appEorByteNo_) {
1477 // cannot track for more than one app byte EOR
1478 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1480 appEorByteNo_ = appBytesWritten_ + n;
1483 // 1. It is fine to keep updating minEorRawByteNo_.
1484 // 2. It is _min_ in the sense that SSL record will add some overhead.
1485 minEorRawByteNo_ = getRawBytesWritten() + n;
1488 n = sslWriteImpl(ssl, buf, n);
1490 appBytesWritten_ += n;
1491 if (appEorByteNo_) {
1492 if (getRawBytesWritten() >= minEorRawByteNo_) {
1493 minEorRawByteNo_ = 0;
1495 if(appBytesWritten_ == appEorByteNo_) {
1498 CHECK(appBytesWritten_ < appEorByteNo_);
1506 AsyncSSLSocket::sslInfoCallback(const SSL *ssl, int where, int ret) {
1507 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1508 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1509 sslSocket->renegotiateAttempted_ = true;
1513 int AsyncSSLSocket::eorAwareBioWrite(BIO *b, const char *in, int inl) {
1518 AsyncSSLSocket *tsslSock;
1520 iov.iov_base = const_cast<char *>(in);
1522 memset(&msg, 0, sizeof(msg));
1527 reinterpret_cast<AsyncSSLSocket*>(BIO_get_app_data(b));
1529 tsslSock->minEorRawByteNo_ &&
1530 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1535 ret = sendmsg(b->num, &msg, flags);
1536 BIO_clear_retry_flags(b);
1538 if (BIO_sock_should_retry(ret))
1539 BIO_set_retry_write(b);
1544 int AsyncSSLSocket::sslVerifyCallback(int preverifyOk,
1545 X509_STORE_CTX* x509Ctx) {
1546 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1547 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1548 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1550 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1551 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1552 return (self->handshakeCallback_) ?
1553 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1557 void AsyncSSLSocket::enableClientHelloParsing() {
1558 parseClientHello_ = true;
1559 clientHelloInfo_.reset(new ClientHelloInfo());
1562 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1563 SSL_set_msg_callback(ssl, nullptr);
1564 SSL_set_msg_callback_arg(ssl, nullptr);
1565 clientHelloInfo_->clientHelloBuf_.clear();
1569 AsyncSSLSocket::clientHelloParsingCallback(int written, int version,
1570 int contentType, const void *buf, size_t len, SSL *ssl, void *arg)
1572 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1574 sock->resetClientHelloParsing(ssl);
1577 if (contentType != SSL3_RT_HANDSHAKE) {
1578 sock->resetClientHelloParsing(ssl);
1585 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1586 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1588 Cursor cursor(clientHelloBuf.front());
1589 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1590 sock->resetClientHelloParsing(ssl);
1594 if (cursor.totalLength() < 3) {
1595 clientHelloBuf.trimEnd(len);
1596 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1600 uint32_t messageLength = cursor.read<uint8_t>();
1601 messageLength <<= 8;
1602 messageLength |= cursor.read<uint8_t>();
1603 messageLength <<= 8;
1604 messageLength |= cursor.read<uint8_t>();
1605 if (cursor.totalLength() < messageLength) {
1606 clientHelloBuf.trimEnd(len);
1607 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1611 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1612 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1614 cursor.skip(4); // gmt_unix_time
1615 cursor.skip(28); // random_bytes
1617 cursor.skip(cursor.read<uint8_t>()); // session_id
1619 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1620 for (int i = 0; i < cipherSuitesLength; i += 2) {
1621 sock->clientHelloInfo_->
1622 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1625 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1626 for (int i = 0; i < compressionMethodsLength; ++i) {
1627 sock->clientHelloInfo_->
1628 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1631 if (cursor.totalLength() > 0) {
1632 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1633 while (extensionsLength) {
1634 TLSExtension extensionType = static_cast<TLSExtension>(
1635 cursor.readBE<uint16_t>());
1636 sock->clientHelloInfo_->
1637 clientHelloExtensions_.push_back(extensionType);
1638 extensionsLength -= 2;
1639 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1640 extensionsLength -= 2;
1642 if (extensionType == TLSExtension::SIGNATURE_ALGORITHMS) {
1644 extensionDataLength -= 2;
1645 while (extensionDataLength) {
1646 HashAlgorithm hashAlg = static_cast<HashAlgorithm>(
1647 cursor.readBE<uint8_t>());
1648 SignatureAlgorithm sigAlg = static_cast<SignatureAlgorithm>(
1649 cursor.readBE<uint8_t>());
1650 extensionDataLength -= 2;
1651 sock->clientHelloInfo_->
1652 clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1655 cursor.skip(extensionDataLength);
1656 extensionsLength -= extensionDataLength;
1660 } catch (std::out_of_range& e) {
1661 // we'll use what we found and cleanup below.
1662 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1663 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1666 sock->resetClientHelloParsing(ssl);