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 } // anonymous namespace
253 SSLException::SSLException(int sslError, int errno_copy):
254 AsyncSocketException(
255 AsyncSocketException::SSL_ERROR,
256 ERR_error_string(sslError, msg_),
257 sslError == SSL_ERROR_SYSCALL ? errno_copy : 0), error_(sslError) {}
260 * Create a client AsyncSSLSocket
262 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
263 EventBase* evb, bool deferSecurityNegotiation) :
266 handshakeTimeout_(this, evb) {
268 if (deferSecurityNegotiation) {
269 sslState_ = STATE_UNENCRYPTED;
274 * Create a server/client AsyncSSLSocket
276 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
277 EventBase* evb, int fd, bool server,
278 bool deferSecurityNegotiation) :
279 AsyncSocket(evb, fd),
282 handshakeTimeout_(this, evb) {
285 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
286 AsyncSSLSocket::sslInfoCallback);
288 if (deferSecurityNegotiation) {
289 sslState_ = STATE_UNENCRYPTED;
293 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
295 * Create a client AsyncSSLSocket and allow tlsext_hostname
296 * to be sent in Client Hello.
298 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
300 const std::string& serverName,
301 bool deferSecurityNegotiation) :
302 AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
303 tlsextHostname_ = serverName;
307 * Create a client AsyncSSLSocket from an already connected fd
308 * and allow tlsext_hostname to be sent in Client Hello.
310 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
311 EventBase* evb, int fd,
312 const std::string& serverName,
313 bool deferSecurityNegotiation) :
314 AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
315 tlsextHostname_ = serverName;
319 AsyncSSLSocket::~AsyncSSLSocket() {
320 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
321 << ", evb=" << eventBase_ << ", fd=" << fd_
322 << ", state=" << int(state_) << ", sslState="
323 << sslState_ << ", events=" << eventFlags_ << ")";
326 void AsyncSSLSocket::init() {
327 // Do this here to ensure we initialize this once before any use of
328 // AsyncSSLSocket instances and not as part of library load.
329 static const auto eorAwareBioMethodInitializer = initEorBioMethod();
330 (void)eorAwareBioMethodInitializer;
332 setup_SSL_CTX(ctx_->getSSLCtx());
335 void AsyncSSLSocket::closeNow() {
336 // Close the SSL connection.
337 if (ssl_ != nullptr && fd_ != -1) {
338 int rc = SSL_shutdown(ssl_);
340 rc = SSL_shutdown(ssl_);
347 if (sslSession_ != nullptr) {
348 SSL_SESSION_free(sslSession_);
349 sslSession_ = nullptr;
352 sslState_ = STATE_CLOSED;
354 if (handshakeTimeout_.isScheduled()) {
355 handshakeTimeout_.cancelTimeout();
358 DestructorGuard dg(this);
361 AsyncSocketException(
362 AsyncSocketException::END_OF_FILE,
363 "SSL connection closed locally"));
365 if (ssl_ != nullptr) {
371 AsyncSocket::closeNow();
374 void AsyncSSLSocket::shutdownWrite() {
375 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
377 // (Performing a full shutdown here is more desirable than doing nothing at
378 // all. The purpose of shutdownWrite() is normally to notify the other end
379 // of the connection that no more data will be sent. If we do nothing, the
380 // other end will never know that no more data is coming, and this may result
381 // in protocol deadlock.)
385 void AsyncSSLSocket::shutdownWriteNow() {
389 bool AsyncSSLSocket::good() const {
390 return (AsyncSocket::good() &&
391 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
392 sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
395 // The TAsyncTransport definition of 'good' states that the transport is
396 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
397 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
398 // is connected but we haven't initiated the call to SSL_connect.
399 bool AsyncSSLSocket::connecting() const {
401 (AsyncSocket::connecting() ||
402 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
403 sslState_ == STATE_CONNECTING))));
406 std::string AsyncSSLSocket::getApplicationProtocol() noexcept {
407 const unsigned char* protoName = nullptr;
408 unsigned protoLength;
409 if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) {
410 return std::string(reinterpret_cast<const char*>(protoName), protoLength);
415 bool AsyncSSLSocket::isEorTrackingEnabled() const {
416 if (ssl_ == nullptr) {
419 const BIO *wb = SSL_get_wbio(ssl_);
420 return wb && wb->method == &eorAwareBioMethod;
423 void AsyncSSLSocket::setEorTracking(bool track) {
424 BIO *wb = SSL_get_wbio(ssl_);
426 throw AsyncSocketException(AsyncSocketException::INVALID_STATE,
427 "setting EOR tracking without an initialized "
432 if (wb->method != &eorAwareBioMethod) {
433 // only do this if we didn't
434 wb->method = &eorAwareBioMethod;
435 BIO_set_app_data(wb, this);
437 minEorRawByteNo_ = 0;
439 } else if (wb->method == &eorAwareBioMethod) {
440 wb->method = BIO_s_socket();
441 BIO_set_app_data(wb, nullptr);
443 minEorRawByteNo_ = 0;
445 CHECK(wb->method == BIO_s_socket());
449 size_t AsyncSSLSocket::getRawBytesWritten() const {
451 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
455 return BIO_number_written(b);
458 size_t AsyncSSLSocket::getRawBytesReceived() const {
460 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
464 return BIO_number_read(b);
468 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
469 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
470 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
471 << "events=" << eventFlags_ << ", server=" << short(server_) << "): "
472 << "sslAccept/Connect() called in invalid "
473 << "state, handshake callback " << handshakeCallback_ << ", new callback "
475 assert(!handshakeTimeout_.isScheduled());
476 sslState_ = STATE_ERROR;
478 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
479 "sslAccept() called with socket in invalid state");
481 handshakeEndTime_ = std::chrono::steady_clock::now();
483 callback->handshakeErr(this, ex);
486 // Check the socket state not the ssl state here.
487 if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
488 failHandshake(__func__, ex);
492 void AsyncSSLSocket::sslAccept(HandshakeCB* callback, uint32_t timeout,
493 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
494 DestructorGuard dg(this);
495 assert(eventBase_->isInEventBaseThread());
496 verifyPeer_ = verifyPeer;
498 // Make sure we're in the uninitialized state
499 if (!server_ || (sslState_ != STATE_UNINIT &&
500 sslState_ != STATE_UNENCRYPTED) ||
501 handshakeCallback_ != nullptr) {
502 return invalidState(callback);
505 // Cache local and remote socket addresses to keep them available
506 // after socket file descriptor is closed.
507 if (cacheAddrOnFailure_ && -1 != getFd()) {
508 cacheLocalPeerAddr();
511 handshakeStartTime_ = std::chrono::steady_clock::now();
512 // Make end time at least >= start time.
513 handshakeEndTime_ = handshakeStartTime_;
515 sslState_ = STATE_ACCEPTING;
516 handshakeCallback_ = callback;
519 handshakeTimeout_.scheduleTimeout(timeout);
522 /* register for a read operation (waiting for CLIENT HELLO) */
523 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
526 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
527 void AsyncSSLSocket::attachSSLContext(
528 const std::shared_ptr<SSLContext>& ctx) {
530 // Check to ensure we are in client mode. Changing a server's ssl
531 // context doesn't make sense since clients of that server would likely
532 // become confused when the server's context changes.
536 DCHECK(ctx->getSSLCtx());
539 // In order to call attachSSLContext, detachSSLContext must have been
540 // previously called which sets the socket's context to the dummy
541 // context. Thus we must acquire this lock.
542 SpinLockGuard guard(dummyCtxLock);
543 SSL_set_SSL_CTX(ssl_, ctx->getSSLCtx());
546 void AsyncSSLSocket::detachSSLContext() {
549 // We aren't using the initial_ctx for now, and it can introduce race
550 // conditions in the destructor of the SSL object.
551 #ifndef OPENSSL_NO_TLSEXT
552 if (ssl_->initial_ctx) {
553 SSL_CTX_free(ssl_->initial_ctx);
554 ssl_->initial_ctx = nullptr;
557 SpinLockGuard guard(dummyCtxLock);
558 if (nullptr == dummyCtx) {
559 // We need to lazily initialize the dummy context so we don't
560 // accidentally override any programmatic settings to openssl
561 dummyCtx = new SSLContext;
563 // We must remove this socket's references to its context right now
564 // since this socket could get passed to any thread. If the context has
565 // had its locking disabled, just doing a set in attachSSLContext()
566 // would not be thread safe.
567 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
571 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
572 void AsyncSSLSocket::switchServerSSLContext(
573 const std::shared_ptr<SSLContext>& handshakeCtx) {
575 if (sslState_ != STATE_ACCEPTING) {
576 // We log it here and allow the switch.
577 // It should not affect our re-negotiation support (which
578 // is not supported now).
579 VLOG(6) << "fd=" << getFd()
580 << " renegotation detected when switching SSL_CTX";
583 setup_SSL_CTX(handshakeCtx->getSSLCtx());
584 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
585 AsyncSSLSocket::sslInfoCallback);
586 handshakeCtx_ = handshakeCtx;
587 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
590 bool AsyncSSLSocket::isServerNameMatch() const {
597 SSL_SESSION *ss = SSL_get_session(ssl_);
602 if(!ss->tlsext_hostname) {
605 return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
608 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
609 tlsextHostname_ = std::move(serverName);
614 void AsyncSSLSocket::timeoutExpired() noexcept {
615 if (state_ == StateEnum::ESTABLISHED &&
616 (sslState_ == STATE_CACHE_LOOKUP ||
617 sslState_ == STATE_ASYNC_PENDING)) {
618 sslState_ = STATE_ERROR;
619 // We are expecting a callback in restartSSLAccept. The cache lookup
620 // and rsa-call necessarily have pointers to this ssl socket, so delay
621 // the cleanup until he calls us back.
623 assert(state_ == StateEnum::ESTABLISHED &&
624 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
625 DestructorGuard dg(this);
626 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
627 (sslState_ == STATE_CONNECTING) ?
628 "SSL connect timed out" : "SSL accept timed out");
629 failHandshake(__func__, ex);
633 int AsyncSSLSocket::getSSLExDataIndex() {
634 static auto index = SSL_get_ex_new_index(
635 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
639 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
640 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
641 getSSLExDataIndex()));
644 void AsyncSSLSocket::failHandshake(const char* /* fn */,
645 const AsyncSocketException& ex) {
647 if (handshakeTimeout_.isScheduled()) {
648 handshakeTimeout_.cancelTimeout();
650 invokeHandshakeErr(ex);
654 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
655 handshakeEndTime_ = std::chrono::steady_clock::now();
656 if (handshakeCallback_ != nullptr) {
657 HandshakeCB* callback = handshakeCallback_;
658 handshakeCallback_ = nullptr;
659 callback->handshakeErr(this, ex);
663 void AsyncSSLSocket::invokeHandshakeCB() {
664 handshakeEndTime_ = std::chrono::steady_clock::now();
665 if (handshakeTimeout_.isScheduled()) {
666 handshakeTimeout_.cancelTimeout();
668 if (handshakeCallback_) {
669 HandshakeCB* callback = handshakeCallback_;
670 handshakeCallback_ = nullptr;
671 callback->handshakeSuc(this);
675 void AsyncSSLSocket::cacheLocalPeerAddr() {
676 SocketAddress address;
678 getLocalAddress(&address);
679 getPeerAddress(&address);
680 } catch (const std::system_error& e) {
681 // The handle can be still valid while the connection is already closed.
682 if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
688 void AsyncSSLSocket::connect(ConnectCallback* callback,
689 const folly::SocketAddress& address,
691 const OptionMap &options,
692 const folly::SocketAddress& bindAddr)
695 assert(state_ == StateEnum::UNINIT);
696 assert(sslState_ == STATE_UNINIT);
697 AsyncSSLSocketConnector *connector =
698 new AsyncSSLSocketConnector(this, callback, timeout);
699 AsyncSocket::connect(connector, address, timeout, options, bindAddr);
702 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
703 // apply the settings specified in verifyPeer_
704 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
705 if(ctx_->needsPeerVerification()) {
706 SSL_set_verify(ssl, ctx_->getVerificationMode(),
707 AsyncSSLSocket::sslVerifyCallback);
710 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
711 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
712 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
713 AsyncSSLSocket::sslVerifyCallback);
718 void AsyncSSLSocket::sslConn(HandshakeCB* callback, uint64_t timeout,
719 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
720 DestructorGuard dg(this);
721 assert(eventBase_->isInEventBaseThread());
723 // Cache local and remote socket addresses to keep them available
724 // after socket file descriptor is closed.
725 if (cacheAddrOnFailure_ && -1 != getFd()) {
726 cacheLocalPeerAddr();
729 verifyPeer_ = verifyPeer;
731 // Make sure we're in the uninitialized state
732 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
733 STATE_UNENCRYPTED) ||
734 handshakeCallback_ != nullptr) {
735 return invalidState(callback);
738 handshakeStartTime_ = std::chrono::steady_clock::now();
739 // Make end time at least >= start time.
740 handshakeEndTime_ = handshakeStartTime_;
742 sslState_ = STATE_CONNECTING;
743 handshakeCallback_ = callback;
746 ssl_ = ctx_->createSSL();
747 } catch (std::exception &e) {
748 sslState_ = STATE_ERROR;
749 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
750 "error calling SSLContext::createSSL()");
751 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
752 << fd_ << "): " << e.what();
753 return failHandshake(__func__, ex);
756 applyVerificationOptions(ssl_);
758 SSL_set_fd(ssl_, fd_);
759 if (sslSession_ != nullptr) {
760 SSL_set_session(ssl_, sslSession_);
761 SSL_SESSION_free(sslSession_);
762 sslSession_ = nullptr;
764 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
765 if (tlsextHostname_.size()) {
766 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
770 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
773 handshakeTimeout_.scheduleTimeout(timeout);
779 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
780 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
781 return SSL_get1_session(ssl_);
787 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
788 sslSession_ = session;
789 if (!takeOwnership && session != nullptr) {
790 // Increment the reference count
791 CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
795 void AsyncSSLSocket::getSelectedNextProtocol(
796 const unsigned char** protoName,
798 SSLContext::NextProtocolType* protoType) const {
799 if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
800 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
801 "NPN not supported");
805 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
806 const unsigned char** protoName,
808 SSLContext::NextProtocolType* protoType) const {
809 *protoName = nullptr;
811 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
812 SSL_get0_alpn_selected(ssl_, protoName, protoLen);
815 *protoType = SSLContext::NextProtocolType::ALPN;
820 #ifdef OPENSSL_NPN_NEGOTIATED
821 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
823 *protoType = SSLContext::NextProtocolType::NPN;
832 bool AsyncSSLSocket::getSSLSessionReused() const {
833 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
834 return SSL_session_reused(ssl_);
839 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
840 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
844 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
845 if (ssl == nullptr) {
848 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
849 return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
855 const char *AsyncSSLSocket::getSSLServerName() const {
856 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
857 return getSSLServerNameFromSSL(ssl_);
859 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
860 "SNI not supported");
864 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
865 return getSSLServerNameFromSSL(ssl_);
868 int AsyncSSLSocket::getSSLVersion() const {
869 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
872 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
873 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
875 int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
876 return OBJ_nid2ln(nid);
881 int AsyncSSLSocket::getSSLCertSize() const {
883 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
885 EVP_PKEY *key = X509_get_pubkey(cert);
886 certSize = EVP_PKEY_bits(key);
892 bool AsyncSSLSocket::willBlock(int ret, int *errorOut) noexcept {
893 int error = *errorOut = SSL_get_error(ssl_, ret);
894 if (error == SSL_ERROR_WANT_READ) {
895 // Register for read event if not already.
896 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
898 } else if (error == SSL_ERROR_WANT_WRITE) {
899 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
900 << ", state=" << int(state_) << ", sslState="
901 << sslState_ << ", events=" << eventFlags_ << "): "
902 << "SSL_ERROR_WANT_WRITE";
903 // Register for write event if not already.
904 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
906 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
907 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
908 // We will block but we can't register our own socket. The callback that
909 // triggered this code will re-call handleAccept at the appropriate time.
911 // We can only get here if the linked libssl.so has support for this feature
912 // as well, otherwise SSL_get_error cannot return our error code.
913 sslState_ = STATE_CACHE_LOOKUP;
915 // Unregister for all events while blocked here
916 updateEventRegistration(EventHandler::NONE,
917 EventHandler::READ | EventHandler::WRITE);
919 // The timeout (if set) keeps running here
923 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
924 || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
926 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
927 || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
930 // Our custom openssl function has kicked off an async request to do
931 // rsa/ecdsa private key operation. When that call returns, a callback will
932 // be invoked that will re-call handleAccept.
933 sslState_ = STATE_ASYNC_PENDING;
935 // Unregister for all events while blocked here
936 updateEventRegistration(
938 EventHandler::READ | EventHandler::WRITE
941 // The timeout (if set) keeps running here
944 // SSL_ERROR_ZERO_RETURN is processed here so we can get some detail
946 long lastError = ERR_get_error();
947 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
948 << "state=" << state_ << ", "
949 << "sslState=" << sslState_ << ", "
950 << "events=" << std::hex << eventFlags_ << "): "
951 << "SSL error: " << error << ", "
952 << "errno: " << errno << ", "
953 << "ret: " << ret << ", "
954 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
955 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
956 << "func: " << ERR_func_error_string(lastError) << ", "
957 << "reason: " << ERR_reason_error_string(lastError);
958 if (error != SSL_ERROR_SYSCALL) {
959 if (error == SSL_ERROR_SSL) {
960 *errorOut = lastError;
962 if ((unsigned long)lastError < 0x8000) {
973 void AsyncSSLSocket::checkForImmediateRead() noexcept {
974 // openssl may have buffered data that it read from the socket already.
975 // In this case we have to process it immediately, rather than waiting for
976 // the socket to become readable again.
977 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
978 AsyncSocket::handleRead();
983 AsyncSSLSocket::restartSSLAccept()
985 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this << ", fd=" << fd_
986 << ", state=" << int(state_) << ", "
987 << "sslState=" << sslState_ << ", events=" << eventFlags_;
988 DestructorGuard dg(this);
990 sslState_ == STATE_CACHE_LOOKUP ||
991 sslState_ == STATE_ASYNC_PENDING ||
992 sslState_ == STATE_ERROR ||
993 sslState_ == STATE_CLOSED
995 if (sslState_ == STATE_CLOSED) {
996 // I sure hope whoever closed this socket didn't delete it already,
997 // but this is not strictly speaking an error
1000 if (sslState_ == STATE_ERROR) {
1001 // go straight to fail if timeout expired during lookup
1002 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
1003 "SSL accept timed out");
1004 failHandshake(__func__, ex);
1007 sslState_ = STATE_ACCEPTING;
1008 this->handleAccept();
1012 AsyncSSLSocket::handleAccept() noexcept {
1013 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
1014 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1015 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1017 assert(state_ == StateEnum::ESTABLISHED &&
1018 sslState_ == STATE_ACCEPTING);
1020 /* lazily create the SSL structure */
1022 ssl_ = ctx_->createSSL();
1023 } catch (std::exception &e) {
1024 sslState_ = STATE_ERROR;
1025 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1026 "error calling SSLContext::createSSL()");
1027 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
1028 << ", fd=" << fd_ << "): " << e.what();
1029 return failHandshake(__func__, ex);
1031 SSL_set_fd(ssl_, fd_);
1032 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
1034 applyVerificationOptions(ssl_);
1037 if (server_ && parseClientHello_) {
1038 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1039 SSL_set_msg_callback_arg(ssl_, this);
1043 int ret = SSL_accept(ssl_);
1046 if (willBlock(ret, &error)) {
1049 sslState_ = STATE_ERROR;
1050 SSLException ex(error, errno);
1051 return failHandshake(__func__, ex);
1055 handshakeComplete_ = true;
1056 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1058 // Move into STATE_ESTABLISHED in the normal case that we are in
1060 sslState_ = STATE_ESTABLISHED;
1062 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1063 << " successfully accepted; state=" << int(state_)
1064 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1066 // Remember the EventBase we are attached to, before we start invoking any
1067 // callbacks (since the callbacks may call detachEventBase()).
1068 EventBase* originalEventBase = eventBase_;
1070 // Call the accept callback.
1071 invokeHandshakeCB();
1073 // Note that the accept callback may have changed our state.
1074 // (set or unset the read callback, called write(), closed the socket, etc.)
1075 // The following code needs to handle these situations correctly.
1077 // If the socket has been closed, readCallback_ and writeReqHead_ will
1078 // always be nullptr, so that will prevent us from trying to read or write.
1080 // The main thing to check for is if eventBase_ is still originalEventBase.
1081 // If not, we have been detached from this event base, so we shouldn't
1082 // perform any more operations.
1083 if (eventBase_ != originalEventBase) {
1087 AsyncSocket::handleInitialReadWrite();
1091 AsyncSSLSocket::handleConnect() noexcept {
1092 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1093 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1094 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1096 if (state_ < StateEnum::ESTABLISHED) {
1097 return AsyncSocket::handleConnect();
1100 assert(state_ == StateEnum::ESTABLISHED &&
1101 sslState_ == STATE_CONNECTING);
1105 int ret = SSL_connect(ssl_);
1108 if (willBlock(ret, &error)) {
1111 sslState_ = STATE_ERROR;
1112 SSLException ex(error, errno);
1113 return failHandshake(__func__, ex);
1117 handshakeComplete_ = true;
1118 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1120 // Move into STATE_ESTABLISHED in the normal case that we are in
1121 // STATE_CONNECTING.
1122 sslState_ = STATE_ESTABLISHED;
1124 VLOG(3) << "AsyncSSLSocket %p: fd %d successfully connected; "
1125 << "state=" << int(state_) << ", sslState=" << sslState_
1126 << ", events=" << eventFlags_;
1128 // Remember the EventBase we are attached to, before we start invoking any
1129 // callbacks (since the callbacks may call detachEventBase()).
1130 EventBase* originalEventBase = eventBase_;
1132 // Call the handshake callback.
1133 invokeHandshakeCB();
1135 // Note that the connect callback may have changed our state.
1136 // (set or unset the read callback, called write(), closed the socket, etc.)
1137 // The following code needs to handle these situations correctly.
1139 // If the socket has been closed, readCallback_ and writeReqHead_ will
1140 // always be nullptr, so that will prevent us from trying to read or write.
1142 // The main thing to check for is if eventBase_ is still originalEventBase.
1143 // If not, we have been detached from this event base, so we shouldn't
1144 // perform any more operations.
1145 if (eventBase_ != originalEventBase) {
1149 AsyncSocket::handleInitialReadWrite();
1152 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1153 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1154 // turn on the buffer movable in openssl
1155 if (ssl_ != nullptr && !isBufferMovable_ &&
1156 callback != nullptr && callback->isBufferMovable()) {
1157 SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1158 isBufferMovable_ = true;
1162 AsyncSocket::setReadCB(callback);
1165 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) noexcept {
1166 CHECK(readCallback_);
1167 if (isBufferMovable_) {
1171 // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1172 readCallback_->getReadBuffer(buf, buflen);
1177 AsyncSSLSocket::handleRead() noexcept {
1178 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1179 << ", state=" << int(state_) << ", "
1180 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1181 if (state_ < StateEnum::ESTABLISHED) {
1182 return AsyncSocket::handleRead();
1186 if (sslState_ == STATE_ACCEPTING) {
1191 else if (sslState_ == STATE_CONNECTING) {
1198 AsyncSocket::handleRead();
1202 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1203 VLOG(4) << "AsyncSSLSocket::performRead() this=" << this
1204 << ", buf=" << *buf << ", buflen=" << *buflen;
1206 if (sslState_ == STATE_UNENCRYPTED) {
1207 return AsyncSocket::performRead(buf, buflen, offset);
1212 if (!isBufferMovable_) {
1213 bytes = SSL_read(ssl_, *buf, *buflen);
1215 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1217 bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1221 if (server_ && renegotiateAttempted_) {
1222 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1223 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1224 << "): client intitiated SSL renegotiation not permitted";
1225 // We pack our own SSLerr here with a dummy function
1226 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1227 SSL_CLIENT_RENEGOTIATION_ATTEMPT);
1232 int error = SSL_get_error(ssl_, bytes);
1233 if (error == SSL_ERROR_WANT_READ) {
1234 // The caller will register for read event if not already.
1235 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1236 return READ_BLOCKING;
1240 } else if (error == SSL_ERROR_WANT_WRITE) {
1241 // TODO: Even though we are attempting to read data, SSL_read() may
1242 // need to write data if renegotiation is being performed. We currently
1243 // don't support this and just fail the read.
1244 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1245 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1246 << "): unsupported SSL renegotiation during read",
1247 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1248 SSL_INVALID_RENEGOTIATION);
1252 // TODO: Fix this code so that it can return a proper error message
1253 // to the callback, rather than relying on AsyncSocket code which
1254 // can't handle SSL errors.
1255 long lastError = ERR_get_error();
1257 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1258 << "state=" << state_ << ", "
1259 << "sslState=" << sslState_ << ", "
1260 << "events=" << std::hex << eventFlags_ << "): "
1261 << "bytes: " << bytes << ", "
1262 << "error: " << error << ", "
1263 << "errno: " << errno << ", "
1264 << "func: " << ERR_func_error_string(lastError) << ", "
1265 << "reason: " << ERR_reason_error_string(lastError);
1267 if (zero_return(error, bytes)) {
1270 if (error != SSL_ERROR_SYSCALL) {
1271 if ((unsigned long)lastError < 0x8000) {
1280 appBytesReceived_ += bytes;
1285 void AsyncSSLSocket::handleWrite() noexcept {
1286 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1287 << ", state=" << int(state_) << ", "
1288 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1289 if (state_ < StateEnum::ESTABLISHED) {
1290 return AsyncSocket::handleWrite();
1293 if (sslState_ == STATE_ACCEPTING) {
1299 if (sslState_ == STATE_CONNECTING) {
1306 AsyncSocket::handleWrite();
1309 int AsyncSSLSocket::interpretSSLError(int rc, int error) {
1310 if (error == SSL_ERROR_WANT_READ) {
1311 // TODO: Even though we are attempting to write data, SSL_write() may
1312 // need to read data if renegotiation is being performed. We currently
1313 // don't support this and just fail the write.
1314 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1315 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1316 << "): " << "unsupported SSL renegotiation during write",
1317 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1318 SSL_INVALID_RENEGOTIATION);
1322 // TODO: Fix this code so that it can return a proper error message
1323 // to the callback, rather than relying on AsyncSocket code which
1324 // can't handle SSL errors.
1325 long lastError = ERR_get_error();
1326 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1327 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1328 << "SSL error: " << error << ", errno: " << errno
1329 << ", func: " << ERR_func_error_string(lastError)
1330 << ", reason: " << ERR_reason_error_string(lastError);
1331 if (error != SSL_ERROR_SYSCALL) {
1332 if ((unsigned long)lastError < 0x8000) {
1339 if (!zero_return(error, rc)) {
1347 ssize_t AsyncSSLSocket::performWrite(const iovec* vec,
1350 uint32_t* countWritten,
1351 uint32_t* partialWritten) {
1352 if (sslState_ == STATE_UNENCRYPTED) {
1353 return AsyncSocket::performWrite(
1354 vec, count, flags, countWritten, partialWritten);
1356 if (sslState_ != STATE_ESTABLISHED) {
1357 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1358 << ", sslState=" << sslState_
1359 << ", events=" << eventFlags_ << "): "
1360 << "TODO: AsyncSSLSocket currently does not support calling "
1361 << "write() before the handshake has fully completed";
1362 errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1367 bool cork = isSet(flags, WriteFlags::CORK) || persistentCork_;
1368 CorkGuard guard(fd_, count > 1, cork, &corked_);
1371 //#ifdef SSL_MODE_WRITE_IOVEC
1372 if (ssl_->expand == nullptr &&
1373 ssl_->compress == nullptr &&
1374 (ssl_->mode & SSL_MODE_WRITE_IOVEC)) {
1375 return performWriteIovec(vec, count, flags, countWritten, partialWritten);
1379 // Declare a buffer used to hold small write requests. It could point to a
1380 // memory block either on stack or on heap. If it is on heap, we release it
1381 // manually when scope exits
1382 char* combinedBuf{nullptr};
1384 // Note, always keep this check consistent with what we do below
1385 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1386 delete[] combinedBuf;
1391 *partialWritten = 0;
1392 ssize_t totalWritten = 0;
1393 size_t bytesStolenFromNextBuffer = 0;
1394 for (uint32_t i = 0; i < count; i++) {
1395 const iovec* v = vec + i;
1396 size_t offset = bytesStolenFromNextBuffer;
1397 bytesStolenFromNextBuffer = 0;
1398 size_t len = v->iov_len - offset;
1404 buf = ((const char*)v->iov_base) + offset;
1408 uint32_t buffersStolen = 0;
1409 if ((len < minWriteSize_) && ((i + 1) < count)) {
1410 // Combine this buffer with part or all of the next buffers in
1411 // order to avoid really small-grained calls to SSL_write().
1412 // Each call to SSL_write() produces a separate record in
1413 // the egress SSL stream, and we've found that some low-end
1414 // mobile clients can't handle receiving an HTTP response
1415 // header and the first part of the response body in two
1416 // separate SSL records (even if those two records are in
1417 // the same TCP packet).
1419 if (combinedBuf == nullptr) {
1420 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1421 // Allocate the buffer on heap
1422 combinedBuf = new char[minWriteSize_];
1424 // Allocate the buffer on stack
1425 combinedBuf = (char*)alloca(minWriteSize_);
1428 assert(combinedBuf != nullptr);
1430 memcpy(combinedBuf, buf, len);
1432 // INVARIANT: i + buffersStolen == complete chunks serialized
1433 uint32_t nextIndex = i + buffersStolen + 1;
1434 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1435 minWriteSize_ - len);
1436 memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1437 bytesStolenFromNextBuffer);
1438 len += bytesStolenFromNextBuffer;
1439 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1440 // couldn't steal the whole buffer
1443 bytesStolenFromNextBuffer = 0;
1446 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1447 bytes = eorAwareSSLWrite(
1448 ssl_, combinedBuf, len,
1449 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1452 bytes = eorAwareSSLWrite(ssl_, buf, len,
1453 (isSet(flags, WriteFlags::EOR) && i + 1 == count));
1457 int error = SSL_get_error(ssl_, bytes);
1458 if (error == SSL_ERROR_WANT_WRITE) {
1459 // The caller will register for write event if not already.
1460 *partialWritten = offset;
1461 return totalWritten;
1463 int rc = interpretSSLError(bytes, error);
1466 } // else fall through to below to correctly record totalWritten
1469 totalWritten += bytes;
1471 if (bytes == (ssize_t)len) {
1472 // The full iovec is written.
1473 (*countWritten) += 1 + buffersStolen;
1477 bytes += offset; // adjust bytes to account for all of v
1478 while (bytes >= (ssize_t)v->iov_len) {
1479 // We combined this buf with part or all of the next one, and
1480 // we managed to write all of this buf but not all of the bytes
1481 // from the next one that we'd hoped to write.
1482 bytes -= v->iov_len;
1486 *partialWritten = bytes;
1487 return totalWritten;
1491 return totalWritten;
1495 //#ifdef SSL_MODE_WRITE_IOVEC
1496 ssize_t AsyncSSLSocket::performWriteIovec(const iovec* vec,
1499 uint32_t* countWritten,
1500 uint32_t* partialWritten) {
1502 for (uint32_t j = 0; j < count; j++) {
1503 tot += vec[j].iov_len;
1506 ssize_t totalWritten = SSL_write_iovec(ssl_, vec, count);
1509 *partialWritten = 0;
1510 if (totalWritten <= 0) {
1511 return interpretSSLError(totalWritten, SSL_get_error(ssl_, totalWritten));
1513 ssize_t bytes = totalWritten, i = 0;
1514 while (i < count && bytes >= (ssize_t)vec[i].iov_len) {
1515 // we managed to write all of this buf
1516 bytes -= vec[i].iov_len;
1520 *partialWritten = bytes;
1522 VLOG(4) << "SSL_write_iovec() writes " << tot
1523 << ", returns " << totalWritten << " bytes"
1524 << ", max_send_fragment=" << ssl_->max_send_fragment
1525 << ", count=" << count << ", countWritten=" << *countWritten;
1527 return totalWritten;
1532 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1534 if (eor && SSL_get_wbio(ssl)->method == &eorAwareBioMethod) {
1535 if (appEorByteNo_) {
1536 // cannot track for more than one app byte EOR
1537 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1539 appEorByteNo_ = appBytesWritten_ + n;
1542 // 1. It is fine to keep updating minEorRawByteNo_.
1543 // 2. It is _min_ in the sense that SSL record will add some overhead.
1544 minEorRawByteNo_ = getRawBytesWritten() + n;
1547 n = sslWriteImpl(ssl, buf, n);
1549 appBytesWritten_ += n;
1550 if (appEorByteNo_) {
1551 if (getRawBytesWritten() >= minEorRawByteNo_) {
1552 minEorRawByteNo_ = 0;
1554 if(appBytesWritten_ == appEorByteNo_) {
1557 CHECK(appBytesWritten_ < appEorByteNo_);
1564 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int /* ret */) {
1565 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1566 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1567 sslSocket->renegotiateAttempted_ = true;
1571 int AsyncSSLSocket::eorAwareBioWrite(BIO *b, const char *in, int inl) {
1576 AsyncSSLSocket *tsslSock;
1578 iov.iov_base = const_cast<char *>(in);
1580 memset(&msg, 0, sizeof(msg));
1585 reinterpret_cast<AsyncSSLSocket*>(BIO_get_app_data(b));
1587 tsslSock->minEorRawByteNo_ &&
1588 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1593 ret = sendmsg(b->num, &msg, flags);
1594 BIO_clear_retry_flags(b);
1596 if (BIO_sock_should_retry(ret))
1597 BIO_set_retry_write(b);
1602 int AsyncSSLSocket::sslVerifyCallback(int preverifyOk,
1603 X509_STORE_CTX* x509Ctx) {
1604 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1605 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1606 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1608 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1609 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1610 return (self->handshakeCallback_) ?
1611 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1615 void AsyncSSLSocket::enableClientHelloParsing() {
1616 parseClientHello_ = true;
1617 clientHelloInfo_.reset(new ClientHelloInfo());
1620 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1621 SSL_set_msg_callback(ssl, nullptr);
1622 SSL_set_msg_callback_arg(ssl, nullptr);
1623 clientHelloInfo_->clientHelloBuf_.clear();
1626 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1633 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1635 sock->resetClientHelloParsing(ssl);
1638 if (contentType != SSL3_RT_HANDSHAKE) {
1645 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1646 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1648 Cursor cursor(clientHelloBuf.front());
1649 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1650 sock->resetClientHelloParsing(ssl);
1654 if (cursor.totalLength() < 3) {
1655 clientHelloBuf.trimEnd(len);
1656 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1660 uint32_t messageLength = cursor.read<uint8_t>();
1661 messageLength <<= 8;
1662 messageLength |= cursor.read<uint8_t>();
1663 messageLength <<= 8;
1664 messageLength |= cursor.read<uint8_t>();
1665 if (cursor.totalLength() < messageLength) {
1666 clientHelloBuf.trimEnd(len);
1667 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1671 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1672 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1674 cursor.skip(4); // gmt_unix_time
1675 cursor.skip(28); // random_bytes
1677 cursor.skip(cursor.read<uint8_t>()); // session_id
1679 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1680 for (int i = 0; i < cipherSuitesLength; i += 2) {
1681 sock->clientHelloInfo_->
1682 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1685 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1686 for (int i = 0; i < compressionMethodsLength; ++i) {
1687 sock->clientHelloInfo_->
1688 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1691 if (cursor.totalLength() > 0) {
1692 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1693 while (extensionsLength) {
1694 TLSExtension extensionType = static_cast<TLSExtension>(
1695 cursor.readBE<uint16_t>());
1696 sock->clientHelloInfo_->
1697 clientHelloExtensions_.push_back(extensionType);
1698 extensionsLength -= 2;
1699 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1700 extensionsLength -= 2;
1702 if (extensionType == TLSExtension::SIGNATURE_ALGORITHMS) {
1704 extensionDataLength -= 2;
1705 while (extensionDataLength) {
1706 HashAlgorithm hashAlg = static_cast<HashAlgorithm>(
1707 cursor.readBE<uint8_t>());
1708 SignatureAlgorithm sigAlg = static_cast<SignatureAlgorithm>(
1709 cursor.readBE<uint8_t>());
1710 extensionDataLength -= 2;
1711 sock->clientHelloInfo_->
1712 clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1715 cursor.skip(extensionDataLength);
1716 extensionsLength -= extensionDataLength;
1720 } catch (std::out_of_range& e) {
1721 // we'll use what we found and cleanup below.
1722 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1723 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1726 sock->resetClientHelloParsing(ssl);