2 * Copyright 2017 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 <openssl/err.h>
26 #include <openssl/asn1.h>
27 #include <openssl/ssl.h>
28 #include <sys/types.h>
31 #include <folly/Bits.h>
32 #include <folly/SocketAddress.h>
33 #include <folly/SpinLock.h>
34 #include <folly/io/Cursor.h>
35 #include <folly/io/IOBuf.h>
36 #include <folly/portability/OpenSSL.h>
37 #include <folly/portability/Unistd.h>
39 using folly::SocketAddress;
40 using folly::SSLContext;
42 using std::shared_ptr;
46 using folly::SpinLock;
47 using folly::SpinLockGuard;
48 using folly::io::Cursor;
49 using std::unique_ptr;
53 using folly::AsyncSocket;
54 using folly::AsyncSocketException;
55 using folly::AsyncSSLSocket;
56 using folly::Optional;
57 using folly::SSLContext;
58 // For OpenSSL portability API
59 using namespace folly::ssl;
60 using folly::ssl::OpenSSLUtils;
62 // We have one single dummy SSL context so that we can implement attach
63 // and detach methods in a thread safe fashion without modifying opnessl.
64 static SSLContext *dummyCtx = nullptr;
65 static SpinLock dummyCtxLock;
67 // If given min write size is less than this, buffer will be allocated on
68 // stack, otherwise it is allocated on heap
69 const size_t MAX_STACK_BUF_SIZE = 2048;
71 // This converts "illegal" shutdowns into ZERO_RETURN
72 inline bool zero_return(int error, int rc) {
73 return (error == SSL_ERROR_ZERO_RETURN || (rc == 0 && errno == 0));
76 class AsyncSSLSocketConnector: public AsyncSocket::ConnectCallback,
77 public AsyncSSLSocket::HandshakeCB {
80 AsyncSSLSocket *sslSocket_;
81 AsyncSSLSocket::ConnectCallback *callback_;
86 ~AsyncSSLSocketConnector() override {}
89 AsyncSSLSocketConnector(AsyncSSLSocket *sslSocket,
90 AsyncSocket::ConnectCallback *callback,
92 sslSocket_(sslSocket),
95 startTime_(std::chrono::duration_cast<std::chrono::milliseconds>(
96 std::chrono::steady_clock::now().time_since_epoch()).count()) {
99 void connectSuccess() noexcept override {
100 VLOG(7) << "client socket connected";
102 int64_t timeoutLeft = 0;
104 auto curTime = std::chrono::duration_cast<std::chrono::milliseconds>(
105 std::chrono::steady_clock::now().time_since_epoch()).count();
107 timeoutLeft = timeout_ - (curTime - startTime_);
108 if (timeoutLeft <= 0) {
109 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
110 "SSL connect timed out");
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 BIO_METHOD sslBioMethod;
181 void* initsslBioMethod(void) {
182 memcpy(&sslBioMethod, BIO_s_socket(), sizeof(sslBioMethod));
183 // override the bwrite method for MSG_EOR support
184 OpenSSLUtils::setCustomBioWriteMethod(
185 &sslBioMethod, AsyncSSLSocket::bioWrite);
186 OpenSSLUtils::setCustomBioReadMethod(&sslBioMethod, AsyncSSLSocket::bioRead);
188 // Note that the sslBioMethod.type and sslBioMethod.name are not
189 // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
190 // then have specific handlings. The sslWriteBioWrite should be compatible
191 // with the one in openssl.
193 // Return something here to enable AsyncSSLSocket to call this method using
194 // a function-scoped static.
198 } // anonymous namespace
203 * Create a client AsyncSSLSocket
205 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
206 EventBase* evb, bool deferSecurityNegotiation) :
209 handshakeTimeout_(this, evb),
210 connectionTimeout_(this, evb) {
212 if (deferSecurityNegotiation) {
213 sslState_ = STATE_UNENCRYPTED;
218 * Create a server/client AsyncSSLSocket
220 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
221 EventBase* evb, int fd, bool server,
222 bool deferSecurityNegotiation) :
223 AsyncSocket(evb, fd),
226 handshakeTimeout_(this, evb),
227 connectionTimeout_(this, evb) {
228 noTransparentTls_ = true;
231 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
232 AsyncSSLSocket::sslInfoCallback);
234 if (deferSecurityNegotiation) {
235 sslState_ = STATE_UNENCRYPTED;
239 #if FOLLY_OPENSSL_HAS_SNI
241 * Create a client AsyncSSLSocket and allow tlsext_hostname
242 * to be sent in Client Hello.
244 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
246 const std::string& serverName,
247 bool deferSecurityNegotiation) :
248 AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
249 tlsextHostname_ = serverName;
253 * Create a client AsyncSSLSocket from an already connected fd
254 * and allow tlsext_hostname to be sent in Client Hello.
256 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
257 EventBase* evb, int fd,
258 const std::string& serverName,
259 bool deferSecurityNegotiation) :
260 AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
261 tlsextHostname_ = serverName;
263 #endif // FOLLY_OPENSSL_HAS_SNI
265 AsyncSSLSocket::~AsyncSSLSocket() {
266 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
267 << ", evb=" << eventBase_ << ", fd=" << fd_
268 << ", state=" << int(state_) << ", sslState="
269 << sslState_ << ", events=" << eventFlags_ << ")";
272 void AsyncSSLSocket::init() {
273 // Do this here to ensure we initialize this once before any use of
274 // AsyncSSLSocket instances and not as part of library load.
275 static const auto sslBioMethodInitializer = initsslBioMethod();
276 (void)sslBioMethodInitializer;
278 setup_SSL_CTX(ctx_->getSSLCtx());
281 void AsyncSSLSocket::closeNow() {
282 // Close the SSL connection.
283 if (ssl_ != nullptr && fd_ != -1) {
284 int rc = SSL_shutdown(ssl_);
286 rc = SSL_shutdown(ssl_);
293 if (sslSession_ != nullptr) {
294 SSL_SESSION_free(sslSession_);
295 sslSession_ = nullptr;
298 sslState_ = STATE_CLOSED;
300 if (handshakeTimeout_.isScheduled()) {
301 handshakeTimeout_.cancelTimeout();
304 DestructorGuard dg(this);
307 AsyncSocketException(
308 AsyncSocketException::END_OF_FILE,
309 "SSL connection closed locally"));
311 if (ssl_ != nullptr) {
317 AsyncSocket::closeNow();
320 void AsyncSSLSocket::shutdownWrite() {
321 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
323 // (Performing a full shutdown here is more desirable than doing nothing at
324 // all. The purpose of shutdownWrite() is normally to notify the other end
325 // of the connection that no more data will be sent. If we do nothing, the
326 // other end will never know that no more data is coming, and this may result
327 // in protocol deadlock.)
331 void AsyncSSLSocket::shutdownWriteNow() {
335 bool AsyncSSLSocket::good() const {
336 return (AsyncSocket::good() &&
337 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
338 sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
341 // The TAsyncTransport definition of 'good' states that the transport is
342 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
343 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
344 // is connected but we haven't initiated the call to SSL_connect.
345 bool AsyncSSLSocket::connecting() const {
347 (AsyncSocket::connecting() ||
348 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
349 sslState_ == STATE_CONNECTING))));
352 std::string AsyncSSLSocket::getApplicationProtocol() noexcept {
353 const unsigned char* protoName = nullptr;
354 unsigned protoLength;
355 if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) {
356 return std::string(reinterpret_cast<const char*>(protoName), protoLength);
361 void AsyncSSLSocket::setEorTracking(bool track) {
362 if (isEorTrackingEnabled() != track) {
363 AsyncSocket::setEorTracking(track);
365 minEorRawByteNo_ = 0;
369 size_t AsyncSSLSocket::getRawBytesWritten() const {
370 // The bio(s) in the write path are in a chain
371 // each bio flushes to the next and finally written into the socket
372 // to get the rawBytesWritten on the socket,
373 // get the write bytes of the last bio
375 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
378 BIO* next = BIO_next(b);
379 while (next != NULL) {
384 return BIO_number_written(b);
387 size_t AsyncSSLSocket::getRawBytesReceived() const {
389 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
393 return BIO_number_read(b);
397 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
398 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
399 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
400 << "events=" << eventFlags_ << ", server=" << short(server_)
401 << "): " << "sslAccept/Connect() called in invalid "
402 << "state, handshake callback " << handshakeCallback_
403 << ", new callback " << callback;
404 assert(!handshakeTimeout_.isScheduled());
405 sslState_ = STATE_ERROR;
407 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
408 "sslAccept() called with socket in invalid state");
410 handshakeEndTime_ = std::chrono::steady_clock::now();
412 callback->handshakeErr(this, ex);
415 failHandshake(__func__, ex);
418 void AsyncSSLSocket::sslAccept(
419 HandshakeCB* callback,
420 std::chrono::milliseconds timeout,
421 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
422 DestructorGuard dg(this);
423 assert(eventBase_->isInEventBaseThread());
424 verifyPeer_ = verifyPeer;
426 // Make sure we're in the uninitialized state
427 if (!server_ || (sslState_ != STATE_UNINIT &&
428 sslState_ != STATE_UNENCRYPTED) ||
429 handshakeCallback_ != nullptr) {
430 return invalidState(callback);
433 // Cache local and remote socket addresses to keep them available
434 // after socket file descriptor is closed.
435 if (cacheAddrOnFailure_ && -1 != getFd()) {
436 cacheLocalPeerAddr();
439 handshakeStartTime_ = std::chrono::steady_clock::now();
440 // Make end time at least >= start time.
441 handshakeEndTime_ = handshakeStartTime_;
443 sslState_ = STATE_ACCEPTING;
444 handshakeCallback_ = callback;
446 if (timeout > std::chrono::milliseconds::zero()) {
447 handshakeTimeout_.scheduleTimeout(timeout);
450 /* register for a read operation (waiting for CLIENT HELLO) */
451 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
453 if (preReceivedData_) {
458 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
459 void AsyncSSLSocket::attachSSLContext(
460 const std::shared_ptr<SSLContext>& ctx) {
462 // Check to ensure we are in client mode. Changing a server's ssl
463 // context doesn't make sense since clients of that server would likely
464 // become confused when the server's context changes.
468 DCHECK(ctx->getSSLCtx());
471 // It's possible this could be attached before ssl_ is set up
476 // In order to call attachSSLContext, detachSSLContext must have been
477 // previously called.
478 // We need to update the initial_ctx if necessary
479 auto sslCtx = ctx->getSSLCtx();
480 SSL_CTX_up_ref(sslCtx);
481 #ifndef OPENSSL_NO_TLSEXT
482 // note that detachSSLContext has already freed ssl_->initial_ctx
483 ssl_->initial_ctx = sslCtx;
485 // Detach sets the socket's context to the dummy context. Thus we must acquire
487 SpinLockGuard guard(dummyCtxLock);
488 SSL_set_SSL_CTX(ssl_, sslCtx);
491 void AsyncSSLSocket::detachSSLContext() {
494 // It's possible for this to be called before ssl_ has been
499 // Detach the initial_ctx as well. Internally w/ OPENSSL_NO_TLSEXT
500 // it is used for session info. It will be reattached in attachSSLContext
501 #ifndef OPENSSL_NO_TLSEXT
502 if (ssl_->initial_ctx) {
503 SSL_CTX_free(ssl_->initial_ctx);
504 ssl_->initial_ctx = nullptr;
507 SpinLockGuard guard(dummyCtxLock);
508 if (nullptr == dummyCtx) {
509 // We need to lazily initialize the dummy context so we don't
510 // accidentally override any programmatic settings to openssl
511 dummyCtx = new SSLContext;
513 // We must remove this socket's references to its context right now
514 // since this socket could get passed to any thread. If the context has
515 // had its locking disabled, just doing a set in attachSSLContext()
516 // would not be thread safe.
517 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
521 #if FOLLY_OPENSSL_HAS_SNI
522 void AsyncSSLSocket::switchServerSSLContext(
523 const std::shared_ptr<SSLContext>& handshakeCtx) {
525 if (sslState_ != STATE_ACCEPTING) {
526 // We log it here and allow the switch.
527 // It should not affect our re-negotiation support (which
528 // is not supported now).
529 VLOG(6) << "fd=" << getFd()
530 << " renegotation detected when switching SSL_CTX";
533 setup_SSL_CTX(handshakeCtx->getSSLCtx());
534 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
535 AsyncSSLSocket::sslInfoCallback);
536 handshakeCtx_ = handshakeCtx;
537 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
540 bool AsyncSSLSocket::isServerNameMatch() const {
547 SSL_SESSION *ss = SSL_get_session(ssl_);
552 if(!ss->tlsext_hostname) {
555 return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
558 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
559 tlsextHostname_ = std::move(serverName);
562 #endif // FOLLY_OPENSSL_HAS_SNI
564 void AsyncSSLSocket::timeoutExpired() noexcept {
565 if (state_ == StateEnum::ESTABLISHED &&
566 (sslState_ == STATE_CACHE_LOOKUP ||
567 sslState_ == STATE_ASYNC_PENDING)) {
568 sslState_ = STATE_ERROR;
569 // We are expecting a callback in restartSSLAccept. The cache lookup
570 // and rsa-call necessarily have pointers to this ssl socket, so delay
571 // the cleanup until he calls us back.
572 } else if (state_ == StateEnum::CONNECTING) {
573 assert(sslState_ == STATE_CONNECTING);
574 DestructorGuard dg(this);
575 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
576 "Fallback connect timed out during TFO");
577 failHandshake(__func__, ex);
579 assert(state_ == StateEnum::ESTABLISHED &&
580 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
581 DestructorGuard dg(this);
582 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
583 (sslState_ == STATE_CONNECTING) ?
584 "SSL connect timed out" : "SSL accept timed out");
585 failHandshake(__func__, ex);
589 int AsyncSSLSocket::getSSLExDataIndex() {
590 static auto index = SSL_get_ex_new_index(
591 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
595 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
596 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
597 getSSLExDataIndex()));
600 void AsyncSSLSocket::failHandshake(const char* /* fn */,
601 const AsyncSocketException& ex) {
603 if (handshakeTimeout_.isScheduled()) {
604 handshakeTimeout_.cancelTimeout();
606 invokeHandshakeErr(ex);
610 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
611 handshakeEndTime_ = std::chrono::steady_clock::now();
612 if (handshakeCallback_ != nullptr) {
613 HandshakeCB* callback = handshakeCallback_;
614 handshakeCallback_ = nullptr;
615 callback->handshakeErr(this, ex);
619 void AsyncSSLSocket::invokeHandshakeCB() {
620 handshakeEndTime_ = std::chrono::steady_clock::now();
621 if (handshakeTimeout_.isScheduled()) {
622 handshakeTimeout_.cancelTimeout();
624 if (handshakeCallback_) {
625 HandshakeCB* callback = handshakeCallback_;
626 handshakeCallback_ = nullptr;
627 callback->handshakeSuc(this);
631 void AsyncSSLSocket::cacheLocalPeerAddr() {
632 SocketAddress address;
634 getLocalAddress(&address);
635 getPeerAddress(&address);
636 } catch (const std::system_error& e) {
637 // The handle can be still valid while the connection is already closed.
638 if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
644 void AsyncSSLSocket::connect(ConnectCallback* callback,
645 const folly::SocketAddress& address,
647 const OptionMap &options,
648 const folly::SocketAddress& bindAddr)
651 assert(state_ == StateEnum::UNINIT);
652 assert(sslState_ == STATE_UNINIT);
653 noTransparentTls_ = true;
654 AsyncSSLSocketConnector *connector =
655 new AsyncSSLSocketConnector(this, callback, timeout);
656 AsyncSocket::connect(connector, address, timeout, options, bindAddr);
659 bool AsyncSSLSocket::needsPeerVerification() const {
660 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
661 return ctx_->needsPeerVerification();
664 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
665 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
668 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
669 // apply the settings specified in verifyPeer_
670 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
671 if(ctx_->needsPeerVerification()) {
672 SSL_set_verify(ssl, ctx_->getVerificationMode(),
673 AsyncSSLSocket::sslVerifyCallback);
676 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
677 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
678 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
679 AsyncSSLSocket::sslVerifyCallback);
684 bool AsyncSSLSocket::setupSSLBio() {
685 auto sslBio = BIO_new(&sslBioMethod);
691 OpenSSLUtils::setBioAppData(sslBio, this);
692 OpenSSLUtils::setBioFd(sslBio, fd_, BIO_NOCLOSE);
693 SSL_set_bio(ssl_, sslBio, sslBio);
697 void AsyncSSLSocket::sslConn(
698 HandshakeCB* callback,
699 std::chrono::milliseconds timeout,
700 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
701 DestructorGuard dg(this);
702 assert(eventBase_->isInEventBaseThread());
704 // Cache local and remote socket addresses to keep them available
705 // after socket file descriptor is closed.
706 if (cacheAddrOnFailure_ && -1 != getFd()) {
707 cacheLocalPeerAddr();
710 verifyPeer_ = verifyPeer;
712 // Make sure we're in the uninitialized state
713 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
714 STATE_UNENCRYPTED) ||
715 handshakeCallback_ != nullptr) {
716 return invalidState(callback);
719 sslState_ = STATE_CONNECTING;
720 handshakeCallback_ = callback;
723 ssl_ = ctx_->createSSL();
724 } catch (std::exception &e) {
725 sslState_ = STATE_ERROR;
726 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
727 "error calling SSLContext::createSSL()");
728 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
729 << fd_ << "): " << e.what();
730 return failHandshake(__func__, ex);
733 if (!setupSSLBio()) {
734 sslState_ = STATE_ERROR;
735 AsyncSocketException ex(
736 AsyncSocketException::INTERNAL_ERROR, "error creating SSL bio");
737 return failHandshake(__func__, ex);
740 applyVerificationOptions(ssl_);
742 if (sslSession_ != nullptr) {
743 sessionResumptionAttempted_ = true;
744 SSL_set_session(ssl_, sslSession_);
745 SSL_SESSION_free(sslSession_);
746 sslSession_ = nullptr;
748 #if FOLLY_OPENSSL_HAS_SNI
749 if (tlsextHostname_.size()) {
750 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
754 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
756 handshakeConnectTimeout_ = timeout;
760 // This could be called multiple times, during normal ssl connections
761 // and after TFO fallback.
762 void AsyncSSLSocket::startSSLConnect() {
763 handshakeStartTime_ = std::chrono::steady_clock::now();
764 // Make end time at least >= start time.
765 handshakeEndTime_ = handshakeStartTime_;
766 if (handshakeConnectTimeout_ > std::chrono::milliseconds::zero()) {
767 handshakeTimeout_.scheduleTimeout(handshakeConnectTimeout_);
772 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
773 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
774 return SSL_get1_session(ssl_);
780 const SSL* AsyncSSLSocket::getSSL() const {
784 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
785 sslSession_ = session;
786 if (!takeOwnership && session != nullptr) {
787 // Increment the reference count
788 // This API exists in BoringSSL and OpenSSL 1.1.0
789 SSL_SESSION_up_ref(session);
793 void AsyncSSLSocket::getSelectedNextProtocol(
794 const unsigned char** protoName,
796 SSLContext::NextProtocolType* protoType) const {
797 if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
798 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
799 "NPN not supported");
803 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
804 const unsigned char** protoName,
806 SSLContext::NextProtocolType* protoType) const {
807 *protoName = nullptr;
809 #if FOLLY_OPENSSL_HAS_ALPN
810 SSL_get0_alpn_selected(ssl_, protoName, protoLen);
813 *protoType = SSLContext::NextProtocolType::ALPN;
818 #ifdef OPENSSL_NPN_NEGOTIATED
819 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
821 *protoType = SSLContext::NextProtocolType::NPN;
830 bool AsyncSSLSocket::getSSLSessionReused() const {
831 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
832 return SSL_session_reused(ssl_);
837 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
838 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
842 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
843 if (ssl == nullptr) {
846 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
847 return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
853 const char *AsyncSSLSocket::getSSLServerName() const {
854 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
855 return getSSLServerNameFromSSL(ssl_);
857 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
858 "SNI not supported");
862 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
863 return getSSLServerNameFromSSL(ssl_);
866 int AsyncSSLSocket::getSSLVersion() const {
867 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
870 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
871 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
873 int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
874 return OBJ_nid2ln(nid);
879 int AsyncSSLSocket::getSSLCertSize() const {
881 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
883 EVP_PKEY *key = X509_get_pubkey(cert);
884 certSize = EVP_PKEY_bits(key);
890 const X509* AsyncSSLSocket::getSelfCert() const {
891 return (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
894 bool AsyncSSLSocket::willBlock(int ret,
896 unsigned long* errErrorOut) noexcept {
898 int error = *sslErrorOut = SSL_get_error(ssl_, ret);
899 if (error == SSL_ERROR_WANT_READ) {
900 // Register for read event if not already.
901 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
903 } else if (error == SSL_ERROR_WANT_WRITE) {
904 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
905 << ", state=" << int(state_) << ", sslState="
906 << sslState_ << ", events=" << eventFlags_ << "): "
907 << "SSL_ERROR_WANT_WRITE";
908 // Register for write event if not already.
909 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
911 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
912 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
913 // We will block but we can't register our own socket. The callback that
914 // triggered this code will re-call handleAccept at the appropriate time.
916 // We can only get here if the linked libssl.so has support for this feature
917 // as well, otherwise SSL_get_error cannot return our error code.
918 sslState_ = STATE_CACHE_LOOKUP;
920 // Unregister for all events while blocked here
921 updateEventRegistration(EventHandler::NONE,
922 EventHandler::READ | EventHandler::WRITE);
924 // The timeout (if set) keeps running here
928 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
929 || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
931 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
932 || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
935 // Our custom openssl function has kicked off an async request to do
936 // rsa/ecdsa private key operation. When that call returns, a callback will
937 // be invoked that will re-call handleAccept.
938 sslState_ = STATE_ASYNC_PENDING;
940 // Unregister for all events while blocked here
941 updateEventRegistration(
943 EventHandler::READ | EventHandler::WRITE
946 // The timeout (if set) keeps running here
949 unsigned long lastError = *errErrorOut = ERR_get_error();
950 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
951 << "state=" << state_ << ", "
952 << "sslState=" << sslState_ << ", "
953 << "events=" << std::hex << eventFlags_ << "): "
954 << "SSL error: " << error << ", "
955 << "errno: " << errno << ", "
956 << "ret: " << ret << ", "
957 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
958 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
959 << "func: " << ERR_func_error_string(lastError) << ", "
960 << "reason: " << ERR_reason_error_string(lastError);
965 void AsyncSSLSocket::checkForImmediateRead() noexcept {
966 // openssl may have buffered data that it read from the socket already.
967 // In this case we have to process it immediately, rather than waiting for
968 // the socket to become readable again.
969 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
970 AsyncSocket::handleRead();
975 AsyncSSLSocket::restartSSLAccept()
977 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this
978 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
979 << "sslState=" << sslState_ << ", events=" << eventFlags_;
980 DestructorGuard dg(this);
982 sslState_ == STATE_CACHE_LOOKUP ||
983 sslState_ == STATE_ASYNC_PENDING ||
984 sslState_ == STATE_ERROR ||
985 sslState_ == STATE_CLOSED);
986 if (sslState_ == STATE_CLOSED) {
987 // I sure hope whoever closed this socket didn't delete it already,
988 // but this is not strictly speaking an error
991 if (sslState_ == STATE_ERROR) {
992 // go straight to fail if timeout expired during lookup
993 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
994 "SSL accept timed out");
995 failHandshake(__func__, ex);
998 sslState_ = STATE_ACCEPTING;
999 this->handleAccept();
1003 AsyncSSLSocket::handleAccept() noexcept {
1004 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
1005 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1006 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1008 assert(state_ == StateEnum::ESTABLISHED &&
1009 sslState_ == STATE_ACCEPTING);
1011 /* lazily create the SSL structure */
1013 ssl_ = ctx_->createSSL();
1014 } catch (std::exception &e) {
1015 sslState_ = STATE_ERROR;
1016 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1017 "error calling SSLContext::createSSL()");
1018 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
1019 << ", fd=" << fd_ << "): " << e.what();
1020 return failHandshake(__func__, ex);
1023 if (!setupSSLBio()) {
1024 sslState_ = STATE_ERROR;
1025 AsyncSocketException ex(
1026 AsyncSocketException::INTERNAL_ERROR, "error creating write bio");
1027 return failHandshake(__func__, ex);
1030 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
1032 applyVerificationOptions(ssl_);
1035 if (server_ && parseClientHello_) {
1036 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1037 SSL_set_msg_callback_arg(ssl_, this);
1040 int ret = SSL_accept(ssl_);
1043 unsigned long errError;
1044 int errnoCopy = errno;
1045 if (willBlock(ret, &sslError, &errError)) {
1048 sslState_ = STATE_ERROR;
1049 SSLException ex(sslError, errError, ret, errnoCopy);
1050 return failHandshake(__func__, ex);
1054 handshakeComplete_ = true;
1055 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1057 // Move into STATE_ESTABLISHED in the normal case that we are in
1059 sslState_ = STATE_ESTABLISHED;
1061 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1062 << " successfully accepted; state=" << int(state_)
1063 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1065 // Remember the EventBase we are attached to, before we start invoking any
1066 // callbacks (since the callbacks may call detachEventBase()).
1067 EventBase* originalEventBase = eventBase_;
1069 // Call the accept callback.
1070 invokeHandshakeCB();
1072 // Note that the accept callback may have changed our state.
1073 // (set or unset the read callback, called write(), closed the socket, etc.)
1074 // The following code needs to handle these situations correctly.
1076 // If the socket has been closed, readCallback_ and writeReqHead_ will
1077 // always be nullptr, so that will prevent us from trying to read or write.
1079 // The main thing to check for is if eventBase_ is still originalEventBase.
1080 // If not, we have been detached from this event base, so we shouldn't
1081 // perform any more operations.
1082 if (eventBase_ != originalEventBase) {
1086 AsyncSocket::handleInitialReadWrite();
1090 AsyncSSLSocket::handleConnect() noexcept {
1091 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1092 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1093 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1095 if (state_ < StateEnum::ESTABLISHED) {
1096 return AsyncSocket::handleConnect();
1100 (state_ == StateEnum::FAST_OPEN || state_ == StateEnum::ESTABLISHED) &&
1101 sslState_ == STATE_CONNECTING);
1104 auto originalState = state_;
1105 int ret = SSL_connect(ssl_);
1108 unsigned long errError;
1109 int errnoCopy = errno;
1110 if (willBlock(ret, &sslError, &errError)) {
1111 // We fell back to connecting state due to TFO
1112 if (state_ == StateEnum::CONNECTING) {
1113 DCHECK_EQ(StateEnum::FAST_OPEN, originalState);
1114 if (handshakeTimeout_.isScheduled()) {
1115 handshakeTimeout_.cancelTimeout();
1120 sslState_ = STATE_ERROR;
1121 SSLException ex(sslError, errError, ret, errnoCopy);
1122 return failHandshake(__func__, ex);
1126 handshakeComplete_ = true;
1127 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1129 // Move into STATE_ESTABLISHED in the normal case that we are in
1130 // STATE_CONNECTING.
1131 sslState_ = STATE_ESTABLISHED;
1133 VLOG(3) << "AsyncSSLSocket " << this << ": "
1134 << "fd " << fd_ << " successfully connected; "
1135 << "state=" << int(state_) << ", sslState=" << sslState_
1136 << ", events=" << eventFlags_;
1138 // Remember the EventBase we are attached to, before we start invoking any
1139 // callbacks (since the callbacks may call detachEventBase()).
1140 EventBase* originalEventBase = eventBase_;
1142 // Call the handshake callback.
1143 invokeHandshakeCB();
1145 // Note that the connect callback may have changed our state.
1146 // (set or unset the read callback, called write(), closed the socket, etc.)
1147 // The following code needs to handle these situations correctly.
1149 // If the socket has been closed, readCallback_ and writeReqHead_ will
1150 // always be nullptr, so that will prevent us from trying to read or write.
1152 // The main thing to check for is if eventBase_ is still originalEventBase.
1153 // If not, we have been detached from this event base, so we shouldn't
1154 // perform any more operations.
1155 if (eventBase_ != originalEventBase) {
1159 AsyncSocket::handleInitialReadWrite();
1162 void AsyncSSLSocket::invokeConnectErr(const AsyncSocketException& ex) {
1163 connectionTimeout_.cancelTimeout();
1164 AsyncSocket::invokeConnectErr(ex);
1165 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1166 if (handshakeTimeout_.isScheduled()) {
1167 handshakeTimeout_.cancelTimeout();
1169 // If we fell back to connecting state during TFO and the connection
1170 // failed, it would be an SSL failure as well.
1171 invokeHandshakeErr(ex);
1175 void AsyncSSLSocket::invokeConnectSuccess() {
1176 connectionTimeout_.cancelTimeout();
1177 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1178 assert(tfoAttempted_);
1179 // If we failed TFO, we'd fall back to trying to connect the socket,
1180 // to setup things like timeouts.
1183 // still invoke the base class since it re-sets the connect time.
1184 AsyncSocket::invokeConnectSuccess();
1187 void AsyncSSLSocket::scheduleConnectTimeout() {
1188 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1189 // We fell back from TFO, and need to set the timeouts.
1190 // We will not have a connect callback in this case, thus if the timer
1191 // expires we would have no-one to notify.
1192 // Thus we should reset even the connect timers to point to the handshake
1194 assert(connectCallback_ == nullptr);
1195 // We use a different connect timeout here than the handshake timeout, so
1196 // that we can disambiguate the 2 timers.
1197 if (connectTimeout_.count() > 0) {
1198 if (!connectionTimeout_.scheduleTimeout(connectTimeout_)) {
1199 throw AsyncSocketException(
1200 AsyncSocketException::INTERNAL_ERROR,
1201 withAddr("failed to schedule AsyncSSLSocket connect timeout"));
1206 AsyncSocket::scheduleConnectTimeout();
1209 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1210 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1211 // turn on the buffer movable in openssl
1212 if (bufferMovableEnabled_ && ssl_ != nullptr && !isBufferMovable_ &&
1213 callback != nullptr && callback->isBufferMovable()) {
1214 SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1215 isBufferMovable_ = true;
1219 AsyncSocket::setReadCB(callback);
1222 void AsyncSSLSocket::setBufferMovableEnabled(bool enabled) {
1223 bufferMovableEnabled_ = enabled;
1226 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1227 CHECK(readCallback_);
1228 if (isBufferMovable_) {
1232 // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1233 readCallback_->getReadBuffer(buf, buflen);
1238 AsyncSSLSocket::handleRead() noexcept {
1239 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1240 << ", state=" << int(state_) << ", "
1241 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1242 if (state_ < StateEnum::ESTABLISHED) {
1243 return AsyncSocket::handleRead();
1247 if (sslState_ == STATE_ACCEPTING) {
1252 else if (sslState_ == STATE_CONNECTING) {
1259 AsyncSocket::handleRead();
1262 AsyncSocket::ReadResult
1263 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1264 VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf
1265 << ", buflen=" << *buflen;
1267 if (sslState_ == STATE_UNENCRYPTED) {
1268 return AsyncSocket::performRead(buf, buflen, offset);
1272 if (!isBufferMovable_) {
1273 bytes = SSL_read(ssl_, *buf, int(*buflen));
1275 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1277 bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1281 if (server_ && renegotiateAttempted_) {
1282 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1283 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1284 << "): client intitiated SSL renegotiation not permitted";
1287 folly::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION));
1290 int error = SSL_get_error(ssl_, bytes);
1291 if (error == SSL_ERROR_WANT_READ) {
1292 // The caller will register for read event if not already.
1293 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1294 return ReadResult(READ_BLOCKING);
1296 return ReadResult(READ_ERROR);
1298 } else if (error == SSL_ERROR_WANT_WRITE) {
1299 // TODO: Even though we are attempting to read data, SSL_read() may
1300 // need to write data if renegotiation is being performed. We currently
1301 // don't support this and just fail the read.
1302 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1303 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1304 << "): unsupported SSL renegotiation during read";
1307 folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1309 if (zero_return(error, bytes)) {
1310 return ReadResult(bytes);
1312 long errError = ERR_get_error();
1313 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1314 << "state=" << state_ << ", "
1315 << "sslState=" << sslState_ << ", "
1316 << "events=" << std::hex << eventFlags_ << "): "
1317 << "bytes: " << bytes << ", "
1318 << "error: " << error << ", "
1319 << "errno: " << errno << ", "
1320 << "func: " << ERR_func_error_string(errError) << ", "
1321 << "reason: " << ERR_reason_error_string(errError);
1324 folly::make_unique<SSLException>(error, errError, bytes, errno));
1327 appBytesReceived_ += bytes;
1328 return ReadResult(bytes);
1332 void AsyncSSLSocket::handleWrite() noexcept {
1333 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1334 << ", state=" << int(state_) << ", "
1335 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1336 if (state_ < StateEnum::ESTABLISHED) {
1337 return AsyncSocket::handleWrite();
1340 if (sslState_ == STATE_ACCEPTING) {
1346 if (sslState_ == STATE_CONNECTING) {
1353 AsyncSocket::handleWrite();
1356 AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {
1357 if (error == SSL_ERROR_WANT_READ) {
1358 // Even though we are attempting to write data, SSL_write() may
1359 // need to read data if renegotiation is being performed. We currently
1360 // don't support this and just fail the write.
1361 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1362 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1364 << "unsupported SSL renegotiation during write";
1367 folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1369 if (zero_return(error, rc)) {
1370 return WriteResult(0);
1372 auto errError = ERR_get_error();
1373 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1374 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1375 << "SSL error: " << error << ", errno: " << errno
1376 << ", func: " << ERR_func_error_string(errError)
1377 << ", reason: " << ERR_reason_error_string(errError);
1380 folly::make_unique<SSLException>(error, errError, rc, errno));
1384 AsyncSocket::WriteResult AsyncSSLSocket::performWrite(
1388 uint32_t* countWritten,
1389 uint32_t* partialWritten) {
1390 if (sslState_ == STATE_UNENCRYPTED) {
1391 return AsyncSocket::performWrite(
1392 vec, count, flags, countWritten, partialWritten);
1394 if (sslState_ != STATE_ESTABLISHED) {
1395 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1396 << ", sslState=" << sslState_
1397 << ", events=" << eventFlags_ << "): "
1398 << "TODO: AsyncSSLSocket currently does not support calling "
1399 << "write() before the handshake has fully completed";
1401 WRITE_ERROR, folly::make_unique<SSLException>(SSLError::EARLY_WRITE));
1404 // Declare a buffer used to hold small write requests. It could point to a
1405 // memory block either on stack or on heap. If it is on heap, we release it
1406 // manually when scope exits
1407 char* combinedBuf{nullptr};
1409 // Note, always keep this check consistent with what we do below
1410 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1411 delete[] combinedBuf;
1416 *partialWritten = 0;
1417 ssize_t totalWritten = 0;
1418 size_t bytesStolenFromNextBuffer = 0;
1419 for (uint32_t i = 0; i < count; i++) {
1420 const iovec* v = vec + i;
1421 size_t offset = bytesStolenFromNextBuffer;
1422 bytesStolenFromNextBuffer = 0;
1423 size_t len = v->iov_len - offset;
1429 buf = ((const char*)v->iov_base) + offset;
1432 uint32_t buffersStolen = 0;
1433 auto sslWriteBuf = buf;
1434 if ((len < minWriteSize_) && ((i + 1) < count)) {
1435 // Combine this buffer with part or all of the next buffers in
1436 // order to avoid really small-grained calls to SSL_write().
1437 // Each call to SSL_write() produces a separate record in
1438 // the egress SSL stream, and we've found that some low-end
1439 // mobile clients can't handle receiving an HTTP response
1440 // header and the first part of the response body in two
1441 // separate SSL records (even if those two records are in
1442 // the same TCP packet).
1444 if (combinedBuf == nullptr) {
1445 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1446 // Allocate the buffer on heap
1447 combinedBuf = new char[minWriteSize_];
1449 // Allocate the buffer on stack
1450 combinedBuf = (char*)alloca(minWriteSize_);
1453 assert(combinedBuf != nullptr);
1454 sslWriteBuf = combinedBuf;
1456 memcpy(combinedBuf, buf, len);
1458 // INVARIANT: i + buffersStolen == complete chunks serialized
1459 uint32_t nextIndex = i + buffersStolen + 1;
1460 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1461 minWriteSize_ - len);
1462 memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1463 bytesStolenFromNextBuffer);
1464 len += bytesStolenFromNextBuffer;
1465 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1466 // couldn't steal the whole buffer
1469 bytesStolenFromNextBuffer = 0;
1472 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1475 // Advance any empty buffers immediately after.
1476 if (bytesStolenFromNextBuffer == 0) {
1477 while ((i + buffersStolen + 1) < count &&
1478 vec[i + buffersStolen + 1].iov_len == 0) {
1484 isSet(flags, WriteFlags::CORK) || (i + buffersStolen + 1 < count);
1485 bytes = eorAwareSSLWrite(
1489 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1492 int error = SSL_get_error(ssl_, int(bytes));
1493 if (error == SSL_ERROR_WANT_WRITE) {
1494 // The caller will register for write event if not already.
1495 *partialWritten = uint32_t(offset);
1496 return WriteResult(totalWritten);
1498 auto writeResult = interpretSSLError(int(bytes), error);
1499 if (writeResult.writeReturn < 0) {
1501 } // else fall through to below to correctly record totalWritten
1504 totalWritten += bytes;
1506 if (bytes == (ssize_t)len) {
1507 // The full iovec is written.
1508 (*countWritten) += 1 + buffersStolen;
1512 bytes += offset; // adjust bytes to account for all of v
1513 while (bytes >= (ssize_t)v->iov_len) {
1514 // We combined this buf with part or all of the next one, and
1515 // we managed to write all of this buf but not all of the bytes
1516 // from the next one that we'd hoped to write.
1517 bytes -= v->iov_len;
1521 *partialWritten = uint32_t(bytes);
1522 return WriteResult(totalWritten);
1526 return WriteResult(totalWritten);
1529 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1531 if (eor && isEorTrackingEnabled()) {
1532 if (appEorByteNo_) {
1533 // cannot track for more than one app byte EOR
1534 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1536 appEorByteNo_ = appBytesWritten_ + n;
1539 // 1. It is fine to keep updating minEorRawByteNo_.
1540 // 2. It is _min_ in the sense that SSL record will add some overhead.
1541 minEorRawByteNo_ = getRawBytesWritten() + n;
1544 n = sslWriteImpl(ssl, buf, n);
1546 appBytesWritten_ += n;
1547 if (appEorByteNo_) {
1548 if (getRawBytesWritten() >= minEorRawByteNo_) {
1549 minEorRawByteNo_ = 0;
1551 if(appBytesWritten_ == appEorByteNo_) {
1554 CHECK(appBytesWritten_ < appEorByteNo_);
1561 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) {
1562 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1563 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1564 sslSocket->renegotiateAttempted_ = true;
1566 if (where & SSL_CB_READ_ALERT) {
1567 const char* type = SSL_alert_type_string(ret);
1569 const char* desc = SSL_alert_desc_string(ret);
1570 sslSocket->alertsReceived_.emplace_back(
1571 *type, StringPiece(desc, std::strlen(desc)));
1576 int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) {
1580 AsyncSSLSocket* tsslSock;
1582 iov.iov_base = const_cast<char*>(in);
1584 memset(&msg, 0, sizeof(msg));
1588 auto appData = OpenSSLUtils::getBioAppData(b);
1591 tsslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1594 if (tsslSock->isEorTrackingEnabled() && tsslSock->minEorRawByteNo_ &&
1595 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1600 flags |= MSG_NOSIGNAL;
1604 if (tsslSock->corkCurrentWrite_) {
1609 auto result = tsslSock->sendSocketMessage(
1610 OpenSSLUtils::getBioFd(b, nullptr), &msg, flags);
1611 BIO_clear_retry_flags(b);
1612 if (!result.exception && result.writeReturn <= 0) {
1613 if (OpenSSLUtils::getBioShouldRetryWrite(int(result.writeReturn))) {
1614 BIO_set_retry_write(b);
1617 return int(result.writeReturn);
1620 int AsyncSSLSocket::bioRead(BIO* b, char* out, int outl) {
1624 BIO_clear_retry_flags(b);
1626 auto appData = OpenSSLUtils::getBioAppData(b);
1628 auto sslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1630 if (sslSock->preReceivedData_ && !sslSock->preReceivedData_->empty()) {
1631 VLOG(5) << "AsyncSSLSocket::bioRead() this=" << sslSock
1632 << ", reading pre-received data";
1634 Cursor cursor(sslSock->preReceivedData_.get());
1635 auto len = cursor.pullAtMost(out, outl);
1638 queue.append(std::move(sslSock->preReceivedData_));
1639 queue.trimStart(len);
1640 sslSock->preReceivedData_ = queue.move();
1643 auto result = recv(OpenSSLUtils::getBioFd(b, nullptr), out, outl, 0);
1644 if (result <= 0 && OpenSSLUtils::getBioShouldRetryWrite(result)) {
1645 BIO_set_retry_read(b);
1651 int AsyncSSLSocket::sslVerifyCallback(
1653 X509_STORE_CTX* x509Ctx) {
1654 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1655 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1656 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1658 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1659 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1660 return (self->handshakeCallback_) ?
1661 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1665 void AsyncSSLSocket::setPreReceivedData(std::unique_ptr<IOBuf> data) {
1666 CHECK(sslState_ == STATE_UNINIT || sslState_ == STATE_UNENCRYPTED);
1667 CHECK(!preReceivedData_);
1668 preReceivedData_ = std::move(data);
1671 void AsyncSSLSocket::enableClientHelloParsing() {
1672 parseClientHello_ = true;
1673 clientHelloInfo_.reset(new ssl::ClientHelloInfo());
1676 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1677 SSL_set_msg_callback(ssl, nullptr);
1678 SSL_set_msg_callback_arg(ssl, nullptr);
1679 clientHelloInfo_->clientHelloBuf_.clear();
1682 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1689 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1691 sock->resetClientHelloParsing(ssl);
1694 if (contentType != SSL3_RT_HANDSHAKE) {
1701 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1702 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1704 Cursor cursor(clientHelloBuf.front());
1705 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1706 sock->resetClientHelloParsing(ssl);
1710 if (cursor.totalLength() < 3) {
1711 clientHelloBuf.trimEnd(len);
1712 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1716 uint32_t messageLength = cursor.read<uint8_t>();
1717 messageLength <<= 8;
1718 messageLength |= cursor.read<uint8_t>();
1719 messageLength <<= 8;
1720 messageLength |= cursor.read<uint8_t>();
1721 if (cursor.totalLength() < messageLength) {
1722 clientHelloBuf.trimEnd(len);
1723 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1727 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1728 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1730 cursor.skip(4); // gmt_unix_time
1731 cursor.skip(28); // random_bytes
1733 cursor.skip(cursor.read<uint8_t>()); // session_id
1735 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1736 for (int i = 0; i < cipherSuitesLength; i += 2) {
1737 sock->clientHelloInfo_->
1738 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1741 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1742 for (int i = 0; i < compressionMethodsLength; ++i) {
1743 sock->clientHelloInfo_->
1744 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1747 if (cursor.totalLength() > 0) {
1748 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1749 while (extensionsLength) {
1750 ssl::TLSExtension extensionType =
1751 static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>());
1752 sock->clientHelloInfo_->
1753 clientHelloExtensions_.push_back(extensionType);
1754 extensionsLength -= 2;
1755 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1756 extensionsLength -= 2;
1757 extensionsLength -= extensionDataLength;
1759 if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) {
1761 extensionDataLength -= 2;
1762 while (extensionDataLength) {
1763 ssl::HashAlgorithm hashAlg =
1764 static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>());
1765 ssl::SignatureAlgorithm sigAlg =
1766 static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>());
1767 extensionDataLength -= 2;
1768 sock->clientHelloInfo_->
1769 clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1771 } else if (extensionType == ssl::TLSExtension::SUPPORTED_VERSIONS) {
1773 extensionDataLength -= 1;
1774 while (extensionDataLength) {
1775 sock->clientHelloInfo_->clientHelloSupportedVersions_.push_back(
1776 cursor.readBE<uint16_t>());
1777 extensionDataLength -= 2;
1780 cursor.skip(extensionDataLength);
1784 } catch (std::out_of_range&) {
1785 // we'll use what we found and cleanup below.
1786 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1787 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1790 sock->resetClientHelloParsing(ssl);
1793 void AsyncSSLSocket::getSSLClientCiphers(
1794 std::string& clientCiphers,
1795 bool convertToString) const {
1796 std::string ciphers;
1798 if (parseClientHello_ == false
1799 || clientHelloInfo_->clientHelloCipherSuites_.empty()) {
1805 for (auto originalCipherCode : clientHelloInfo_->clientHelloCipherSuites_)
1813 bool nameFound = convertToString;
1815 if (convertToString) {
1816 const auto& name = OpenSSLUtils::getCipherName(originalCipherCode);
1826 std::array<uint8_t, 2>{{
1827 static_cast<uint8_t>((originalCipherCode >> 8) & 0xffL),
1828 static_cast<uint8_t>(originalCipherCode & 0x00ffL) }},
1830 /* append to ciphers = */ true);
1834 clientCiphers = std::move(ciphers);
1837 std::string AsyncSSLSocket::getSSLClientComprMethods() const {
1838 if (!parseClientHello_) {
1841 return folly::join(":", clientHelloInfo_->clientHelloCompressionMethods_);
1844 std::string AsyncSSLSocket::getSSLClientExts() const {
1845 if (!parseClientHello_) {
1848 return folly::join(":", clientHelloInfo_->clientHelloExtensions_);
1851 std::string AsyncSSLSocket::getSSLClientSigAlgs() const {
1852 if (!parseClientHello_) {
1856 std::string sigAlgs;
1857 sigAlgs.reserve(clientHelloInfo_->clientHelloSigAlgs_.size() * 4);
1858 for (size_t i = 0; i < clientHelloInfo_->clientHelloSigAlgs_.size(); i++) {
1860 sigAlgs.push_back(':');
1862 sigAlgs.append(folly::to<std::string>(
1863 clientHelloInfo_->clientHelloSigAlgs_[i].first));
1864 sigAlgs.push_back(',');
1865 sigAlgs.append(folly::to<std::string>(
1866 clientHelloInfo_->clientHelloSigAlgs_[i].second));
1872 std::string AsyncSSLSocket::getSSLClientSupportedVersions() const {
1873 if (!parseClientHello_) {
1876 return folly::join(":", clientHelloInfo_->clientHelloSupportedVersions_);
1879 std::string AsyncSSLSocket::getSSLAlertsReceived() const {
1882 for (const auto& alert : alertsReceived_) {
1886 ret.append(folly::to<std::string>(alert.first, ": ", alert.second));
1892 void AsyncSSLSocket::getSSLSharedCiphers(std::string& sharedCiphers) const {
1893 char ciphersBuffer[1024];
1894 ciphersBuffer[0] = '\0';
1895 SSL_get_shared_ciphers(ssl_, ciphersBuffer, sizeof(ciphersBuffer) - 1);
1896 sharedCiphers = ciphersBuffer;
1899 void AsyncSSLSocket::getSSLServerCiphers(std::string& serverCiphers) const {
1900 serverCiphers = SSL_get_cipher_list(ssl_, 0);
1903 while ((cipher = SSL_get_cipher_list(ssl_, i)) != nullptr) {
1904 serverCiphers.append(":");
1905 serverCiphers.append(cipher);