2 * Copyright 2016 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;
58 using folly::SSLContext;
60 // We have one single dummy SSL context so that we can implement attach
61 // and detach methods in a thread safe fashion without modifying opnessl.
62 static SSLContext *dummyCtx = nullptr;
63 static SpinLock dummyCtxLock;
65 // Numbers chosen as to not collide with functions in ssl.h
66 const uint8_t TASYNCSSLSOCKET_F_PERFORM_READ = 90;
67 const uint8_t TASYNCSSLSOCKET_F_PERFORM_WRITE = 91;
69 // If given min write size is less than this, buffer will be allocated on
70 // stack, otherwise it is allocated on heap
71 const size_t MAX_STACK_BUF_SIZE = 2048;
73 // This converts "illegal" shutdowns into ZERO_RETURN
74 inline bool zero_return(int error, int rc) {
75 return (error == SSL_ERROR_ZERO_RETURN || (rc == 0 && errno == 0));
78 class AsyncSSLSocketConnector: public AsyncSocket::ConnectCallback,
79 public AsyncSSLSocket::HandshakeCB {
82 AsyncSSLSocket *sslSocket_;
83 AsyncSSLSocket::ConnectCallback *callback_;
88 ~AsyncSSLSocketConnector() override {}
91 AsyncSSLSocketConnector(AsyncSSLSocket *sslSocket,
92 AsyncSocket::ConnectCallback *callback,
94 sslSocket_(sslSocket),
97 startTime_(std::chrono::duration_cast<std::chrono::milliseconds>(
98 std::chrono::steady_clock::now().time_since_epoch()).count()) {
101 void connectSuccess() noexcept override {
102 VLOG(7) << "client socket connected";
104 int64_t timeoutLeft = 0;
106 auto curTime = std::chrono::duration_cast<std::chrono::milliseconds>(
107 std::chrono::steady_clock::now().time_since_epoch()).count();
109 timeoutLeft = timeout_ - (curTime - startTime_);
110 if (timeoutLeft <= 0) {
111 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
112 "SSL connect timed out");
118 sslSocket_->sslConn(this, timeoutLeft);
121 void connectErr(const AsyncSocketException& ex) noexcept override {
122 LOG(ERROR) << "TCP connect failed: " << ex.what();
127 void handshakeSuc(AsyncSSLSocket* /* sock */) noexcept override {
128 VLOG(7) << "client handshake success";
130 callback_->connectSuccess();
135 void handshakeErr(AsyncSSLSocket* /* socket */,
136 const AsyncSocketException& ex) noexcept override {
137 LOG(ERROR) << "client handshakeErr: " << ex.what();
142 void fail(const AsyncSocketException &ex) {
143 // fail is a noop if called twice
145 AsyncSSLSocket::ConnectCallback *cb = callback_;
149 sslSocket_->closeNow();
150 // closeNow can call handshakeErr if it hasn't been called already.
151 // So this may have been deleted, no member variable access beyond this
153 // Note that closeNow may invoke writeError callbacks if the socket had
154 // write data pending connection completion.
159 // XXX: implement an equivalent to corking for platforms with TCP_NOPUSH?
160 #ifdef TCP_CORK // Linux-only
162 * Utility class that corks a TCP socket upon construction or uncorks
163 * the socket upon destruction
165 class CorkGuard : private boost::noncopyable {
167 CorkGuard(int fd, bool multipleWrites, bool haveMore, bool* corked):
168 fd_(fd), haveMore_(haveMore), corked_(corked) {
170 // socket is already corked; nothing to do
173 if (multipleWrites || haveMore) {
174 // We are performing multiple writes in this performWrite() call,
175 // and/or there are more calls to performWrite() that will be invoked
176 // later, so enable corking
178 setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
185 // more data to come; don't uncork yet
189 // socket isn't corked; nothing to do
194 setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
204 class CorkGuard : private boost::noncopyable {
206 CorkGuard(int, bool, bool, bool*) {}
210 void setup_SSL_CTX(SSL_CTX *ctx) {
211 #ifdef SSL_MODE_RELEASE_BUFFERS
212 SSL_CTX_set_mode(ctx,
213 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
214 SSL_MODE_ENABLE_PARTIAL_WRITE
215 | SSL_MODE_RELEASE_BUFFERS
218 SSL_CTX_set_mode(ctx,
219 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
220 SSL_MODE_ENABLE_PARTIAL_WRITE
223 // SSL_CTX_set_mode is a Macro
224 #ifdef SSL_MODE_WRITE_IOVEC
225 SSL_CTX_set_mode(ctx,
226 SSL_CTX_get_mode(ctx)
227 | SSL_MODE_WRITE_IOVEC);
232 BIO_METHOD eorAwareBioMethod;
234 void* initEorBioMethod(void) {
235 memcpy(&eorAwareBioMethod, BIO_s_socket(), sizeof(eorAwareBioMethod));
236 // override the bwrite method for MSG_EOR support
237 eorAwareBioMethod.bwrite = AsyncSSLSocket::eorAwareBioWrite;
239 // Note that the eorAwareBioMethod.type and eorAwareBioMethod.name are not
240 // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
241 // then have specific handlings. The eorAwareBioWrite should be compatible
242 // with the one in openssl.
244 // Return something here to enable AsyncSSLSocket to call this method using
245 // a function-scoped static.
249 std::string decodeOpenSSLError(int sslError,
250 unsigned long errError,
251 int sslOperationReturnValue) {
252 if (sslError == SSL_ERROR_SYSCALL && errError == 0) {
253 if (sslOperationReturnValue == 0) {
254 return "SSL_ERROR_SYSCALL: EOF";
256 // In this case errno is set, AsyncSocketException will add it.
257 return "SSL_ERROR_SYSCALL";
259 } else if (sslError == SSL_ERROR_ZERO_RETURN) {
260 // This signifies a TLS closure alert.
261 return "SSL_ERROR_ZERO_RETURN";
264 std::string msg(ERR_error_string(errError, buf));
269 } // anonymous namespace
273 SSLException::SSLException(int sslError,
274 unsigned long errError,
275 int sslOperationReturnValue,
277 : AsyncSocketException(
278 AsyncSocketException::SSL_ERROR,
279 decodeOpenSSLError(sslError, errError, sslOperationReturnValue),
280 sslError == SSL_ERROR_SYSCALL ? errno_copy : 0) {}
283 * Create a client AsyncSSLSocket
285 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
286 EventBase* evb, bool deferSecurityNegotiation) :
289 handshakeTimeout_(this, evb) {
291 if (deferSecurityNegotiation) {
292 sslState_ = STATE_UNENCRYPTED;
297 * Create a server/client AsyncSSLSocket
299 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
300 EventBase* evb, int fd, bool server,
301 bool deferSecurityNegotiation) :
302 AsyncSocket(evb, fd),
305 handshakeTimeout_(this, evb) {
308 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
309 AsyncSSLSocket::sslInfoCallback);
311 if (deferSecurityNegotiation) {
312 sslState_ = STATE_UNENCRYPTED;
316 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
318 * Create a client AsyncSSLSocket and allow tlsext_hostname
319 * to be sent in Client Hello.
321 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
323 const std::string& serverName,
324 bool deferSecurityNegotiation) :
325 AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
326 tlsextHostname_ = serverName;
330 * Create a client AsyncSSLSocket from an already connected fd
331 * and allow tlsext_hostname to be sent in Client Hello.
333 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
334 EventBase* evb, int fd,
335 const std::string& serverName,
336 bool deferSecurityNegotiation) :
337 AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
338 tlsextHostname_ = serverName;
342 AsyncSSLSocket::~AsyncSSLSocket() {
343 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
344 << ", evb=" << eventBase_ << ", fd=" << fd_
345 << ", state=" << int(state_) << ", sslState="
346 << sslState_ << ", events=" << eventFlags_ << ")";
349 void AsyncSSLSocket::init() {
350 // Do this here to ensure we initialize this once before any use of
351 // AsyncSSLSocket instances and not as part of library load.
352 static const auto eorAwareBioMethodInitializer = initEorBioMethod();
353 (void)eorAwareBioMethodInitializer;
355 setup_SSL_CTX(ctx_->getSSLCtx());
358 void AsyncSSLSocket::closeNow() {
359 // Close the SSL connection.
360 if (ssl_ != nullptr && fd_ != -1) {
361 int rc = SSL_shutdown(ssl_);
363 rc = SSL_shutdown(ssl_);
370 if (sslSession_ != nullptr) {
371 SSL_SESSION_free(sslSession_);
372 sslSession_ = nullptr;
375 sslState_ = STATE_CLOSED;
377 if (handshakeTimeout_.isScheduled()) {
378 handshakeTimeout_.cancelTimeout();
381 DestructorGuard dg(this);
384 AsyncSocketException(
385 AsyncSocketException::END_OF_FILE,
386 "SSL connection closed locally"));
388 if (ssl_ != nullptr) {
394 AsyncSocket::closeNow();
397 void AsyncSSLSocket::shutdownWrite() {
398 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
400 // (Performing a full shutdown here is more desirable than doing nothing at
401 // all. The purpose of shutdownWrite() is normally to notify the other end
402 // of the connection that no more data will be sent. If we do nothing, the
403 // other end will never know that no more data is coming, and this may result
404 // in protocol deadlock.)
408 void AsyncSSLSocket::shutdownWriteNow() {
412 bool AsyncSSLSocket::good() const {
413 return (AsyncSocket::good() &&
414 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
415 sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
418 // The TAsyncTransport definition of 'good' states that the transport is
419 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
420 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
421 // is connected but we haven't initiated the call to SSL_connect.
422 bool AsyncSSLSocket::connecting() const {
424 (AsyncSocket::connecting() ||
425 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
426 sslState_ == STATE_CONNECTING))));
429 std::string AsyncSSLSocket::getApplicationProtocol() noexcept {
430 const unsigned char* protoName = nullptr;
431 unsigned protoLength;
432 if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) {
433 return std::string(reinterpret_cast<const char*>(protoName), protoLength);
438 bool AsyncSSLSocket::isEorTrackingEnabled() const {
439 if (ssl_ == nullptr) {
442 const BIO *wb = SSL_get_wbio(ssl_);
443 return wb && wb->method == &eorAwareBioMethod;
446 void AsyncSSLSocket::setEorTracking(bool track) {
447 BIO *wb = SSL_get_wbio(ssl_);
449 throw AsyncSocketException(AsyncSocketException::INVALID_STATE,
450 "setting EOR tracking without an initialized "
455 if (wb->method != &eorAwareBioMethod) {
456 // only do this if we didn't
457 wb->method = &eorAwareBioMethod;
458 BIO_set_app_data(wb, this);
460 minEorRawByteNo_ = 0;
462 } else if (wb->method == &eorAwareBioMethod) {
463 wb->method = BIO_s_socket();
464 BIO_set_app_data(wb, nullptr);
466 minEorRawByteNo_ = 0;
468 CHECK(wb->method == BIO_s_socket());
472 size_t AsyncSSLSocket::getRawBytesWritten() const {
474 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
478 return BIO_number_written(b);
481 size_t AsyncSSLSocket::getRawBytesReceived() const {
483 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
487 return BIO_number_read(b);
491 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
492 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
493 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
494 << "events=" << eventFlags_ << ", server=" << short(server_) << "): "
495 << "sslAccept/Connect() called in invalid "
496 << "state, handshake callback " << handshakeCallback_ << ", new callback "
498 assert(!handshakeTimeout_.isScheduled());
499 sslState_ = STATE_ERROR;
501 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
502 "sslAccept() called with socket in invalid state");
504 handshakeEndTime_ = std::chrono::steady_clock::now();
506 callback->handshakeErr(this, ex);
509 // Check the socket state not the ssl state here.
510 if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
511 failHandshake(__func__, ex);
515 void AsyncSSLSocket::sslAccept(HandshakeCB* callback, uint32_t timeout,
516 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
517 DestructorGuard dg(this);
518 assert(eventBase_->isInEventBaseThread());
519 verifyPeer_ = verifyPeer;
521 // Make sure we're in the uninitialized state
522 if (!server_ || (sslState_ != STATE_UNINIT &&
523 sslState_ != STATE_UNENCRYPTED) ||
524 handshakeCallback_ != nullptr) {
525 return invalidState(callback);
528 // Cache local and remote socket addresses to keep them available
529 // after socket file descriptor is closed.
530 if (cacheAddrOnFailure_ && -1 != getFd()) {
531 cacheLocalPeerAddr();
534 handshakeStartTime_ = std::chrono::steady_clock::now();
535 // Make end time at least >= start time.
536 handshakeEndTime_ = handshakeStartTime_;
538 sslState_ = STATE_ACCEPTING;
539 handshakeCallback_ = callback;
542 handshakeTimeout_.scheduleTimeout(timeout);
545 /* register for a read operation (waiting for CLIENT HELLO) */
546 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
549 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
550 void AsyncSSLSocket::attachSSLContext(
551 const std::shared_ptr<SSLContext>& ctx) {
553 // Check to ensure we are in client mode. Changing a server's ssl
554 // context doesn't make sense since clients of that server would likely
555 // become confused when the server's context changes.
559 DCHECK(ctx->getSSLCtx());
562 // In order to call attachSSLContext, detachSSLContext must have been
563 // previously called which sets the socket's context to the dummy
564 // context. Thus we must acquire this lock.
565 SpinLockGuard guard(dummyCtxLock);
566 SSL_set_SSL_CTX(ssl_, ctx->getSSLCtx());
569 void AsyncSSLSocket::detachSSLContext() {
572 // We aren't using the initial_ctx for now, and it can introduce race
573 // conditions in the destructor of the SSL object.
574 #ifndef OPENSSL_NO_TLSEXT
575 if (ssl_->initial_ctx) {
576 SSL_CTX_free(ssl_->initial_ctx);
577 ssl_->initial_ctx = nullptr;
580 SpinLockGuard guard(dummyCtxLock);
581 if (nullptr == dummyCtx) {
582 // We need to lazily initialize the dummy context so we don't
583 // accidentally override any programmatic settings to openssl
584 dummyCtx = new SSLContext;
586 // We must remove this socket's references to its context right now
587 // since this socket could get passed to any thread. If the context has
588 // had its locking disabled, just doing a set in attachSSLContext()
589 // would not be thread safe.
590 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
594 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
595 void AsyncSSLSocket::switchServerSSLContext(
596 const std::shared_ptr<SSLContext>& handshakeCtx) {
598 if (sslState_ != STATE_ACCEPTING) {
599 // We log it here and allow the switch.
600 // It should not affect our re-negotiation support (which
601 // is not supported now).
602 VLOG(6) << "fd=" << getFd()
603 << " renegotation detected when switching SSL_CTX";
606 setup_SSL_CTX(handshakeCtx->getSSLCtx());
607 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
608 AsyncSSLSocket::sslInfoCallback);
609 handshakeCtx_ = handshakeCtx;
610 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
613 bool AsyncSSLSocket::isServerNameMatch() const {
620 SSL_SESSION *ss = SSL_get_session(ssl_);
625 if(!ss->tlsext_hostname) {
628 return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
631 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
632 tlsextHostname_ = std::move(serverName);
637 void AsyncSSLSocket::timeoutExpired() noexcept {
638 if (state_ == StateEnum::ESTABLISHED &&
639 (sslState_ == STATE_CACHE_LOOKUP ||
640 sslState_ == STATE_ASYNC_PENDING)) {
641 sslState_ = STATE_ERROR;
642 // We are expecting a callback in restartSSLAccept. The cache lookup
643 // and rsa-call necessarily have pointers to this ssl socket, so delay
644 // the cleanup until he calls us back.
646 assert(state_ == StateEnum::ESTABLISHED &&
647 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
648 DestructorGuard dg(this);
649 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
650 (sslState_ == STATE_CONNECTING) ?
651 "SSL connect timed out" : "SSL accept timed out");
652 failHandshake(__func__, ex);
656 int AsyncSSLSocket::getSSLExDataIndex() {
657 static auto index = SSL_get_ex_new_index(
658 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
662 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
663 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
664 getSSLExDataIndex()));
667 void AsyncSSLSocket::failHandshake(const char* /* fn */,
668 const AsyncSocketException& ex) {
670 if (handshakeTimeout_.isScheduled()) {
671 handshakeTimeout_.cancelTimeout();
673 invokeHandshakeErr(ex);
677 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
678 handshakeEndTime_ = std::chrono::steady_clock::now();
679 if (handshakeCallback_ != nullptr) {
680 HandshakeCB* callback = handshakeCallback_;
681 handshakeCallback_ = nullptr;
682 callback->handshakeErr(this, ex);
686 void AsyncSSLSocket::invokeHandshakeCB() {
687 handshakeEndTime_ = std::chrono::steady_clock::now();
688 if (handshakeTimeout_.isScheduled()) {
689 handshakeTimeout_.cancelTimeout();
691 if (handshakeCallback_) {
692 HandshakeCB* callback = handshakeCallback_;
693 handshakeCallback_ = nullptr;
694 callback->handshakeSuc(this);
698 void AsyncSSLSocket::cacheLocalPeerAddr() {
699 SocketAddress address;
701 getLocalAddress(&address);
702 getPeerAddress(&address);
703 } catch (const std::system_error& e) {
704 // The handle can be still valid while the connection is already closed.
705 if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
711 void AsyncSSLSocket::connect(ConnectCallback* callback,
712 const folly::SocketAddress& address,
714 const OptionMap &options,
715 const folly::SocketAddress& bindAddr)
718 assert(state_ == StateEnum::UNINIT);
719 assert(sslState_ == STATE_UNINIT);
720 AsyncSSLSocketConnector *connector =
721 new AsyncSSLSocketConnector(this, callback, timeout);
722 AsyncSocket::connect(connector, address, timeout, options, bindAddr);
725 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
726 // apply the settings specified in verifyPeer_
727 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
728 if(ctx_->needsPeerVerification()) {
729 SSL_set_verify(ssl, ctx_->getVerificationMode(),
730 AsyncSSLSocket::sslVerifyCallback);
733 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
734 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
735 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
736 AsyncSSLSocket::sslVerifyCallback);
741 void AsyncSSLSocket::sslConn(HandshakeCB* callback, uint64_t timeout,
742 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
743 DestructorGuard dg(this);
744 assert(eventBase_->isInEventBaseThread());
746 // Cache local and remote socket addresses to keep them available
747 // after socket file descriptor is closed.
748 if (cacheAddrOnFailure_ && -1 != getFd()) {
749 cacheLocalPeerAddr();
752 verifyPeer_ = verifyPeer;
754 // Make sure we're in the uninitialized state
755 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
756 STATE_UNENCRYPTED) ||
757 handshakeCallback_ != nullptr) {
758 return invalidState(callback);
761 handshakeStartTime_ = std::chrono::steady_clock::now();
762 // Make end time at least >= start time.
763 handshakeEndTime_ = handshakeStartTime_;
765 sslState_ = STATE_CONNECTING;
766 handshakeCallback_ = callback;
769 ssl_ = ctx_->createSSL();
770 } catch (std::exception &e) {
771 sslState_ = STATE_ERROR;
772 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
773 "error calling SSLContext::createSSL()");
774 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
775 << fd_ << "): " << e.what();
776 return failHandshake(__func__, ex);
779 applyVerificationOptions(ssl_);
781 SSL_set_fd(ssl_, fd_);
782 if (sslSession_ != nullptr) {
783 SSL_set_session(ssl_, sslSession_);
784 SSL_SESSION_free(sslSession_);
785 sslSession_ = nullptr;
787 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
788 if (tlsextHostname_.size()) {
789 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
793 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
796 handshakeTimeout_.scheduleTimeout(timeout);
802 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
803 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
804 return SSL_get1_session(ssl_);
810 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
811 sslSession_ = session;
812 if (!takeOwnership && session != nullptr) {
813 // Increment the reference count
814 CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
818 void AsyncSSLSocket::getSelectedNextProtocol(
819 const unsigned char** protoName,
821 SSLContext::NextProtocolType* protoType) const {
822 if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
823 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
824 "NPN not supported");
828 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
829 const unsigned char** protoName,
831 SSLContext::NextProtocolType* protoType) const {
832 *protoName = nullptr;
834 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
835 SSL_get0_alpn_selected(ssl_, protoName, protoLen);
838 *protoType = SSLContext::NextProtocolType::ALPN;
843 #ifdef OPENSSL_NPN_NEGOTIATED
844 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
846 *protoType = SSLContext::NextProtocolType::NPN;
855 bool AsyncSSLSocket::getSSLSessionReused() const {
856 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
857 return SSL_session_reused(ssl_);
862 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
863 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
867 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
868 if (ssl == nullptr) {
871 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
872 return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
878 const char *AsyncSSLSocket::getSSLServerName() const {
879 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
880 return getSSLServerNameFromSSL(ssl_);
882 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
883 "SNI not supported");
887 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
888 return getSSLServerNameFromSSL(ssl_);
891 int AsyncSSLSocket::getSSLVersion() const {
892 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
895 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
896 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
898 int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
899 return OBJ_nid2ln(nid);
904 int AsyncSSLSocket::getSSLCertSize() const {
906 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
908 EVP_PKEY *key = X509_get_pubkey(cert);
909 certSize = EVP_PKEY_bits(key);
915 bool AsyncSSLSocket::willBlock(int ret,
917 unsigned long* errErrorOut) noexcept {
919 int error = *sslErrorOut = SSL_get_error(ssl_, ret);
920 if (error == SSL_ERROR_WANT_READ) {
921 // Register for read event if not already.
922 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
924 } else if (error == SSL_ERROR_WANT_WRITE) {
925 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
926 << ", state=" << int(state_) << ", sslState="
927 << sslState_ << ", events=" << eventFlags_ << "): "
928 << "SSL_ERROR_WANT_WRITE";
929 // Register for write event if not already.
930 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
932 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
933 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
934 // We will block but we can't register our own socket. The callback that
935 // triggered this code will re-call handleAccept at the appropriate time.
937 // We can only get here if the linked libssl.so has support for this feature
938 // as well, otherwise SSL_get_error cannot return our error code.
939 sslState_ = STATE_CACHE_LOOKUP;
941 // Unregister for all events while blocked here
942 updateEventRegistration(EventHandler::NONE,
943 EventHandler::READ | EventHandler::WRITE);
945 // The timeout (if set) keeps running here
949 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
950 || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
952 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
953 || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
956 // Our custom openssl function has kicked off an async request to do
957 // rsa/ecdsa private key operation. When that call returns, a callback will
958 // be invoked that will re-call handleAccept.
959 sslState_ = STATE_ASYNC_PENDING;
961 // Unregister for all events while blocked here
962 updateEventRegistration(
964 EventHandler::READ | EventHandler::WRITE
967 // The timeout (if set) keeps running here
970 // SSL_ERROR_ZERO_RETURN is processed here so we can get some detail
972 unsigned long lastError = *errErrorOut = ERR_get_error();
973 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
974 << "state=" << state_ << ", "
975 << "sslState=" << sslState_ << ", "
976 << "events=" << std::hex << eventFlags_ << "): "
977 << "SSL error: " << error << ", "
978 << "errno: " << errno << ", "
979 << "ret: " << ret << ", "
980 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
981 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
982 << "func: " << ERR_func_error_string(lastError) << ", "
983 << "reason: " << ERR_reason_error_string(lastError);
989 void AsyncSSLSocket::checkForImmediateRead() noexcept {
990 // openssl may have buffered data that it read from the socket already.
991 // In this case we have to process it immediately, rather than waiting for
992 // the socket to become readable again.
993 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
994 AsyncSocket::handleRead();
999 AsyncSSLSocket::restartSSLAccept()
1001 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this << ", fd=" << fd_
1002 << ", state=" << int(state_) << ", "
1003 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1004 DestructorGuard dg(this);
1006 sslState_ == STATE_CACHE_LOOKUP ||
1007 sslState_ == STATE_ASYNC_PENDING ||
1008 sslState_ == STATE_ERROR ||
1009 sslState_ == STATE_CLOSED
1011 if (sslState_ == STATE_CLOSED) {
1012 // I sure hope whoever closed this socket didn't delete it already,
1013 // but this is not strictly speaking an error
1016 if (sslState_ == STATE_ERROR) {
1017 // go straight to fail if timeout expired during lookup
1018 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
1019 "SSL accept timed out");
1020 failHandshake(__func__, ex);
1023 sslState_ = STATE_ACCEPTING;
1024 this->handleAccept();
1028 AsyncSSLSocket::handleAccept() noexcept {
1029 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
1030 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1031 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1033 assert(state_ == StateEnum::ESTABLISHED &&
1034 sslState_ == STATE_ACCEPTING);
1036 /* lazily create the SSL structure */
1038 ssl_ = ctx_->createSSL();
1039 } catch (std::exception &e) {
1040 sslState_ = STATE_ERROR;
1041 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1042 "error calling SSLContext::createSSL()");
1043 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
1044 << ", fd=" << fd_ << "): " << e.what();
1045 return failHandshake(__func__, ex);
1047 SSL_set_fd(ssl_, fd_);
1048 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
1050 applyVerificationOptions(ssl_);
1053 if (server_ && parseClientHello_) {
1054 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1055 SSL_set_msg_callback_arg(ssl_, this);
1059 int ret = SSL_accept(ssl_);
1062 unsigned long errError;
1063 int errnoCopy = errno;
1064 if (willBlock(ret, &sslError, &errError)) {
1067 sslState_ = STATE_ERROR;
1068 SSLException ex(sslError, errError, ret, errnoCopy);
1069 return failHandshake(__func__, ex);
1073 handshakeComplete_ = true;
1074 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1076 // Move into STATE_ESTABLISHED in the normal case that we are in
1078 sslState_ = STATE_ESTABLISHED;
1080 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1081 << " successfully accepted; state=" << int(state_)
1082 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1084 // Remember the EventBase we are attached to, before we start invoking any
1085 // callbacks (since the callbacks may call detachEventBase()).
1086 EventBase* originalEventBase = eventBase_;
1088 // Call the accept callback.
1089 invokeHandshakeCB();
1091 // Note that the accept callback may have changed our state.
1092 // (set or unset the read callback, called write(), closed the socket, etc.)
1093 // The following code needs to handle these situations correctly.
1095 // If the socket has been closed, readCallback_ and writeReqHead_ will
1096 // always be nullptr, so that will prevent us from trying to read or write.
1098 // The main thing to check for is if eventBase_ is still originalEventBase.
1099 // If not, we have been detached from this event base, so we shouldn't
1100 // perform any more operations.
1101 if (eventBase_ != originalEventBase) {
1105 AsyncSocket::handleInitialReadWrite();
1109 AsyncSSLSocket::handleConnect() noexcept {
1110 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1111 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1112 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1114 if (state_ < StateEnum::ESTABLISHED) {
1115 return AsyncSocket::handleConnect();
1118 assert(state_ == StateEnum::ESTABLISHED &&
1119 sslState_ == STATE_CONNECTING);
1123 int ret = SSL_connect(ssl_);
1126 unsigned long errError;
1127 int errnoCopy = errno;
1128 if (willBlock(ret, &sslError, &errError)) {
1131 sslState_ = STATE_ERROR;
1132 SSLException ex(sslError, errError, ret, errnoCopy);
1133 return failHandshake(__func__, ex);
1137 handshakeComplete_ = true;
1138 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1140 // Move into STATE_ESTABLISHED in the normal case that we are in
1141 // STATE_CONNECTING.
1142 sslState_ = STATE_ESTABLISHED;
1144 VLOG(3) << "AsyncSSLSocket " << this << ": "
1145 << "fd " << fd_ << " successfully connected; "
1146 << "state=" << int(state_) << ", sslState=" << sslState_
1147 << ", events=" << eventFlags_;
1149 // Remember the EventBase we are attached to, before we start invoking any
1150 // callbacks (since the callbacks may call detachEventBase()).
1151 EventBase* originalEventBase = eventBase_;
1153 // Call the handshake callback.
1154 invokeHandshakeCB();
1156 // Note that the connect callback may have changed our state.
1157 // (set or unset the read callback, called write(), closed the socket, etc.)
1158 // The following code needs to handle these situations correctly.
1160 // If the socket has been closed, readCallback_ and writeReqHead_ will
1161 // always be nullptr, so that will prevent us from trying to read or write.
1163 // The main thing to check for is if eventBase_ is still originalEventBase.
1164 // If not, we have been detached from this event base, so we shouldn't
1165 // perform any more operations.
1166 if (eventBase_ != originalEventBase) {
1170 AsyncSocket::handleInitialReadWrite();
1173 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1174 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1175 // turn on the buffer movable in openssl
1176 if (bufferMovableEnabled_ && ssl_ != nullptr && !isBufferMovable_ &&
1177 callback != nullptr && callback->isBufferMovable()) {
1178 SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1179 isBufferMovable_ = true;
1183 AsyncSocket::setReadCB(callback);
1186 void AsyncSSLSocket::setBufferMovableEnabled(bool enabled) {
1187 bufferMovableEnabled_ = enabled;
1190 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) noexcept {
1191 CHECK(readCallback_);
1192 if (isBufferMovable_) {
1196 // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1197 readCallback_->getReadBuffer(buf, buflen);
1202 AsyncSSLSocket::handleRead() noexcept {
1203 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1204 << ", state=" << int(state_) << ", "
1205 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1206 if (state_ < StateEnum::ESTABLISHED) {
1207 return AsyncSocket::handleRead();
1211 if (sslState_ == STATE_ACCEPTING) {
1216 else if (sslState_ == STATE_CONNECTING) {
1223 AsyncSocket::handleRead();
1227 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1228 VLOG(4) << "AsyncSSLSocket::performRead() this=" << this
1229 << ", buf=" << *buf << ", buflen=" << *buflen;
1231 if (sslState_ == STATE_UNENCRYPTED) {
1232 return AsyncSocket::performRead(buf, buflen, offset);
1237 if (!isBufferMovable_) {
1238 bytes = SSL_read(ssl_, *buf, *buflen);
1240 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1242 bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1246 if (server_ && renegotiateAttempted_) {
1247 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1248 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1249 << "): client intitiated SSL renegotiation not permitted";
1250 // We pack our own SSLerr here with a dummy function
1251 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1252 SSL_CLIENT_RENEGOTIATION_ATTEMPT);
1257 int error = SSL_get_error(ssl_, bytes);
1258 if (error == SSL_ERROR_WANT_READ) {
1259 // The caller will register for read event if not already.
1260 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1261 return READ_BLOCKING;
1265 } else if (error == SSL_ERROR_WANT_WRITE) {
1266 // TODO: Even though we are attempting to read data, SSL_read() may
1267 // need to write data if renegotiation is being performed. We currently
1268 // don't support this and just fail the read.
1269 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1270 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1271 << "): unsupported SSL renegotiation during read",
1272 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1273 SSL_INVALID_RENEGOTIATION);
1277 // TODO: Fix this code so that it can return a proper error message
1278 // to the callback, rather than relying on AsyncSocket code which
1279 // can't handle SSL errors.
1280 long lastError = ERR_get_error();
1282 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1283 << "state=" << state_ << ", "
1284 << "sslState=" << sslState_ << ", "
1285 << "events=" << std::hex << eventFlags_ << "): "
1286 << "bytes: " << bytes << ", "
1287 << "error: " << error << ", "
1288 << "errno: " << errno << ", "
1289 << "func: " << ERR_func_error_string(lastError) << ", "
1290 << "reason: " << ERR_reason_error_string(lastError);
1292 if (zero_return(error, bytes)) {
1295 if (error != SSL_ERROR_SYSCALL) {
1296 if ((unsigned long)lastError < 0x8000) {
1305 appBytesReceived_ += bytes;
1310 void AsyncSSLSocket::handleWrite() noexcept {
1311 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1312 << ", state=" << int(state_) << ", "
1313 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1314 if (state_ < StateEnum::ESTABLISHED) {
1315 return AsyncSocket::handleWrite();
1318 if (sslState_ == STATE_ACCEPTING) {
1324 if (sslState_ == STATE_CONNECTING) {
1331 AsyncSocket::handleWrite();
1334 int AsyncSSLSocket::interpretSSLError(int rc, int error) {
1335 if (error == SSL_ERROR_WANT_READ) {
1336 // TODO: Even though we are attempting to write data, SSL_write() may
1337 // need to read data if renegotiation is being performed. We currently
1338 // don't support this and just fail the write.
1339 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1340 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1341 << "): " << "unsupported SSL renegotiation during write",
1342 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1343 SSL_INVALID_RENEGOTIATION);
1347 // TODO: Fix this code so that it can return a proper error message
1348 // to the callback, rather than relying on AsyncSocket code which
1349 // can't handle SSL errors.
1350 long lastError = ERR_get_error();
1351 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1352 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1353 << "SSL error: " << error << ", errno: " << errno
1354 << ", func: " << ERR_func_error_string(lastError)
1355 << ", reason: " << ERR_reason_error_string(lastError);
1356 if (error != SSL_ERROR_SYSCALL) {
1357 if ((unsigned long)lastError < 0x8000) {
1364 if (!zero_return(error, rc)) {
1372 ssize_t AsyncSSLSocket::performWrite(const iovec* vec,
1375 uint32_t* countWritten,
1376 uint32_t* partialWritten) {
1377 if (sslState_ == STATE_UNENCRYPTED) {
1378 return AsyncSocket::performWrite(
1379 vec, count, flags, countWritten, partialWritten);
1381 if (sslState_ != STATE_ESTABLISHED) {
1382 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1383 << ", sslState=" << sslState_
1384 << ", events=" << eventFlags_ << "): "
1385 << "TODO: AsyncSSLSocket currently does not support calling "
1386 << "write() before the handshake has fully completed";
1387 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1392 bool cork = isSet(flags, WriteFlags::CORK);
1393 CorkGuard guard(fd_, count > 1, cork, &corked_);
1396 //#ifdef SSL_MODE_WRITE_IOVEC
1397 if (ssl_->expand == nullptr &&
1398 ssl_->compress == nullptr &&
1399 (ssl_->mode & SSL_MODE_WRITE_IOVEC)) {
1400 return performWriteIovec(vec, count, flags, countWritten, partialWritten);
1404 // Declare a buffer used to hold small write requests. It could point to a
1405 // memory block either on stack or on heap. If it is on heap, we release it
1406 // manually when scope exits
1407 char* combinedBuf{nullptr};
1409 // Note, always keep this check consistent with what we do below
1410 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1411 delete[] combinedBuf;
1416 *partialWritten = 0;
1417 ssize_t totalWritten = 0;
1418 size_t bytesStolenFromNextBuffer = 0;
1419 for (uint32_t i = 0; i < count; i++) {
1420 const iovec* v = vec + i;
1421 size_t offset = bytesStolenFromNextBuffer;
1422 bytesStolenFromNextBuffer = 0;
1423 size_t len = v->iov_len - offset;
1429 buf = ((const char*)v->iov_base) + offset;
1433 uint32_t buffersStolen = 0;
1434 if ((len < minWriteSize_) && ((i + 1) < count)) {
1435 // Combine this buffer with part or all of the next buffers in
1436 // order to avoid really small-grained calls to SSL_write().
1437 // Each call to SSL_write() produces a separate record in
1438 // the egress SSL stream, and we've found that some low-end
1439 // mobile clients can't handle receiving an HTTP response
1440 // header and the first part of the response body in two
1441 // separate SSL records (even if those two records are in
1442 // the same TCP packet).
1444 if (combinedBuf == nullptr) {
1445 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1446 // Allocate the buffer on heap
1447 combinedBuf = new char[minWriteSize_];
1449 // Allocate the buffer on stack
1450 combinedBuf = (char*)alloca(minWriteSize_);
1453 assert(combinedBuf != nullptr);
1455 memcpy(combinedBuf, buf, len);
1457 // INVARIANT: i + buffersStolen == complete chunks serialized
1458 uint32_t nextIndex = i + buffersStolen + 1;
1459 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1460 minWriteSize_ - len);
1461 memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1462 bytesStolenFromNextBuffer);
1463 len += bytesStolenFromNextBuffer;
1464 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1465 // couldn't steal the whole buffer
1468 bytesStolenFromNextBuffer = 0;
1471 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1472 bytes = eorAwareSSLWrite(
1473 ssl_, combinedBuf, len,
1474 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1477 bytes = eorAwareSSLWrite(ssl_, buf, len,
1478 (isSet(flags, WriteFlags::EOR) && i + 1 == count));
1482 int error = SSL_get_error(ssl_, bytes);
1483 if (error == SSL_ERROR_WANT_WRITE) {
1484 // The caller will register for write event if not already.
1485 *partialWritten = offset;
1486 return totalWritten;
1488 int rc = interpretSSLError(bytes, error);
1491 } // else fall through to below to correctly record totalWritten
1494 totalWritten += bytes;
1496 if (bytes == (ssize_t)len) {
1497 // The full iovec is written.
1498 (*countWritten) += 1 + buffersStolen;
1502 bytes += offset; // adjust bytes to account for all of v
1503 while (bytes >= (ssize_t)v->iov_len) {
1504 // We combined this buf with part or all of the next one, and
1505 // we managed to write all of this buf but not all of the bytes
1506 // from the next one that we'd hoped to write.
1507 bytes -= v->iov_len;
1511 *partialWritten = bytes;
1512 return totalWritten;
1516 return totalWritten;
1520 //#ifdef SSL_MODE_WRITE_IOVEC
1521 ssize_t AsyncSSLSocket::performWriteIovec(const iovec* vec,
1524 uint32_t* countWritten,
1525 uint32_t* partialWritten) {
1527 for (uint32_t j = 0; j < count; j++) {
1528 tot += vec[j].iov_len;
1531 ssize_t totalWritten = SSL_write_iovec(ssl_, vec, count);
1534 *partialWritten = 0;
1535 if (totalWritten <= 0) {
1536 return interpretSSLError(totalWritten, SSL_get_error(ssl_, totalWritten));
1538 ssize_t bytes = totalWritten, i = 0;
1539 while (i < count && bytes >= (ssize_t)vec[i].iov_len) {
1540 // we managed to write all of this buf
1541 bytes -= vec[i].iov_len;
1545 *partialWritten = bytes;
1547 VLOG(4) << "SSL_write_iovec() writes " << tot
1548 << ", returns " << totalWritten << " bytes"
1549 << ", max_send_fragment=" << ssl_->max_send_fragment
1550 << ", count=" << count << ", countWritten=" << *countWritten;
1552 return totalWritten;
1557 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1559 if (eor && SSL_get_wbio(ssl)->method == &eorAwareBioMethod) {
1560 if (appEorByteNo_) {
1561 // cannot track for more than one app byte EOR
1562 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1564 appEorByteNo_ = appBytesWritten_ + n;
1567 // 1. It is fine to keep updating minEorRawByteNo_.
1568 // 2. It is _min_ in the sense that SSL record will add some overhead.
1569 minEorRawByteNo_ = getRawBytesWritten() + n;
1572 n = sslWriteImpl(ssl, buf, n);
1574 appBytesWritten_ += n;
1575 if (appEorByteNo_) {
1576 if (getRawBytesWritten() >= minEorRawByteNo_) {
1577 minEorRawByteNo_ = 0;
1579 if(appBytesWritten_ == appEorByteNo_) {
1582 CHECK(appBytesWritten_ < appEorByteNo_);
1589 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int /* ret */) {
1590 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1591 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1592 sslSocket->renegotiateAttempted_ = true;
1596 int AsyncSSLSocket::eorAwareBioWrite(BIO *b, const char *in, int inl) {
1601 AsyncSSLSocket *tsslSock;
1603 iov.iov_base = const_cast<char *>(in);
1605 memset(&msg, 0, sizeof(msg));
1610 reinterpret_cast<AsyncSSLSocket*>(BIO_get_app_data(b));
1612 tsslSock->minEorRawByteNo_ &&
1613 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1618 ret = sendmsg(b->num, &msg, flags);
1619 BIO_clear_retry_flags(b);
1621 if (BIO_sock_should_retry(ret))
1622 BIO_set_retry_write(b);
1627 int AsyncSSLSocket::sslVerifyCallback(int preverifyOk,
1628 X509_STORE_CTX* x509Ctx) {
1629 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1630 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1631 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1633 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1634 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1635 return (self->handshakeCallback_) ?
1636 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1640 void AsyncSSLSocket::enableClientHelloParsing() {
1641 parseClientHello_ = true;
1642 clientHelloInfo_.reset(new ssl::ClientHelloInfo());
1645 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1646 SSL_set_msg_callback(ssl, nullptr);
1647 SSL_set_msg_callback_arg(ssl, nullptr);
1648 clientHelloInfo_->clientHelloBuf_.clear();
1651 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1658 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1660 sock->resetClientHelloParsing(ssl);
1663 if (contentType != SSL3_RT_HANDSHAKE) {
1670 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1671 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1673 Cursor cursor(clientHelloBuf.front());
1674 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1675 sock->resetClientHelloParsing(ssl);
1679 if (cursor.totalLength() < 3) {
1680 clientHelloBuf.trimEnd(len);
1681 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1685 uint32_t messageLength = cursor.read<uint8_t>();
1686 messageLength <<= 8;
1687 messageLength |= cursor.read<uint8_t>();
1688 messageLength <<= 8;
1689 messageLength |= cursor.read<uint8_t>();
1690 if (cursor.totalLength() < messageLength) {
1691 clientHelloBuf.trimEnd(len);
1692 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1696 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1697 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1699 cursor.skip(4); // gmt_unix_time
1700 cursor.skip(28); // random_bytes
1702 cursor.skip(cursor.read<uint8_t>()); // session_id
1704 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1705 for (int i = 0; i < cipherSuitesLength; i += 2) {
1706 sock->clientHelloInfo_->
1707 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1710 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1711 for (int i = 0; i < compressionMethodsLength; ++i) {
1712 sock->clientHelloInfo_->
1713 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1716 if (cursor.totalLength() > 0) {
1717 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1718 while (extensionsLength) {
1719 ssl::TLSExtension extensionType =
1720 static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>());
1721 sock->clientHelloInfo_->
1722 clientHelloExtensions_.push_back(extensionType);
1723 extensionsLength -= 2;
1724 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1725 extensionsLength -= 2;
1727 if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) {
1729 extensionDataLength -= 2;
1730 while (extensionDataLength) {
1731 ssl::HashAlgorithm hashAlg =
1732 static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>());
1733 ssl::SignatureAlgorithm sigAlg =
1734 static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>());
1735 extensionDataLength -= 2;
1736 sock->clientHelloInfo_->
1737 clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1740 cursor.skip(extensionDataLength);
1741 extensionsLength -= extensionDataLength;
1745 } catch (std::out_of_range& e) {
1746 // we'll use what we found and cleanup below.
1747 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1748 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1751 sock->resetClientHelloParsing(ssl);