2 * Copyright 2014-present 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>
20 #include <folly/portability/Sockets.h>
22 #include <boost/noncopyable.hpp>
25 #include <sys/types.h>
29 #include <folly/Format.h>
30 #include <folly/SocketAddress.h>
31 #include <folly/SpinLock.h>
32 #include <folly/io/Cursor.h>
33 #include <folly/io/IOBuf.h>
34 #include <folly/lang/Bits.h>
35 #include <folly/portability/OpenSSL.h>
37 using folly::SocketAddress;
38 using folly::SSLContext;
40 using std::shared_ptr;
44 using folly::SpinLock;
45 using folly::SpinLockGuard;
46 using folly::io::Cursor;
47 using std::unique_ptr;
51 using folly::AsyncSocket;
52 using folly::AsyncSocketException;
53 using folly::AsyncSSLSocket;
54 using folly::Optional;
55 using folly::SSLContext;
56 // For OpenSSL portability API
57 using namespace folly::ssl;
58 using folly::ssl::OpenSSLUtils;
61 // We have one single dummy SSL context so that we can implement attach
62 // and detach methods in a thread safe fashion without modifying opnessl.
63 static SSLContext *dummyCtx = nullptr;
64 static SpinLock dummyCtxLock;
66 // If given min write size is less than this, buffer will be allocated on
67 // stack, otherwise it is allocated on heap
68 const size_t MAX_STACK_BUF_SIZE = 2048;
70 // This converts "illegal" shutdowns into ZERO_RETURN
71 inline bool zero_return(int error, int rc) {
72 return (error == SSL_ERROR_ZERO_RETURN || (rc == 0 && errno == 0));
75 class AsyncSSLSocketConnector: public AsyncSocket::ConnectCallback,
76 public AsyncSSLSocket::HandshakeCB {
79 AsyncSSLSocket *sslSocket_;
80 AsyncSSLSocket::ConnectCallback *callback_;
85 ~AsyncSSLSocketConnector() override {}
88 AsyncSSLSocketConnector(AsyncSSLSocket *sslSocket,
89 AsyncSocket::ConnectCallback *callback,
91 sslSocket_(sslSocket),
94 startTime_(std::chrono::duration_cast<std::chrono::milliseconds>(
95 std::chrono::steady_clock::now().time_since_epoch()).count()) {
98 void connectSuccess() noexcept override {
99 VLOG(7) << "client socket connected";
101 int64_t timeoutLeft = 0;
103 auto curTime = std::chrono::duration_cast<std::chrono::milliseconds>(
104 std::chrono::steady_clock::now().time_since_epoch()).count();
106 timeoutLeft = timeout_ - (curTime - startTime_);
107 if (timeoutLeft <= 0) {
108 AsyncSocketException ex(
109 AsyncSocketException::TIMED_OUT,
110 folly::sformat("SSL connect timed out after {}ms", timeout_));
116 sslSocket_->sslConn(this, std::chrono::milliseconds(timeoutLeft));
119 void connectErr(const AsyncSocketException& ex) noexcept override {
120 VLOG(1) << "TCP connect failed: " << ex.what();
125 void handshakeSuc(AsyncSSLSocket* /* sock */) noexcept override {
126 VLOG(7) << "client handshake success";
128 callback_->connectSuccess();
133 void handshakeErr(AsyncSSLSocket* /* socket */,
134 const AsyncSocketException& ex) noexcept override {
135 VLOG(1) << "client handshakeErr: " << ex.what();
140 void fail(const AsyncSocketException &ex) {
141 // fail is a noop if called twice
143 AsyncSSLSocket::ConnectCallback *cb = callback_;
147 sslSocket_->closeNow();
148 // closeNow can call handshakeErr if it hasn't been called already.
149 // So this may have been deleted, no member variable access beyond this
151 // Note that closeNow may invoke writeError callbacks if the socket had
152 // write data pending connection completion.
157 void setup_SSL_CTX(SSL_CTX *ctx) {
158 #ifdef SSL_MODE_RELEASE_BUFFERS
159 SSL_CTX_set_mode(ctx,
160 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
161 SSL_MODE_ENABLE_PARTIAL_WRITE
162 | SSL_MODE_RELEASE_BUFFERS
165 SSL_CTX_set_mode(ctx,
166 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
167 SSL_MODE_ENABLE_PARTIAL_WRITE
170 // SSL_CTX_set_mode is a Macro
171 #ifdef SSL_MODE_WRITE_IOVEC
172 SSL_CTX_set_mode(ctx,
173 SSL_CTX_get_mode(ctx)
174 | SSL_MODE_WRITE_IOVEC);
179 // Note: This is a Leaky Meyer's Singleton. The reason we can't use a non-leaky
180 // thing is because we will be setting this BIO_METHOD* inside BIOs owned by
181 // various SSL objects which may get callbacks even during teardown. We may
182 // eventually try to fix this
183 static BIO_METHOD* getSSLBioMethod() {
184 static auto const instance = OpenSSLUtils::newSocketBioMethod().release();
188 void* initsslBioMethod() {
189 auto sslBioMethod = getSSLBioMethod();
190 // override the bwrite method for MSG_EOR support
191 OpenSSLUtils::setCustomBioWriteMethod(sslBioMethod, AsyncSSLSocket::bioWrite);
192 OpenSSLUtils::setCustomBioReadMethod(sslBioMethod, AsyncSSLSocket::bioRead);
194 // Note that the sslBioMethod.type and sslBioMethod.name are not
195 // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
196 // then have specific handlings. The sslWriteBioWrite should be compatible
197 // with the one in openssl.
199 // Return something here to enable AsyncSSLSocket to call this method using
200 // a function-scoped static.
209 * Create a client AsyncSSLSocket
211 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
212 EventBase* evb, bool deferSecurityNegotiation) :
215 handshakeTimeout_(this, evb),
216 connectionTimeout_(this, evb) {
218 if (deferSecurityNegotiation) {
219 sslState_ = STATE_UNENCRYPTED;
224 * Create a server/client AsyncSSLSocket
226 AsyncSSLSocket::AsyncSSLSocket(
227 const shared_ptr<SSLContext>& ctx,
231 bool deferSecurityNegotiation)
232 : AsyncSocket(evb, fd),
235 handshakeTimeout_(this, evb),
236 connectionTimeout_(this, evb) {
237 noTransparentTls_ = true;
240 SSL_CTX_set_info_callback(
241 ctx_->getSSLCtx(), AsyncSSLSocket::sslInfoCallback);
243 if (deferSecurityNegotiation) {
244 sslState_ = STATE_UNENCRYPTED;
248 AsyncSSLSocket::AsyncSSLSocket(
249 const shared_ptr<SSLContext>& ctx,
250 AsyncSocket::UniquePtr oldAsyncSocket,
252 bool deferSecurityNegotiation)
253 : AsyncSocket(std::move(oldAsyncSocket)),
256 handshakeTimeout_(this, AsyncSocket::getEventBase()),
257 connectionTimeout_(this, AsyncSocket::getEventBase()) {
258 noTransparentTls_ = true;
261 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
262 AsyncSSLSocket::sslInfoCallback);
264 if (deferSecurityNegotiation) {
265 sslState_ = STATE_UNENCRYPTED;
269 #if FOLLY_OPENSSL_HAS_SNI
271 * Create a client AsyncSSLSocket and allow tlsext_hostname
272 * to be sent in Client Hello.
274 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
276 const std::string& serverName,
277 bool deferSecurityNegotiation) :
278 AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
279 tlsextHostname_ = serverName;
283 * Create a client AsyncSSLSocket from an already connected fd
284 * and allow tlsext_hostname to be sent in Client Hello.
286 AsyncSSLSocket::AsyncSSLSocket(
287 const shared_ptr<SSLContext>& ctx,
290 const std::string& serverName,
291 bool deferSecurityNegotiation)
292 : AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
293 tlsextHostname_ = serverName;
295 #endif // FOLLY_OPENSSL_HAS_SNI
297 AsyncSSLSocket::~AsyncSSLSocket() {
298 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
299 << ", evb=" << eventBase_ << ", fd=" << fd_
300 << ", state=" << int(state_) << ", sslState="
301 << sslState_ << ", events=" << eventFlags_ << ")";
304 void AsyncSSLSocket::init() {
305 // Do this here to ensure we initialize this once before any use of
306 // AsyncSSLSocket instances and not as part of library load.
307 static const auto sslBioMethodInitializer = initsslBioMethod();
308 (void)sslBioMethodInitializer;
310 setup_SSL_CTX(ctx_->getSSLCtx());
313 void AsyncSSLSocket::closeNow() {
314 // Close the SSL connection.
315 if (ssl_ != nullptr && fd_ != -1) {
316 int rc = SSL_shutdown(ssl_);
318 rc = SSL_shutdown(ssl_);
325 if (sslSession_ != nullptr) {
326 SSL_SESSION_free(sslSession_);
327 sslSession_ = nullptr;
330 sslState_ = STATE_CLOSED;
332 if (handshakeTimeout_.isScheduled()) {
333 handshakeTimeout_.cancelTimeout();
336 DestructorGuard dg(this);
339 AsyncSocketException(
340 AsyncSocketException::END_OF_FILE,
341 "SSL connection closed locally"));
343 if (ssl_ != nullptr) {
349 AsyncSocket::closeNow();
352 void AsyncSSLSocket::shutdownWrite() {
353 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
355 // (Performing a full shutdown here is more desirable than doing nothing at
356 // all. The purpose of shutdownWrite() is normally to notify the other end
357 // of the connection that no more data will be sent. If we do nothing, the
358 // other end will never know that no more data is coming, and this may result
359 // in protocol deadlock.)
363 void AsyncSSLSocket::shutdownWriteNow() {
367 bool AsyncSSLSocket::good() const {
368 return (AsyncSocket::good() &&
369 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
370 sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
373 // The TAsyncTransport definition of 'good' states that the transport is
374 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
375 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
376 // is connected but we haven't initiated the call to SSL_connect.
377 bool AsyncSSLSocket::connecting() const {
379 (AsyncSocket::connecting() ||
380 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
381 sslState_ == STATE_CONNECTING))));
384 std::string AsyncSSLSocket::getApplicationProtocol() noexcept {
385 const unsigned char* protoName = nullptr;
386 unsigned protoLength;
387 if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) {
388 return std::string(reinterpret_cast<const char*>(protoName), protoLength);
393 void AsyncSSLSocket::setEorTracking(bool track) {
394 if (isEorTrackingEnabled() != track) {
395 AsyncSocket::setEorTracking(track);
397 minEorRawByteNo_ = 0;
401 size_t AsyncSSLSocket::getRawBytesWritten() const {
402 // The bio(s) in the write path are in a chain
403 // each bio flushes to the next and finally written into the socket
404 // to get the rawBytesWritten on the socket,
405 // get the write bytes of the last bio
407 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
410 BIO* next = BIO_next(b);
411 while (next != nullptr) {
416 return BIO_number_written(b);
419 size_t AsyncSSLSocket::getRawBytesReceived() const {
421 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
425 return BIO_number_read(b);
429 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
430 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
431 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
432 << "events=" << eventFlags_ << ", server=" << short(server_)
433 << "): " << "sslAccept/Connect() called in invalid "
434 << "state, handshake callback " << handshakeCallback_
435 << ", new callback " << callback;
436 assert(!handshakeTimeout_.isScheduled());
437 sslState_ = STATE_ERROR;
439 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
440 "sslAccept() called with socket in invalid state");
442 handshakeEndTime_ = std::chrono::steady_clock::now();
444 callback->handshakeErr(this, ex);
447 failHandshake(__func__, ex);
450 void AsyncSSLSocket::sslAccept(
451 HandshakeCB* callback,
452 std::chrono::milliseconds timeout,
453 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
454 DestructorGuard dg(this);
455 eventBase_->dcheckIsInEventBaseThread();
456 verifyPeer_ = verifyPeer;
458 // Make sure we're in the uninitialized state
460 (sslState_ != STATE_UNINIT && sslState_ != STATE_UNENCRYPTED) ||
461 handshakeCallback_ != nullptr) {
462 return invalidState(callback);
465 // Cache local and remote socket addresses to keep them available
466 // after socket file descriptor is closed.
467 if (cacheAddrOnFailure_) {
471 handshakeStartTime_ = std::chrono::steady_clock::now();
472 // Make end time at least >= start time.
473 handshakeEndTime_ = handshakeStartTime_;
475 sslState_ = STATE_ACCEPTING;
476 handshakeCallback_ = callback;
478 if (timeout > std::chrono::milliseconds::zero()) {
479 handshakeTimeout_.scheduleTimeout(timeout);
482 /* register for a read operation (waiting for CLIENT HELLO) */
483 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
485 checkForImmediateRead();
488 void AsyncSSLSocket::attachSSLContext(
489 const std::shared_ptr<SSLContext>& ctx) {
491 // Check to ensure we are in client mode. Changing a server's ssl
492 // context doesn't make sense since clients of that server would likely
493 // become confused when the server's context changes.
497 DCHECK(ctx->getSSLCtx());
500 // It's possible this could be attached before ssl_ is set up
505 // In order to call attachSSLContext, detachSSLContext must have been
506 // previously called.
507 // We need to update the initial_ctx if necessary
508 // The 'initial_ctx' inside an SSL* points to the context that it was created
509 // with, which is also where session callbacks and servername callbacks
511 // When we switch to a different SSL_CTX, we want to update the initial_ctx as
512 // well so that any callbacks don't go to a different object
513 // NOTE: this will only work if we have access to ssl_ internals, so it may
515 // OpenSSL version >= 1.1.0
516 auto sslCtx = ctx->getSSLCtx();
517 OpenSSLUtils::setSSLInitialCtx(ssl_, sslCtx);
518 // Detach sets the socket's context to the dummy context. Thus we must acquire
520 SpinLockGuard guard(dummyCtxLock);
521 SSL_set_SSL_CTX(ssl_, sslCtx);
524 void AsyncSSLSocket::detachSSLContext() {
527 // It's possible for this to be called before ssl_ has been
532 // The 'initial_ctx' inside an SSL* points to the context that it was created
533 // with, which is also where session callbacks and servername callbacks
535 // Detach the initial_ctx as well. It will be reattached in attachSSLContext
536 // it is used for session info.
537 // NOTE: this will only work if we have access to ssl_ internals, so it may
539 // OpenSSL version >= 1.1.0
540 SSL_CTX* initialCtx = OpenSSLUtils::getSSLInitialCtx(ssl_);
542 SSL_CTX_free(initialCtx);
543 OpenSSLUtils::setSSLInitialCtx(ssl_, nullptr);
546 SpinLockGuard guard(dummyCtxLock);
547 if (nullptr == dummyCtx) {
548 // We need to lazily initialize the dummy context so we don't
549 // accidentally override any programmatic settings to openssl
550 dummyCtx = new SSLContext;
552 // We must remove this socket's references to its context right now
553 // since this socket could get passed to any thread. If the context has
554 // had its locking disabled, just doing a set in attachSSLContext()
555 // would not be thread safe.
556 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
559 #if FOLLY_OPENSSL_HAS_SNI
560 void AsyncSSLSocket::switchServerSSLContext(
561 const std::shared_ptr<SSLContext>& handshakeCtx) {
563 if (sslState_ != STATE_ACCEPTING) {
564 // We log it here and allow the switch.
565 // It should not affect our re-negotiation support (which
566 // is not supported now).
567 VLOG(6) << "fd=" << getFd()
568 << " renegotation detected when switching SSL_CTX";
571 setup_SSL_CTX(handshakeCtx->getSSLCtx());
572 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
573 AsyncSSLSocket::sslInfoCallback);
574 handshakeCtx_ = handshakeCtx;
575 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
578 bool AsyncSSLSocket::isServerNameMatch() const {
585 SSL_SESSION *ss = SSL_get_session(ssl_);
590 auto tlsextHostname = SSL_SESSION_get0_hostname(ss);
591 return (tlsextHostname && !tlsextHostname_.compare(tlsextHostname));
594 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
595 tlsextHostname_ = std::move(serverName);
598 #endif // FOLLY_OPENSSL_HAS_SNI
600 void AsyncSSLSocket::timeoutExpired(
601 std::chrono::milliseconds timeout) noexcept {
602 if (state_ == StateEnum::ESTABLISHED &&
603 (sslState_ == STATE_CACHE_LOOKUP || sslState_ == STATE_ASYNC_PENDING)) {
604 sslState_ = STATE_ERROR;
605 // We are expecting a callback in restartSSLAccept. The cache lookup
606 // and rsa-call necessarily have pointers to this ssl socket, so delay
607 // the cleanup until he calls us back.
608 } else if (state_ == StateEnum::CONNECTING) {
609 assert(sslState_ == STATE_CONNECTING);
610 DestructorGuard dg(this);
611 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
612 "Fallback connect timed out during TFO");
613 failHandshake(__func__, ex);
615 assert(state_ == StateEnum::ESTABLISHED &&
616 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
617 DestructorGuard dg(this);
618 AsyncSocketException ex(
619 AsyncSocketException::TIMED_OUT,
621 "SSL {} timed out after {}ms",
622 (sslState_ == STATE_CONNECTING) ? "connect" : "accept",
624 failHandshake(__func__, ex);
628 int AsyncSSLSocket::getSSLExDataIndex() {
629 static auto index = SSL_get_ex_new_index(
630 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
634 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
635 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
636 getSSLExDataIndex()));
639 void AsyncSSLSocket::failHandshake(const char* /* fn */,
640 const AsyncSocketException& ex) {
642 if (handshakeTimeout_.isScheduled()) {
643 handshakeTimeout_.cancelTimeout();
645 invokeHandshakeErr(ex);
649 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
650 handshakeEndTime_ = std::chrono::steady_clock::now();
651 if (handshakeCallback_ != nullptr) {
652 HandshakeCB* callback = handshakeCallback_;
653 handshakeCallback_ = nullptr;
654 callback->handshakeErr(this, ex);
658 void AsyncSSLSocket::invokeHandshakeCB() {
659 handshakeEndTime_ = std::chrono::steady_clock::now();
660 if (handshakeTimeout_.isScheduled()) {
661 handshakeTimeout_.cancelTimeout();
663 if (handshakeCallback_) {
664 HandshakeCB* callback = handshakeCallback_;
665 handshakeCallback_ = nullptr;
666 callback->handshakeSuc(this);
670 void AsyncSSLSocket::connect(
671 ConnectCallback* callback,
672 const folly::SocketAddress& address,
674 const OptionMap& options,
675 const folly::SocketAddress& bindAddr) noexcept {
676 auto timeoutChrono = std::chrono::milliseconds(timeout);
677 connect(callback, address, timeoutChrono, timeoutChrono, options, bindAddr);
680 void AsyncSSLSocket::connect(
681 ConnectCallback* callback,
682 const folly::SocketAddress& address,
683 std::chrono::milliseconds connectTimeout,
684 std::chrono::milliseconds totalConnectTimeout,
685 const OptionMap& options,
686 const folly::SocketAddress& bindAddr) noexcept {
688 assert(state_ == StateEnum::UNINIT);
689 assert(sslState_ == STATE_UNINIT || sslState_ == STATE_UNENCRYPTED);
690 noTransparentTls_ = true;
691 totalConnectTimeout_ = totalConnectTimeout;
692 if (sslState_ != STATE_UNENCRYPTED) {
693 callback = new AsyncSSLSocketConnector(
694 this, callback, int(totalConnectTimeout.count()));
696 AsyncSocket::connect(
697 callback, address, int(connectTimeout.count()), options, bindAddr);
700 bool AsyncSSLSocket::needsPeerVerification() const {
701 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
702 return ctx_->needsPeerVerification();
705 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
706 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
709 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
710 // apply the settings specified in verifyPeer_
711 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
712 if(ctx_->needsPeerVerification()) {
713 SSL_set_verify(ssl, ctx_->getVerificationMode(),
714 AsyncSSLSocket::sslVerifyCallback);
717 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
718 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
719 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
720 AsyncSSLSocket::sslVerifyCallback);
725 bool AsyncSSLSocket::setupSSLBio() {
726 auto sslBio = BIO_new(getSSLBioMethod());
732 OpenSSLUtils::setBioAppData(sslBio, this);
733 OpenSSLUtils::setBioFd(sslBio, fd_, BIO_NOCLOSE);
734 SSL_set_bio(ssl_, sslBio, sslBio);
738 void AsyncSSLSocket::sslConn(
739 HandshakeCB* callback,
740 std::chrono::milliseconds timeout,
741 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
742 DestructorGuard dg(this);
743 eventBase_->dcheckIsInEventBaseThread();
745 // Cache local and remote socket addresses to keep them available
746 // after socket file descriptor is closed.
747 if (cacheAddrOnFailure_) {
751 verifyPeer_ = verifyPeer;
753 // Make sure we're in the uninitialized state
754 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
755 STATE_UNENCRYPTED) ||
756 handshakeCallback_ != nullptr) {
757 return invalidState(callback);
760 sslState_ = STATE_CONNECTING;
761 handshakeCallback_ = callback;
764 ssl_ = ctx_->createSSL();
765 } catch (std::exception &e) {
766 sslState_ = STATE_ERROR;
767 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
768 "error calling SSLContext::createSSL()");
769 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
770 << fd_ << "): " << e.what();
771 return failHandshake(__func__, ex);
774 if (!setupSSLBio()) {
775 sslState_ = STATE_ERROR;
776 AsyncSocketException ex(
777 AsyncSocketException::INTERNAL_ERROR, "error creating SSL bio");
778 return failHandshake(__func__, ex);
781 applyVerificationOptions(ssl_);
783 if (sslSession_ != nullptr) {
784 sessionResumptionAttempted_ = true;
785 SSL_set_session(ssl_, sslSession_);
786 SSL_SESSION_free(sslSession_);
787 sslSession_ = nullptr;
789 #if FOLLY_OPENSSL_HAS_SNI
790 if (tlsextHostname_.size()) {
791 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
795 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
797 handshakeConnectTimeout_ = timeout;
801 // This could be called multiple times, during normal ssl connections
802 // and after TFO fallback.
803 void AsyncSSLSocket::startSSLConnect() {
804 handshakeStartTime_ = std::chrono::steady_clock::now();
805 // Make end time at least >= start time.
806 handshakeEndTime_ = handshakeStartTime_;
807 if (handshakeConnectTimeout_ > std::chrono::milliseconds::zero()) {
808 handshakeTimeout_.scheduleTimeout(handshakeConnectTimeout_);
813 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
814 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
815 return SSL_get1_session(ssl_);
821 const SSL* AsyncSSLSocket::getSSL() const {
825 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
826 sslSession_ = session;
827 if (!takeOwnership && session != nullptr) {
828 // Increment the reference count
829 // This API exists in BoringSSL and OpenSSL 1.1.0
830 SSL_SESSION_up_ref(session);
834 void AsyncSSLSocket::getSelectedNextProtocol(
835 const unsigned char** protoName,
837 SSLContext::NextProtocolType* protoType) const {
838 if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
839 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
840 "NPN not supported");
844 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
845 const unsigned char** protoName,
847 SSLContext::NextProtocolType* protoType) const {
848 *protoName = nullptr;
850 #if FOLLY_OPENSSL_HAS_ALPN
851 SSL_get0_alpn_selected(ssl_, protoName, protoLen);
854 *protoType = SSLContext::NextProtocolType::ALPN;
859 #ifdef OPENSSL_NPN_NEGOTIATED
860 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
862 *protoType = SSLContext::NextProtocolType::NPN;
871 bool AsyncSSLSocket::getSSLSessionReused() const {
872 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
873 return SSL_session_reused(ssl_);
878 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
879 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
883 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
884 if (ssl == nullptr) {
887 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
888 return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
894 const char *AsyncSSLSocket::getSSLServerName() const {
895 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
896 return getSSLServerNameFromSSL(ssl_);
898 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
899 "SNI not supported");
903 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
904 return getSSLServerNameFromSSL(ssl_);
907 int AsyncSSLSocket::getSSLVersion() const {
908 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
911 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
912 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
914 int nid = X509_get_signature_nid(cert);
915 return OBJ_nid2ln(nid);
920 int AsyncSSLSocket::getSSLCertSize() const {
922 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
924 EVP_PKEY *key = X509_get_pubkey(cert);
925 certSize = EVP_PKEY_bits(key);
931 const X509* AsyncSSLSocket::getSelfCert() const {
932 return (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
935 bool AsyncSSLSocket::willBlock(int ret,
937 unsigned long* errErrorOut) noexcept {
939 int error = *sslErrorOut = SSL_get_error(ssl_, ret);
940 if (error == SSL_ERROR_WANT_READ) {
941 // Register for read event if not already.
942 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
944 } else if (error == SSL_ERROR_WANT_WRITE) {
945 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
946 << ", state=" << int(state_) << ", sslState="
947 << sslState_ << ", events=" << eventFlags_ << "): "
948 << "SSL_ERROR_WANT_WRITE";
949 // Register for write event if not already.
950 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
952 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
953 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
954 // We will block but we can't register our own socket. The callback that
955 // triggered this code will re-call handleAccept at the appropriate time.
957 // We can only get here if the linked libssl.so has support for this feature
958 // as well, otherwise SSL_get_error cannot return our error code.
959 sslState_ = STATE_CACHE_LOOKUP;
961 // Unregister for all events while blocked here
962 updateEventRegistration(EventHandler::NONE,
963 EventHandler::READ | EventHandler::WRITE);
965 // The timeout (if set) keeps running here
969 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
970 || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
972 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
973 || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
976 // Our custom openssl function has kicked off an async request to do
977 // rsa/ecdsa private key operation. When that call returns, a callback will
978 // be invoked that will re-call handleAccept.
979 sslState_ = STATE_ASYNC_PENDING;
981 // Unregister for all events while blocked here
982 updateEventRegistration(
984 EventHandler::READ | EventHandler::WRITE
987 // The timeout (if set) keeps running here
990 unsigned long lastError = *errErrorOut = ERR_get_error();
991 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
992 << "state=" << state_ << ", "
993 << "sslState=" << sslState_ << ", "
994 << "events=" << std::hex << eventFlags_ << "): "
995 << "SSL error: " << error << ", "
996 << "errno: " << errno << ", "
997 << "ret: " << ret << ", "
998 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
999 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
1000 << "func: " << ERR_func_error_string(lastError) << ", "
1001 << "reason: " << ERR_reason_error_string(lastError);
1006 void AsyncSSLSocket::checkForImmediateRead() noexcept {
1007 // openssl may have buffered data that it read from the socket already.
1008 // In this case we have to process it immediately, rather than waiting for
1009 // the socket to become readable again.
1010 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
1011 AsyncSocket::handleRead();
1013 AsyncSocket::checkForImmediateRead();
1018 AsyncSSLSocket::restartSSLAccept()
1020 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this
1021 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1022 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1023 DestructorGuard dg(this);
1025 sslState_ == STATE_CACHE_LOOKUP ||
1026 sslState_ == STATE_ASYNC_PENDING ||
1027 sslState_ == STATE_ERROR ||
1028 sslState_ == STATE_CLOSED);
1029 if (sslState_ == STATE_CLOSED) {
1030 // I sure hope whoever closed this socket didn't delete it already,
1031 // but this is not strictly speaking an error
1034 if (sslState_ == STATE_ERROR) {
1035 // go straight to fail if timeout expired during lookup
1036 AsyncSocketException ex(
1037 AsyncSocketException::TIMED_OUT, "SSL accept timed out");
1038 failHandshake(__func__, ex);
1041 sslState_ = STATE_ACCEPTING;
1042 this->handleAccept();
1046 AsyncSSLSocket::handleAccept() noexcept {
1047 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
1048 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1049 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1051 assert(state_ == StateEnum::ESTABLISHED &&
1052 sslState_ == STATE_ACCEPTING);
1054 /* lazily create the SSL structure */
1056 ssl_ = ctx_->createSSL();
1057 } catch (std::exception &e) {
1058 sslState_ = STATE_ERROR;
1059 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1060 "error calling SSLContext::createSSL()");
1061 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
1062 << ", fd=" << fd_ << "): " << e.what();
1063 return failHandshake(__func__, ex);
1066 if (!setupSSLBio()) {
1067 sslState_ = STATE_ERROR;
1068 AsyncSocketException ex(
1069 AsyncSocketException::INTERNAL_ERROR, "error creating write bio");
1070 return failHandshake(__func__, ex);
1073 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
1075 applyVerificationOptions(ssl_);
1078 if (server_ && parseClientHello_) {
1079 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1080 SSL_set_msg_callback_arg(ssl_, this);
1083 int ret = SSL_accept(ssl_);
1086 unsigned long errError;
1087 int errnoCopy = errno;
1088 if (willBlock(ret, &sslError, &errError)) {
1091 sslState_ = STATE_ERROR;
1092 SSLException ex(sslError, errError, ret, errnoCopy);
1093 return failHandshake(__func__, ex);
1097 handshakeComplete_ = true;
1098 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1100 // Move into STATE_ESTABLISHED in the normal case that we are in
1102 sslState_ = STATE_ESTABLISHED;
1104 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1105 << " successfully accepted; state=" << int(state_)
1106 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1108 // Remember the EventBase we are attached to, before we start invoking any
1109 // callbacks (since the callbacks may call detachEventBase()).
1110 EventBase* originalEventBase = eventBase_;
1112 // Call the accept callback.
1113 invokeHandshakeCB();
1115 // Note that the accept callback may have changed our state.
1116 // (set or unset the read callback, called write(), closed the socket, etc.)
1117 // The following code needs to handle these situations correctly.
1119 // If the socket has been closed, readCallback_ and writeReqHead_ will
1120 // always be nullptr, so that will prevent us from trying to read or write.
1122 // The main thing to check for is if eventBase_ is still originalEventBase.
1123 // If not, we have been detached from this event base, so we shouldn't
1124 // perform any more operations.
1125 if (eventBase_ != originalEventBase) {
1129 AsyncSocket::handleInitialReadWrite();
1133 AsyncSSLSocket::handleConnect() noexcept {
1134 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1135 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1136 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1138 if (state_ < StateEnum::ESTABLISHED) {
1139 return AsyncSocket::handleConnect();
1143 (state_ == StateEnum::FAST_OPEN || state_ == StateEnum::ESTABLISHED) &&
1144 sslState_ == STATE_CONNECTING);
1147 auto originalState = state_;
1148 int ret = SSL_connect(ssl_);
1151 unsigned long errError;
1152 int errnoCopy = errno;
1153 if (willBlock(ret, &sslError, &errError)) {
1154 // We fell back to connecting state due to TFO
1155 if (state_ == StateEnum::CONNECTING) {
1156 DCHECK_EQ(StateEnum::FAST_OPEN, originalState);
1157 if (handshakeTimeout_.isScheduled()) {
1158 handshakeTimeout_.cancelTimeout();
1163 sslState_ = STATE_ERROR;
1164 SSLException ex(sslError, errError, ret, errnoCopy);
1165 return failHandshake(__func__, ex);
1169 handshakeComplete_ = true;
1170 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1172 // Move into STATE_ESTABLISHED in the normal case that we are in
1173 // STATE_CONNECTING.
1174 sslState_ = STATE_ESTABLISHED;
1176 VLOG(3) << "AsyncSSLSocket " << this << ": "
1177 << "fd " << fd_ << " successfully connected; "
1178 << "state=" << int(state_) << ", sslState=" << sslState_
1179 << ", events=" << eventFlags_;
1181 // Remember the EventBase we are attached to, before we start invoking any
1182 // callbacks (since the callbacks may call detachEventBase()).
1183 EventBase* originalEventBase = eventBase_;
1185 // Call the handshake callback.
1186 invokeHandshakeCB();
1188 // Note that the connect callback may have changed our state.
1189 // (set or unset the read callback, called write(), closed the socket, etc.)
1190 // The following code needs to handle these situations correctly.
1192 // If the socket has been closed, readCallback_ and writeReqHead_ will
1193 // always be nullptr, so that will prevent us from trying to read or write.
1195 // The main thing to check for is if eventBase_ is still originalEventBase.
1196 // If not, we have been detached from this event base, so we shouldn't
1197 // perform any more operations.
1198 if (eventBase_ != originalEventBase) {
1202 AsyncSocket::handleInitialReadWrite();
1205 void AsyncSSLSocket::invokeConnectErr(const AsyncSocketException& ex) {
1206 connectionTimeout_.cancelTimeout();
1207 AsyncSocket::invokeConnectErr(ex);
1208 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1209 if (handshakeTimeout_.isScheduled()) {
1210 handshakeTimeout_.cancelTimeout();
1212 // If we fell back to connecting state during TFO and the connection
1213 // failed, it would be an SSL failure as well.
1214 invokeHandshakeErr(ex);
1218 void AsyncSSLSocket::invokeConnectSuccess() {
1219 connectionTimeout_.cancelTimeout();
1220 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1221 assert(tfoAttempted_);
1222 // If we failed TFO, we'd fall back to trying to connect the socket,
1223 // to setup things like timeouts.
1226 // still invoke the base class since it re-sets the connect time.
1227 AsyncSocket::invokeConnectSuccess();
1230 void AsyncSSLSocket::scheduleConnectTimeout() {
1231 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1232 // We fell back from TFO, and need to set the timeouts.
1233 // We will not have a connect callback in this case, thus if the timer
1234 // expires we would have no-one to notify.
1235 // Thus we should reset even the connect timers to point to the handshake
1237 assert(connectCallback_ == nullptr);
1238 // We use a different connect timeout here than the handshake timeout, so
1239 // that we can disambiguate the 2 timers.
1240 if (connectTimeout_.count() > 0) {
1241 if (!connectionTimeout_.scheduleTimeout(connectTimeout_)) {
1242 throw AsyncSocketException(
1243 AsyncSocketException::INTERNAL_ERROR,
1244 withAddr("failed to schedule AsyncSSLSocket connect timeout"));
1249 AsyncSocket::scheduleConnectTimeout();
1252 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1253 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1254 // turn on the buffer movable in openssl
1255 if (bufferMovableEnabled_ && ssl_ != nullptr && !isBufferMovable_ &&
1256 callback != nullptr && callback->isBufferMovable()) {
1257 SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1258 isBufferMovable_ = true;
1262 AsyncSocket::setReadCB(callback);
1265 void AsyncSSLSocket::setBufferMovableEnabled(bool enabled) {
1266 bufferMovableEnabled_ = enabled;
1269 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1270 CHECK(readCallback_);
1271 if (isBufferMovable_) {
1275 // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1276 readCallback_->getReadBuffer(buf, buflen);
1281 AsyncSSLSocket::handleRead() noexcept {
1282 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1283 << ", state=" << int(state_) << ", "
1284 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1285 if (state_ < StateEnum::ESTABLISHED) {
1286 return AsyncSocket::handleRead();
1290 if (sslState_ == STATE_ACCEPTING) {
1295 else if (sslState_ == STATE_CONNECTING) {
1302 AsyncSocket::handleRead();
1305 AsyncSocket::ReadResult
1306 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1307 VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf
1308 << ", buflen=" << *buflen;
1310 if (sslState_ == STATE_UNENCRYPTED) {
1311 return AsyncSocket::performRead(buf, buflen, offset);
1315 if (!isBufferMovable_) {
1316 bytes = SSL_read(ssl_, *buf, int(*buflen));
1318 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1320 bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1324 if (server_ && renegotiateAttempted_) {
1325 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1326 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1327 << "): client intitiated SSL renegotiation not permitted";
1330 std::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION));
1333 int error = SSL_get_error(ssl_, bytes);
1334 if (error == SSL_ERROR_WANT_READ) {
1335 // The caller will register for read event if not already.
1336 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1337 return ReadResult(READ_BLOCKING);
1339 return ReadResult(READ_ERROR);
1341 } else if (error == SSL_ERROR_WANT_WRITE) {
1342 // TODO: Even though we are attempting to read data, SSL_read() may
1343 // need to write data if renegotiation is being performed. We currently
1344 // don't support this and just fail the read.
1345 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1346 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1347 << "): unsupported SSL renegotiation during read";
1350 std::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1352 if (zero_return(error, bytes)) {
1353 return ReadResult(bytes);
1355 auto errError = ERR_get_error();
1356 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1357 << "state=" << state_ << ", "
1358 << "sslState=" << sslState_ << ", "
1359 << "events=" << std::hex << eventFlags_ << "): "
1360 << "bytes: " << bytes << ", "
1361 << "error: " << error << ", "
1362 << "errno: " << errno << ", "
1363 << "func: " << ERR_func_error_string(errError) << ", "
1364 << "reason: " << ERR_reason_error_string(errError);
1367 std::make_unique<SSLException>(error, errError, bytes, errno));
1370 appBytesReceived_ += bytes;
1371 return ReadResult(bytes);
1375 void AsyncSSLSocket::handleWrite() noexcept {
1376 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1377 << ", state=" << int(state_) << ", "
1378 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1379 if (state_ < StateEnum::ESTABLISHED) {
1380 return AsyncSocket::handleWrite();
1383 if (sslState_ == STATE_ACCEPTING) {
1389 if (sslState_ == STATE_CONNECTING) {
1396 AsyncSocket::handleWrite();
1399 AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {
1400 if (error == SSL_ERROR_WANT_READ) {
1401 // Even though we are attempting to write data, SSL_write() may
1402 // need to read data if renegotiation is being performed. We currently
1403 // don't support this and just fail the write.
1404 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1405 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1407 << "unsupported SSL renegotiation during write";
1410 std::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1412 if (zero_return(error, rc)) {
1413 return WriteResult(0);
1415 auto errError = ERR_get_error();
1416 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1417 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1418 << "SSL error: " << error << ", errno: " << errno
1419 << ", func: " << ERR_func_error_string(errError)
1420 << ", reason: " << ERR_reason_error_string(errError);
1423 std::make_unique<SSLException>(error, errError, rc, errno));
1427 AsyncSocket::WriteResult AsyncSSLSocket::performWrite(
1431 uint32_t* countWritten,
1432 uint32_t* partialWritten) {
1433 if (sslState_ == STATE_UNENCRYPTED) {
1434 return AsyncSocket::performWrite(
1435 vec, count, flags, countWritten, partialWritten);
1437 if (sslState_ != STATE_ESTABLISHED) {
1438 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1439 << ", sslState=" << sslState_
1440 << ", events=" << eventFlags_ << "): "
1441 << "TODO: AsyncSSLSocket currently does not support calling "
1442 << "write() before the handshake has fully completed";
1444 WRITE_ERROR, std::make_unique<SSLException>(SSLError::EARLY_WRITE));
1447 // Declare a buffer used to hold small write requests. It could point to a
1448 // memory block either on stack or on heap. If it is on heap, we release it
1449 // manually when scope exits
1450 char* combinedBuf{nullptr};
1452 // Note, always keep this check consistent with what we do below
1453 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1454 delete[] combinedBuf;
1459 *partialWritten = 0;
1460 ssize_t totalWritten = 0;
1461 size_t bytesStolenFromNextBuffer = 0;
1462 for (uint32_t i = 0; i < count; i++) {
1463 const iovec* v = vec + i;
1464 size_t offset = bytesStolenFromNextBuffer;
1465 bytesStolenFromNextBuffer = 0;
1466 size_t len = v->iov_len - offset;
1472 buf = ((const char*)v->iov_base) + offset;
1475 uint32_t buffersStolen = 0;
1476 auto sslWriteBuf = buf;
1477 if ((len < minWriteSize_) && ((i + 1) < count)) {
1478 // Combine this buffer with part or all of the next buffers in
1479 // order to avoid really small-grained calls to SSL_write().
1480 // Each call to SSL_write() produces a separate record in
1481 // the egress SSL stream, and we've found that some low-end
1482 // mobile clients can't handle receiving an HTTP response
1483 // header and the first part of the response body in two
1484 // separate SSL records (even if those two records are in
1485 // the same TCP packet).
1487 if (combinedBuf == nullptr) {
1488 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1489 // Allocate the buffer on heap
1490 combinedBuf = new char[minWriteSize_];
1492 // Allocate the buffer on stack
1493 combinedBuf = (char*)alloca(minWriteSize_);
1496 assert(combinedBuf != nullptr);
1497 sslWriteBuf = combinedBuf;
1499 memcpy(combinedBuf, buf, len);
1501 // INVARIANT: i + buffersStolen == complete chunks serialized
1502 uint32_t nextIndex = i + buffersStolen + 1;
1503 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1504 minWriteSize_ - len);
1505 if (bytesStolenFromNextBuffer > 0) {
1506 assert(vec[nextIndex].iov_base != nullptr);
1509 vec[nextIndex].iov_base,
1510 bytesStolenFromNextBuffer);
1512 len += bytesStolenFromNextBuffer;
1513 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1514 // couldn't steal the whole buffer
1517 bytesStolenFromNextBuffer = 0;
1520 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1523 // Advance any empty buffers immediately after.
1524 if (bytesStolenFromNextBuffer == 0) {
1525 while ((i + buffersStolen + 1) < count &&
1526 vec[i + buffersStolen + 1].iov_len == 0) {
1532 isSet(flags, WriteFlags::CORK) || (i + buffersStolen + 1 < count);
1533 bytes = eorAwareSSLWrite(
1537 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1540 int error = SSL_get_error(ssl_, int(bytes));
1541 if (error == SSL_ERROR_WANT_WRITE) {
1542 // The caller will register for write event if not already.
1543 *partialWritten = uint32_t(offset);
1544 return WriteResult(totalWritten);
1546 auto writeResult = interpretSSLError(int(bytes), error);
1547 if (writeResult.writeReturn < 0) {
1549 } // else fall through to below to correctly record totalWritten
1552 totalWritten += bytes;
1554 if (bytes == (ssize_t)len) {
1555 // The full iovec is written.
1556 (*countWritten) += 1 + buffersStolen;
1560 bytes += offset; // adjust bytes to account for all of v
1561 while (bytes >= (ssize_t)v->iov_len) {
1562 // We combined this buf with part or all of the next one, and
1563 // we managed to write all of this buf but not all of the bytes
1564 // from the next one that we'd hoped to write.
1565 bytes -= v->iov_len;
1569 *partialWritten = uint32_t(bytes);
1570 return WriteResult(totalWritten);
1574 return WriteResult(totalWritten);
1577 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1579 if (eor && isEorTrackingEnabled()) {
1580 if (appEorByteNo_) {
1581 // cannot track for more than one app byte EOR
1582 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1584 appEorByteNo_ = appBytesWritten_ + n;
1587 // 1. It is fine to keep updating minEorRawByteNo_.
1588 // 2. It is _min_ in the sense that SSL record will add some overhead.
1589 minEorRawByteNo_ = getRawBytesWritten() + n;
1592 n = sslWriteImpl(ssl, buf, n);
1594 appBytesWritten_ += n;
1595 if (appEorByteNo_) {
1596 if (getRawBytesWritten() >= minEorRawByteNo_) {
1597 minEorRawByteNo_ = 0;
1599 if(appBytesWritten_ == appEorByteNo_) {
1602 CHECK(appBytesWritten_ < appEorByteNo_);
1609 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) {
1610 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1611 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1612 sslSocket->renegotiateAttempted_ = true;
1614 if (where & SSL_CB_READ_ALERT) {
1615 const char* type = SSL_alert_type_string(ret);
1617 const char* desc = SSL_alert_desc_string(ret);
1618 sslSocket->alertsReceived_.emplace_back(
1619 *type, StringPiece(desc, std::strlen(desc)));
1624 int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) {
1627 AsyncSSLSocket* tsslSock;
1629 iov.iov_base = const_cast<char*>(in);
1630 iov.iov_len = size_t(inl);
1631 memset(&msg, 0, sizeof(msg));
1635 auto appData = OpenSSLUtils::getBioAppData(b);
1638 tsslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1641 WriteFlags flags = WriteFlags::NONE;
1642 if (tsslSock->isEorTrackingEnabled() && tsslSock->minEorRawByteNo_ &&
1643 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1644 flags |= WriteFlags::EOR;
1647 if (tsslSock->corkCurrentWrite_) {
1648 flags |= WriteFlags::CORK;
1651 int msg_flags = tsslSock->getSendMsgParamsCB()->getFlags(
1652 flags, false /*zeroCopyEnabled*/);
1653 msg.msg_controllen =
1654 tsslSock->getSendMsgParamsCB()->getAncillaryDataSize(flags);
1655 CHECK_GE(AsyncSocket::SendMsgParamsCallback::maxAncillaryDataSize,
1656 msg.msg_controllen);
1657 if (msg.msg_controllen != 0) {
1658 msg.msg_control = reinterpret_cast<char*>(alloca(msg.msg_controllen));
1659 tsslSock->getSendMsgParamsCB()->getAncillaryData(flags, msg.msg_control);
1662 auto result = tsslSock->sendSocketMessage(
1663 OpenSSLUtils::getBioFd(b, nullptr), &msg, msg_flags);
1664 BIO_clear_retry_flags(b);
1665 if (!result.exception && result.writeReturn <= 0) {
1666 if (OpenSSLUtils::getBioShouldRetryWrite(int(result.writeReturn))) {
1667 BIO_set_retry_write(b);
1670 return int(result.writeReturn);
1673 int AsyncSSLSocket::bioRead(BIO* b, char* out, int outl) {
1677 BIO_clear_retry_flags(b);
1679 auto appData = OpenSSLUtils::getBioAppData(b);
1681 auto sslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1683 if (sslSock->preReceivedData_ && !sslSock->preReceivedData_->empty()) {
1684 VLOG(5) << "AsyncSSLSocket::bioRead() this=" << sslSock
1685 << ", reading pre-received data";
1687 Cursor cursor(sslSock->preReceivedData_.get());
1688 auto len = cursor.pullAtMost(out, outl);
1691 queue.append(std::move(sslSock->preReceivedData_));
1692 queue.trimStart(len);
1693 sslSock->preReceivedData_ = queue.move();
1694 return static_cast<int>(len);
1696 auto result = int(recv(OpenSSLUtils::getBioFd(b, nullptr), out, outl, 0));
1697 if (result <= 0 && OpenSSLUtils::getBioShouldRetryWrite(result)) {
1698 BIO_set_retry_read(b);
1704 int AsyncSSLSocket::sslVerifyCallback(
1706 X509_STORE_CTX* x509Ctx) {
1707 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1708 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1709 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1711 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1712 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1713 return (self->handshakeCallback_) ?
1714 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1718 void AsyncSSLSocket::enableClientHelloParsing() {
1719 parseClientHello_ = true;
1720 clientHelloInfo_ = std::make_unique<ssl::ClientHelloInfo>();
1723 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1724 SSL_set_msg_callback(ssl, nullptr);
1725 SSL_set_msg_callback_arg(ssl, nullptr);
1726 clientHelloInfo_->clientHelloBuf_.clear();
1729 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1736 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1738 sock->resetClientHelloParsing(ssl);
1741 if (contentType != SSL3_RT_HANDSHAKE) {
1748 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1749 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1751 Cursor cursor(clientHelloBuf.front());
1752 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1753 sock->resetClientHelloParsing(ssl);
1757 if (cursor.totalLength() < 3) {
1758 clientHelloBuf.trimEnd(len);
1759 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1763 uint32_t messageLength = cursor.read<uint8_t>();
1764 messageLength <<= 8;
1765 messageLength |= cursor.read<uint8_t>();
1766 messageLength <<= 8;
1767 messageLength |= cursor.read<uint8_t>();
1768 if (cursor.totalLength() < messageLength) {
1769 clientHelloBuf.trimEnd(len);
1770 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1774 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1775 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1777 cursor.skip(4); // gmt_unix_time
1778 cursor.skip(28); // random_bytes
1780 cursor.skip(cursor.read<uint8_t>()); // session_id
1782 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1783 for (int i = 0; i < cipherSuitesLength; i += 2) {
1784 sock->clientHelloInfo_->
1785 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1788 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1789 for (int i = 0; i < compressionMethodsLength; ++i) {
1790 sock->clientHelloInfo_->
1791 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1794 if (cursor.totalLength() > 0) {
1795 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1796 while (extensionsLength) {
1797 ssl::TLSExtension extensionType =
1798 static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>());
1799 sock->clientHelloInfo_->
1800 clientHelloExtensions_.push_back(extensionType);
1801 extensionsLength -= 2;
1802 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1803 extensionsLength -= 2;
1804 extensionsLength -= extensionDataLength;
1806 if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) {
1808 extensionDataLength -= 2;
1809 while (extensionDataLength) {
1810 ssl::HashAlgorithm hashAlg =
1811 static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>());
1812 ssl::SignatureAlgorithm sigAlg =
1813 static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>());
1814 extensionDataLength -= 2;
1815 sock->clientHelloInfo_->
1816 clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1818 } else if (extensionType == ssl::TLSExtension::SUPPORTED_VERSIONS) {
1820 extensionDataLength -= 1;
1821 while (extensionDataLength) {
1822 sock->clientHelloInfo_->clientHelloSupportedVersions_.push_back(
1823 cursor.readBE<uint16_t>());
1824 extensionDataLength -= 2;
1827 cursor.skip(extensionDataLength);
1831 } catch (std::out_of_range&) {
1832 // we'll use what we found and cleanup below.
1833 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1834 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1837 sock->resetClientHelloParsing(ssl);
1840 void AsyncSSLSocket::getSSLClientCiphers(
1841 std::string& clientCiphers,
1842 bool convertToString) const {
1843 std::string ciphers;
1845 if (parseClientHello_ == false
1846 || clientHelloInfo_->clientHelloCipherSuites_.empty()) {
1852 for (auto originalCipherCode : clientHelloInfo_->clientHelloCipherSuites_)
1860 bool nameFound = convertToString;
1862 if (convertToString) {
1863 const auto& name = OpenSSLUtils::getCipherName(originalCipherCode);
1873 std::array<uint8_t, 2>{{
1874 static_cast<uint8_t>((originalCipherCode >> 8) & 0xffL),
1875 static_cast<uint8_t>(originalCipherCode & 0x00ffL) }},
1877 /* append to ciphers = */ true);
1881 clientCiphers = std::move(ciphers);
1884 std::string AsyncSSLSocket::getSSLClientComprMethods() const {
1885 if (!parseClientHello_) {
1888 return folly::join(":", clientHelloInfo_->clientHelloCompressionMethods_);
1891 std::string AsyncSSLSocket::getSSLClientExts() const {
1892 if (!parseClientHello_) {
1895 return folly::join(":", clientHelloInfo_->clientHelloExtensions_);
1898 std::string AsyncSSLSocket::getSSLClientSigAlgs() const {
1899 if (!parseClientHello_) {
1903 std::string sigAlgs;
1904 sigAlgs.reserve(clientHelloInfo_->clientHelloSigAlgs_.size() * 4);
1905 for (size_t i = 0; i < clientHelloInfo_->clientHelloSigAlgs_.size(); i++) {
1907 sigAlgs.push_back(':');
1909 sigAlgs.append(folly::to<std::string>(
1910 clientHelloInfo_->clientHelloSigAlgs_[i].first));
1911 sigAlgs.push_back(',');
1912 sigAlgs.append(folly::to<std::string>(
1913 clientHelloInfo_->clientHelloSigAlgs_[i].second));
1919 std::string AsyncSSLSocket::getSSLClientSupportedVersions() const {
1920 if (!parseClientHello_) {
1923 return folly::join(":", clientHelloInfo_->clientHelloSupportedVersions_);
1926 std::string AsyncSSLSocket::getSSLAlertsReceived() const {
1929 for (const auto& alert : alertsReceived_) {
1933 ret.append(folly::to<std::string>(alert.first, ": ", alert.second));
1939 void AsyncSSLSocket::setSSLCertVerificationAlert(std::string alert) {
1940 sslVerificationAlert_ = std::move(alert);
1943 std::string AsyncSSLSocket::getSSLCertVerificationAlert() const {
1944 return sslVerificationAlert_;
1947 void AsyncSSLSocket::getSSLSharedCiphers(std::string& sharedCiphers) const {
1948 char ciphersBuffer[1024];
1949 ciphersBuffer[0] = '\0';
1950 SSL_get_shared_ciphers(ssl_, ciphersBuffer, sizeof(ciphersBuffer) - 1);
1951 sharedCiphers = ciphersBuffer;
1954 void AsyncSSLSocket::getSSLServerCiphers(std::string& serverCiphers) const {
1955 serverCiphers = SSL_get_cipher_list(ssl_, 0);
1958 while ((cipher = SSL_get_cipher_list(ssl_, i)) != nullptr) {
1959 serverCiphers.append(":");
1960 serverCiphers.append(cipher);
1965 } // namespace folly