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) {
230 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
231 AsyncSSLSocket::sslInfoCallback);
233 if (deferSecurityNegotiation) {
234 sslState_ = STATE_UNENCRYPTED;
238 #if FOLLY_OPENSSL_HAS_SNI
240 * Create a client AsyncSSLSocket and allow tlsext_hostname
241 * to be sent in Client Hello.
243 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
245 const std::string& serverName,
246 bool deferSecurityNegotiation) :
247 AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
248 tlsextHostname_ = serverName;
252 * Create a client AsyncSSLSocket from an already connected fd
253 * and allow tlsext_hostname to be sent in Client Hello.
255 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
256 EventBase* evb, int fd,
257 const std::string& serverName,
258 bool deferSecurityNegotiation) :
259 AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
260 tlsextHostname_ = serverName;
262 #endif // FOLLY_OPENSSL_HAS_SNI
264 AsyncSSLSocket::~AsyncSSLSocket() {
265 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
266 << ", evb=" << eventBase_ << ", fd=" << fd_
267 << ", state=" << int(state_) << ", sslState="
268 << sslState_ << ", events=" << eventFlags_ << ")";
271 void AsyncSSLSocket::init() {
272 // Do this here to ensure we initialize this once before any use of
273 // AsyncSSLSocket instances and not as part of library load.
274 static const auto sslBioMethodInitializer = initsslBioMethod();
275 (void)sslBioMethodInitializer;
277 setup_SSL_CTX(ctx_->getSSLCtx());
280 void AsyncSSLSocket::closeNow() {
281 // Close the SSL connection.
282 if (ssl_ != nullptr && fd_ != -1) {
283 int rc = SSL_shutdown(ssl_);
285 rc = SSL_shutdown(ssl_);
292 if (sslSession_ != nullptr) {
293 SSL_SESSION_free(sslSession_);
294 sslSession_ = nullptr;
297 sslState_ = STATE_CLOSED;
299 if (handshakeTimeout_.isScheduled()) {
300 handshakeTimeout_.cancelTimeout();
303 DestructorGuard dg(this);
306 AsyncSocketException(
307 AsyncSocketException::END_OF_FILE,
308 "SSL connection closed locally"));
310 if (ssl_ != nullptr) {
316 AsyncSocket::closeNow();
319 void AsyncSSLSocket::shutdownWrite() {
320 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
322 // (Performing a full shutdown here is more desirable than doing nothing at
323 // all. The purpose of shutdownWrite() is normally to notify the other end
324 // of the connection that no more data will be sent. If we do nothing, the
325 // other end will never know that no more data is coming, and this may result
326 // in protocol deadlock.)
330 void AsyncSSLSocket::shutdownWriteNow() {
334 bool AsyncSSLSocket::good() const {
335 return (AsyncSocket::good() &&
336 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
337 sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
340 // The TAsyncTransport definition of 'good' states that the transport is
341 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
342 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
343 // is connected but we haven't initiated the call to SSL_connect.
344 bool AsyncSSLSocket::connecting() const {
346 (AsyncSocket::connecting() ||
347 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
348 sslState_ == STATE_CONNECTING))));
351 std::string AsyncSSLSocket::getApplicationProtocol() noexcept {
352 const unsigned char* protoName = nullptr;
353 unsigned protoLength;
354 if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) {
355 return std::string(reinterpret_cast<const char*>(protoName), protoLength);
360 bool AsyncSSLSocket::isEorTrackingEnabled() const {
364 void AsyncSSLSocket::setEorTracking(bool track) {
365 if (trackEor_ != track) {
368 minEorRawByteNo_ = 0;
372 size_t AsyncSSLSocket::getRawBytesWritten() const {
373 // The bio(s) in the write path are in a chain
374 // each bio flushes to the next and finally written into the socket
375 // to get the rawBytesWritten on the socket,
376 // get the write bytes of the last bio
378 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
381 BIO* next = BIO_next(b);
382 while (next != NULL) {
387 return BIO_number_written(b);
390 size_t AsyncSSLSocket::getRawBytesReceived() const {
392 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
396 return BIO_number_read(b);
400 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
401 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
402 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
403 << "events=" << eventFlags_ << ", server=" << short(server_)
404 << "): " << "sslAccept/Connect() called in invalid "
405 << "state, handshake callback " << handshakeCallback_
406 << ", new callback " << callback;
407 assert(!handshakeTimeout_.isScheduled());
408 sslState_ = STATE_ERROR;
410 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
411 "sslAccept() called with socket in invalid state");
413 handshakeEndTime_ = std::chrono::steady_clock::now();
415 callback->handshakeErr(this, ex);
418 failHandshake(__func__, ex);
421 void AsyncSSLSocket::sslAccept(
422 HandshakeCB* callback,
423 std::chrono::milliseconds timeout,
424 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
425 DestructorGuard dg(this);
426 assert(eventBase_->isInEventBaseThread());
427 verifyPeer_ = verifyPeer;
429 // Make sure we're in the uninitialized state
430 if (!server_ || (sslState_ != STATE_UNINIT &&
431 sslState_ != STATE_UNENCRYPTED) ||
432 handshakeCallback_ != nullptr) {
433 return invalidState(callback);
436 // Cache local and remote socket addresses to keep them available
437 // after socket file descriptor is closed.
438 if (cacheAddrOnFailure_ && -1 != getFd()) {
439 cacheLocalPeerAddr();
442 handshakeStartTime_ = std::chrono::steady_clock::now();
443 // Make end time at least >= start time.
444 handshakeEndTime_ = handshakeStartTime_;
446 sslState_ = STATE_ACCEPTING;
447 handshakeCallback_ = callback;
449 if (timeout > std::chrono::milliseconds::zero()) {
450 handshakeTimeout_.scheduleTimeout(timeout);
453 /* register for a read operation (waiting for CLIENT HELLO) */
454 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
456 if (preReceivedData_) {
461 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
462 void AsyncSSLSocket::attachSSLContext(
463 const std::shared_ptr<SSLContext>& ctx) {
465 // Check to ensure we are in client mode. Changing a server's ssl
466 // context doesn't make sense since clients of that server would likely
467 // become confused when the server's context changes.
471 DCHECK(ctx->getSSLCtx());
474 // It's possible this could be attached before ssl_ is set up
479 // In order to call attachSSLContext, detachSSLContext must have been
480 // previously called.
481 // We need to update the initial_ctx if necessary
482 auto sslCtx = ctx->getSSLCtx();
483 SSL_CTX_up_ref(sslCtx);
484 #ifndef OPENSSL_NO_TLSEXT
485 // note that detachSSLContext has already freed ssl_->initial_ctx
486 ssl_->initial_ctx = sslCtx;
488 // Detach sets the socket's context to the dummy context. Thus we must acquire
490 SpinLockGuard guard(dummyCtxLock);
491 SSL_set_SSL_CTX(ssl_, sslCtx);
494 void AsyncSSLSocket::detachSSLContext() {
497 // It's possible for this to be called before ssl_ has been
502 // Detach the initial_ctx as well. Internally w/ OPENSSL_NO_TLSEXT
503 // it is used for session info. It will be reattached in attachSSLContext
504 #ifndef OPENSSL_NO_TLSEXT
505 if (ssl_->initial_ctx) {
506 SSL_CTX_free(ssl_->initial_ctx);
507 ssl_->initial_ctx = nullptr;
510 SpinLockGuard guard(dummyCtxLock);
511 if (nullptr == dummyCtx) {
512 // We need to lazily initialize the dummy context so we don't
513 // accidentally override any programmatic settings to openssl
514 dummyCtx = new SSLContext;
516 // We must remove this socket's references to its context right now
517 // since this socket could get passed to any thread. If the context has
518 // had its locking disabled, just doing a set in attachSSLContext()
519 // would not be thread safe.
520 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
524 #if FOLLY_OPENSSL_HAS_SNI
525 void AsyncSSLSocket::switchServerSSLContext(
526 const std::shared_ptr<SSLContext>& handshakeCtx) {
528 if (sslState_ != STATE_ACCEPTING) {
529 // We log it here and allow the switch.
530 // It should not affect our re-negotiation support (which
531 // is not supported now).
532 VLOG(6) << "fd=" << getFd()
533 << " renegotation detected when switching SSL_CTX";
536 setup_SSL_CTX(handshakeCtx->getSSLCtx());
537 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
538 AsyncSSLSocket::sslInfoCallback);
539 handshakeCtx_ = handshakeCtx;
540 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
543 bool AsyncSSLSocket::isServerNameMatch() const {
550 SSL_SESSION *ss = SSL_get_session(ssl_);
555 if(!ss->tlsext_hostname) {
558 return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
561 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
562 tlsextHostname_ = std::move(serverName);
565 #endif // FOLLY_OPENSSL_HAS_SNI
567 void AsyncSSLSocket::timeoutExpired() noexcept {
568 if (state_ == StateEnum::ESTABLISHED &&
569 (sslState_ == STATE_CACHE_LOOKUP ||
570 sslState_ == STATE_ASYNC_PENDING)) {
571 sslState_ = STATE_ERROR;
572 // We are expecting a callback in restartSSLAccept. The cache lookup
573 // and rsa-call necessarily have pointers to this ssl socket, so delay
574 // the cleanup until he calls us back.
575 } else if (state_ == StateEnum::CONNECTING) {
576 assert(sslState_ == STATE_CONNECTING);
577 DestructorGuard dg(this);
578 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
579 "Fallback connect timed out during TFO");
580 failHandshake(__func__, ex);
582 assert(state_ == StateEnum::ESTABLISHED &&
583 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
584 DestructorGuard dg(this);
585 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
586 (sslState_ == STATE_CONNECTING) ?
587 "SSL connect timed out" : "SSL accept timed out");
588 failHandshake(__func__, ex);
592 int AsyncSSLSocket::getSSLExDataIndex() {
593 static auto index = SSL_get_ex_new_index(
594 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
598 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
599 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
600 getSSLExDataIndex()));
603 void AsyncSSLSocket::failHandshake(const char* /* fn */,
604 const AsyncSocketException& ex) {
606 if (handshakeTimeout_.isScheduled()) {
607 handshakeTimeout_.cancelTimeout();
609 invokeHandshakeErr(ex);
613 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
614 handshakeEndTime_ = std::chrono::steady_clock::now();
615 if (handshakeCallback_ != nullptr) {
616 HandshakeCB* callback = handshakeCallback_;
617 handshakeCallback_ = nullptr;
618 callback->handshakeErr(this, ex);
622 void AsyncSSLSocket::invokeHandshakeCB() {
623 handshakeEndTime_ = std::chrono::steady_clock::now();
624 if (handshakeTimeout_.isScheduled()) {
625 handshakeTimeout_.cancelTimeout();
627 if (handshakeCallback_) {
628 HandshakeCB* callback = handshakeCallback_;
629 handshakeCallback_ = nullptr;
630 callback->handshakeSuc(this);
634 void AsyncSSLSocket::cacheLocalPeerAddr() {
635 SocketAddress address;
637 getLocalAddress(&address);
638 getPeerAddress(&address);
639 } catch (const std::system_error& e) {
640 // The handle can be still valid while the connection is already closed.
641 if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
647 void AsyncSSLSocket::connect(ConnectCallback* callback,
648 const folly::SocketAddress& address,
650 const OptionMap &options,
651 const folly::SocketAddress& bindAddr)
654 assert(state_ == StateEnum::UNINIT);
655 assert(sslState_ == STATE_UNINIT);
656 AsyncSSLSocketConnector *connector =
657 new AsyncSSLSocketConnector(this, callback, timeout);
658 AsyncSocket::connect(connector, address, timeout, options, bindAddr);
661 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
662 // apply the settings specified in verifyPeer_
663 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
664 if(ctx_->needsPeerVerification()) {
665 SSL_set_verify(ssl, ctx_->getVerificationMode(),
666 AsyncSSLSocket::sslVerifyCallback);
669 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
670 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
671 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
672 AsyncSSLSocket::sslVerifyCallback);
677 bool AsyncSSLSocket::setupSSLBio() {
678 auto sslBio = BIO_new(&sslBioMethod);
684 OpenSSLUtils::setBioAppData(sslBio, this);
685 OpenSSLUtils::setBioFd(sslBio, fd_, BIO_NOCLOSE);
686 SSL_set_bio(ssl_, sslBio, sslBio);
690 void AsyncSSLSocket::sslConn(
691 HandshakeCB* callback,
692 std::chrono::milliseconds timeout,
693 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
694 DestructorGuard dg(this);
695 assert(eventBase_->isInEventBaseThread());
697 // Cache local and remote socket addresses to keep them available
698 // after socket file descriptor is closed.
699 if (cacheAddrOnFailure_ && -1 != getFd()) {
700 cacheLocalPeerAddr();
703 verifyPeer_ = verifyPeer;
705 // Make sure we're in the uninitialized state
706 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
707 STATE_UNENCRYPTED) ||
708 handshakeCallback_ != nullptr) {
709 return invalidState(callback);
712 sslState_ = STATE_CONNECTING;
713 handshakeCallback_ = callback;
716 ssl_ = ctx_->createSSL();
717 } catch (std::exception &e) {
718 sslState_ = STATE_ERROR;
719 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
720 "error calling SSLContext::createSSL()");
721 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
722 << fd_ << "): " << e.what();
723 return failHandshake(__func__, ex);
726 if (!setupSSLBio()) {
727 sslState_ = STATE_ERROR;
728 AsyncSocketException ex(
729 AsyncSocketException::INTERNAL_ERROR, "error creating SSL bio");
730 return failHandshake(__func__, ex);
733 applyVerificationOptions(ssl_);
735 if (sslSession_ != nullptr) {
736 sessionResumptionAttempted_ = true;
737 SSL_set_session(ssl_, sslSession_);
738 SSL_SESSION_free(sslSession_);
739 sslSession_ = nullptr;
741 #if FOLLY_OPENSSL_HAS_SNI
742 if (tlsextHostname_.size()) {
743 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
747 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
749 handshakeConnectTimeout_ = timeout;
753 // This could be called multiple times, during normal ssl connections
754 // and after TFO fallback.
755 void AsyncSSLSocket::startSSLConnect() {
756 handshakeStartTime_ = std::chrono::steady_clock::now();
757 // Make end time at least >= start time.
758 handshakeEndTime_ = handshakeStartTime_;
759 if (handshakeConnectTimeout_ > std::chrono::milliseconds::zero()) {
760 handshakeTimeout_.scheduleTimeout(handshakeConnectTimeout_);
765 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
766 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
767 return SSL_get1_session(ssl_);
773 const SSL* AsyncSSLSocket::getSSL() const {
777 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
778 sslSession_ = session;
779 if (!takeOwnership && session != nullptr) {
780 // Increment the reference count
781 // This API exists in BoringSSL and OpenSSL 1.1.0
782 SSL_SESSION_up_ref(session);
786 void AsyncSSLSocket::getSelectedNextProtocol(
787 const unsigned char** protoName,
789 SSLContext::NextProtocolType* protoType) const {
790 if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
791 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
792 "NPN not supported");
796 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
797 const unsigned char** protoName,
799 SSLContext::NextProtocolType* protoType) const {
800 *protoName = nullptr;
802 #if FOLLY_OPENSSL_HAS_ALPN
803 SSL_get0_alpn_selected(ssl_, protoName, protoLen);
806 *protoType = SSLContext::NextProtocolType::ALPN;
811 #ifdef OPENSSL_NPN_NEGOTIATED
812 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
814 *protoType = SSLContext::NextProtocolType::NPN;
823 bool AsyncSSLSocket::getSSLSessionReused() const {
824 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
825 return SSL_session_reused(ssl_);
830 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
831 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
835 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
836 if (ssl == nullptr) {
839 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
840 return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
846 const char *AsyncSSLSocket::getSSLServerName() const {
847 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
848 return getSSLServerNameFromSSL(ssl_);
850 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
851 "SNI not supported");
855 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
856 return getSSLServerNameFromSSL(ssl_);
859 int AsyncSSLSocket::getSSLVersion() const {
860 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
863 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
864 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
866 int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
867 return OBJ_nid2ln(nid);
872 int AsyncSSLSocket::getSSLCertSize() const {
874 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
876 EVP_PKEY *key = X509_get_pubkey(cert);
877 certSize = EVP_PKEY_bits(key);
883 const X509* AsyncSSLSocket::getSelfCert() const {
884 return (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
887 bool AsyncSSLSocket::willBlock(int ret,
889 unsigned long* errErrorOut) noexcept {
891 int error = *sslErrorOut = SSL_get_error(ssl_, ret);
892 if (error == SSL_ERROR_WANT_READ) {
893 // Register for read event if not already.
894 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
896 } else if (error == SSL_ERROR_WANT_WRITE) {
897 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
898 << ", state=" << int(state_) << ", sslState="
899 << sslState_ << ", events=" << eventFlags_ << "): "
900 << "SSL_ERROR_WANT_WRITE";
901 // Register for write event if not already.
902 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
904 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
905 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
906 // We will block but we can't register our own socket. The callback that
907 // triggered this code will re-call handleAccept at the appropriate time.
909 // We can only get here if the linked libssl.so has support for this feature
910 // as well, otherwise SSL_get_error cannot return our error code.
911 sslState_ = STATE_CACHE_LOOKUP;
913 // Unregister for all events while blocked here
914 updateEventRegistration(EventHandler::NONE,
915 EventHandler::READ | EventHandler::WRITE);
917 // The timeout (if set) keeps running here
921 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
922 || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
924 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
925 || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
928 // Our custom openssl function has kicked off an async request to do
929 // rsa/ecdsa private key operation. When that call returns, a callback will
930 // be invoked that will re-call handleAccept.
931 sslState_ = STATE_ASYNC_PENDING;
933 // Unregister for all events while blocked here
934 updateEventRegistration(
936 EventHandler::READ | EventHandler::WRITE
939 // The timeout (if set) keeps running here
942 unsigned long lastError = *errErrorOut = ERR_get_error();
943 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
944 << "state=" << state_ << ", "
945 << "sslState=" << sslState_ << ", "
946 << "events=" << std::hex << eventFlags_ << "): "
947 << "SSL error: " << error << ", "
948 << "errno: " << errno << ", "
949 << "ret: " << ret << ", "
950 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
951 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
952 << "func: " << ERR_func_error_string(lastError) << ", "
953 << "reason: " << ERR_reason_error_string(lastError);
958 void AsyncSSLSocket::checkForImmediateRead() noexcept {
959 // openssl may have buffered data that it read from the socket already.
960 // In this case we have to process it immediately, rather than waiting for
961 // the socket to become readable again.
962 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
963 AsyncSocket::handleRead();
968 AsyncSSLSocket::restartSSLAccept()
970 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this
971 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
972 << "sslState=" << sslState_ << ", events=" << eventFlags_;
973 DestructorGuard dg(this);
975 sslState_ == STATE_CACHE_LOOKUP ||
976 sslState_ == STATE_ASYNC_PENDING ||
977 sslState_ == STATE_ERROR ||
978 sslState_ == STATE_CLOSED);
979 if (sslState_ == STATE_CLOSED) {
980 // I sure hope whoever closed this socket didn't delete it already,
981 // but this is not strictly speaking an error
984 if (sslState_ == STATE_ERROR) {
985 // go straight to fail if timeout expired during lookup
986 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
987 "SSL accept timed out");
988 failHandshake(__func__, ex);
991 sslState_ = STATE_ACCEPTING;
992 this->handleAccept();
996 AsyncSSLSocket::handleAccept() noexcept {
997 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
998 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
999 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1001 assert(state_ == StateEnum::ESTABLISHED &&
1002 sslState_ == STATE_ACCEPTING);
1004 /* lazily create the SSL structure */
1006 ssl_ = ctx_->createSSL();
1007 } catch (std::exception &e) {
1008 sslState_ = STATE_ERROR;
1009 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1010 "error calling SSLContext::createSSL()");
1011 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
1012 << ", fd=" << fd_ << "): " << e.what();
1013 return failHandshake(__func__, ex);
1016 if (!setupSSLBio()) {
1017 sslState_ = STATE_ERROR;
1018 AsyncSocketException ex(
1019 AsyncSocketException::INTERNAL_ERROR, "error creating write bio");
1020 return failHandshake(__func__, ex);
1023 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
1025 applyVerificationOptions(ssl_);
1028 if (server_ && parseClientHello_) {
1029 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1030 SSL_set_msg_callback_arg(ssl_, this);
1033 int ret = SSL_accept(ssl_);
1036 unsigned long errError;
1037 int errnoCopy = errno;
1038 if (willBlock(ret, &sslError, &errError)) {
1041 sslState_ = STATE_ERROR;
1042 SSLException ex(sslError, errError, ret, errnoCopy);
1043 return failHandshake(__func__, ex);
1047 handshakeComplete_ = true;
1048 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1050 // Move into STATE_ESTABLISHED in the normal case that we are in
1052 sslState_ = STATE_ESTABLISHED;
1054 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1055 << " successfully accepted; state=" << int(state_)
1056 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1058 // Remember the EventBase we are attached to, before we start invoking any
1059 // callbacks (since the callbacks may call detachEventBase()).
1060 EventBase* originalEventBase = eventBase_;
1062 // Call the accept callback.
1063 invokeHandshakeCB();
1065 // Note that the accept callback may have changed our state.
1066 // (set or unset the read callback, called write(), closed the socket, etc.)
1067 // The following code needs to handle these situations correctly.
1069 // If the socket has been closed, readCallback_ and writeReqHead_ will
1070 // always be nullptr, so that will prevent us from trying to read or write.
1072 // The main thing to check for is if eventBase_ is still originalEventBase.
1073 // If not, we have been detached from this event base, so we shouldn't
1074 // perform any more operations.
1075 if (eventBase_ != originalEventBase) {
1079 AsyncSocket::handleInitialReadWrite();
1083 AsyncSSLSocket::handleConnect() noexcept {
1084 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1085 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1086 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1088 if (state_ < StateEnum::ESTABLISHED) {
1089 return AsyncSocket::handleConnect();
1093 (state_ == StateEnum::FAST_OPEN || state_ == StateEnum::ESTABLISHED) &&
1094 sslState_ == STATE_CONNECTING);
1097 auto originalState = state_;
1098 int ret = SSL_connect(ssl_);
1101 unsigned long errError;
1102 int errnoCopy = errno;
1103 if (willBlock(ret, &sslError, &errError)) {
1104 // We fell back to connecting state due to TFO
1105 if (state_ == StateEnum::CONNECTING) {
1106 DCHECK_EQ(StateEnum::FAST_OPEN, originalState);
1107 if (handshakeTimeout_.isScheduled()) {
1108 handshakeTimeout_.cancelTimeout();
1113 sslState_ = STATE_ERROR;
1114 SSLException ex(sslError, errError, ret, errnoCopy);
1115 return failHandshake(__func__, ex);
1119 handshakeComplete_ = true;
1120 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1122 // Move into STATE_ESTABLISHED in the normal case that we are in
1123 // STATE_CONNECTING.
1124 sslState_ = STATE_ESTABLISHED;
1126 VLOG(3) << "AsyncSSLSocket " << this << ": "
1127 << "fd " << fd_ << " successfully connected; "
1128 << "state=" << int(state_) << ", sslState=" << sslState_
1129 << ", events=" << eventFlags_;
1131 // Remember the EventBase we are attached to, before we start invoking any
1132 // callbacks (since the callbacks may call detachEventBase()).
1133 EventBase* originalEventBase = eventBase_;
1135 // Call the handshake callback.
1136 invokeHandshakeCB();
1138 // Note that the connect callback may have changed our state.
1139 // (set or unset the read callback, called write(), closed the socket, etc.)
1140 // The following code needs to handle these situations correctly.
1142 // If the socket has been closed, readCallback_ and writeReqHead_ will
1143 // always be nullptr, so that will prevent us from trying to read or write.
1145 // The main thing to check for is if eventBase_ is still originalEventBase.
1146 // If not, we have been detached from this event base, so we shouldn't
1147 // perform any more operations.
1148 if (eventBase_ != originalEventBase) {
1152 AsyncSocket::handleInitialReadWrite();
1155 void AsyncSSLSocket::invokeConnectErr(const AsyncSocketException& ex) {
1156 connectionTimeout_.cancelTimeout();
1157 AsyncSocket::invokeConnectErr(ex);
1158 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1159 if (handshakeTimeout_.isScheduled()) {
1160 handshakeTimeout_.cancelTimeout();
1162 // If we fell back to connecting state during TFO and the connection
1163 // failed, it would be an SSL failure as well.
1164 invokeHandshakeErr(ex);
1168 void AsyncSSLSocket::invokeConnectSuccess() {
1169 connectionTimeout_.cancelTimeout();
1170 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1171 assert(tfoAttempted_);
1172 // If we failed TFO, we'd fall back to trying to connect the socket,
1173 // to setup things like timeouts.
1176 // still invoke the base class since it re-sets the connect time.
1177 AsyncSocket::invokeConnectSuccess();
1180 void AsyncSSLSocket::scheduleConnectTimeout() {
1181 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1182 // We fell back from TFO, and need to set the timeouts.
1183 // We will not have a connect callback in this case, thus if the timer
1184 // expires we would have no-one to notify.
1185 // Thus we should reset even the connect timers to point to the handshake
1187 assert(connectCallback_ == nullptr);
1188 // We use a different connect timeout here than the handshake timeout, so
1189 // that we can disambiguate the 2 timers.
1190 if (connectTimeout_.count() > 0) {
1191 if (!connectionTimeout_.scheduleTimeout(connectTimeout_)) {
1192 throw AsyncSocketException(
1193 AsyncSocketException::INTERNAL_ERROR,
1194 withAddr("failed to schedule AsyncSSLSocket connect timeout"));
1199 AsyncSocket::scheduleConnectTimeout();
1202 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1203 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1204 // turn on the buffer movable in openssl
1205 if (bufferMovableEnabled_ && ssl_ != nullptr && !isBufferMovable_ &&
1206 callback != nullptr && callback->isBufferMovable()) {
1207 SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1208 isBufferMovable_ = true;
1212 AsyncSocket::setReadCB(callback);
1215 void AsyncSSLSocket::setBufferMovableEnabled(bool enabled) {
1216 bufferMovableEnabled_ = enabled;
1219 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1220 CHECK(readCallback_);
1221 if (isBufferMovable_) {
1225 // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1226 readCallback_->getReadBuffer(buf, buflen);
1231 AsyncSSLSocket::handleRead() noexcept {
1232 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1233 << ", state=" << int(state_) << ", "
1234 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1235 if (state_ < StateEnum::ESTABLISHED) {
1236 return AsyncSocket::handleRead();
1240 if (sslState_ == STATE_ACCEPTING) {
1245 else if (sslState_ == STATE_CONNECTING) {
1252 AsyncSocket::handleRead();
1255 AsyncSocket::ReadResult
1256 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1257 VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf
1258 << ", buflen=" << *buflen;
1260 if (sslState_ == STATE_UNENCRYPTED) {
1261 return AsyncSocket::performRead(buf, buflen, offset);
1265 if (!isBufferMovable_) {
1266 bytes = SSL_read(ssl_, *buf, int(*buflen));
1268 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1270 bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1274 if (server_ && renegotiateAttempted_) {
1275 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1276 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1277 << "): client intitiated SSL renegotiation not permitted";
1280 folly::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION));
1283 int error = SSL_get_error(ssl_, bytes);
1284 if (error == SSL_ERROR_WANT_READ) {
1285 // The caller will register for read event if not already.
1286 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1287 return ReadResult(READ_BLOCKING);
1289 return ReadResult(READ_ERROR);
1291 } else if (error == SSL_ERROR_WANT_WRITE) {
1292 // TODO: Even though we are attempting to read data, SSL_read() may
1293 // need to write data if renegotiation is being performed. We currently
1294 // don't support this and just fail the read.
1295 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1296 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1297 << "): unsupported SSL renegotiation during read";
1300 folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1302 if (zero_return(error, bytes)) {
1303 return ReadResult(bytes);
1305 long errError = ERR_get_error();
1306 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1307 << "state=" << state_ << ", "
1308 << "sslState=" << sslState_ << ", "
1309 << "events=" << std::hex << eventFlags_ << "): "
1310 << "bytes: " << bytes << ", "
1311 << "error: " << error << ", "
1312 << "errno: " << errno << ", "
1313 << "func: " << ERR_func_error_string(errError) << ", "
1314 << "reason: " << ERR_reason_error_string(errError);
1317 folly::make_unique<SSLException>(error, errError, bytes, errno));
1320 appBytesReceived_ += bytes;
1321 return ReadResult(bytes);
1325 void AsyncSSLSocket::handleWrite() noexcept {
1326 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1327 << ", state=" << int(state_) << ", "
1328 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1329 if (state_ < StateEnum::ESTABLISHED) {
1330 return AsyncSocket::handleWrite();
1333 if (sslState_ == STATE_ACCEPTING) {
1339 if (sslState_ == STATE_CONNECTING) {
1346 AsyncSocket::handleWrite();
1349 AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {
1350 if (error == SSL_ERROR_WANT_READ) {
1351 // Even though we are attempting to write data, SSL_write() may
1352 // need to read data if renegotiation is being performed. We currently
1353 // don't support this and just fail the write.
1354 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1355 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1357 << "unsupported SSL renegotiation during write";
1360 folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1362 if (zero_return(error, rc)) {
1363 return WriteResult(0);
1365 auto errError = ERR_get_error();
1366 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1367 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1368 << "SSL error: " << error << ", errno: " << errno
1369 << ", func: " << ERR_func_error_string(errError)
1370 << ", reason: " << ERR_reason_error_string(errError);
1373 folly::make_unique<SSLException>(error, errError, rc, errno));
1377 AsyncSocket::WriteResult AsyncSSLSocket::performWrite(
1381 uint32_t* countWritten,
1382 uint32_t* partialWritten) {
1383 if (sslState_ == STATE_UNENCRYPTED) {
1384 return AsyncSocket::performWrite(
1385 vec, count, flags, countWritten, partialWritten);
1387 if (sslState_ != STATE_ESTABLISHED) {
1388 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1389 << ", sslState=" << sslState_
1390 << ", events=" << eventFlags_ << "): "
1391 << "TODO: AsyncSSLSocket currently does not support calling "
1392 << "write() before the handshake has fully completed";
1394 WRITE_ERROR, folly::make_unique<SSLException>(SSLError::EARLY_WRITE));
1397 // Declare a buffer used to hold small write requests. It could point to a
1398 // memory block either on stack or on heap. If it is on heap, we release it
1399 // manually when scope exits
1400 char* combinedBuf{nullptr};
1402 // Note, always keep this check consistent with what we do below
1403 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1404 delete[] combinedBuf;
1409 *partialWritten = 0;
1410 ssize_t totalWritten = 0;
1411 size_t bytesStolenFromNextBuffer = 0;
1412 for (uint32_t i = 0; i < count; i++) {
1413 const iovec* v = vec + i;
1414 size_t offset = bytesStolenFromNextBuffer;
1415 bytesStolenFromNextBuffer = 0;
1416 size_t len = v->iov_len - offset;
1422 buf = ((const char*)v->iov_base) + offset;
1425 uint32_t buffersStolen = 0;
1426 auto sslWriteBuf = buf;
1427 if ((len < minWriteSize_) && ((i + 1) < count)) {
1428 // Combine this buffer with part or all of the next buffers in
1429 // order to avoid really small-grained calls to SSL_write().
1430 // Each call to SSL_write() produces a separate record in
1431 // the egress SSL stream, and we've found that some low-end
1432 // mobile clients can't handle receiving an HTTP response
1433 // header and the first part of the response body in two
1434 // separate SSL records (even if those two records are in
1435 // the same TCP packet).
1437 if (combinedBuf == nullptr) {
1438 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1439 // Allocate the buffer on heap
1440 combinedBuf = new char[minWriteSize_];
1442 // Allocate the buffer on stack
1443 combinedBuf = (char*)alloca(minWriteSize_);
1446 assert(combinedBuf != nullptr);
1447 sslWriteBuf = combinedBuf;
1449 memcpy(combinedBuf, buf, len);
1451 // INVARIANT: i + buffersStolen == complete chunks serialized
1452 uint32_t nextIndex = i + buffersStolen + 1;
1453 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1454 minWriteSize_ - len);
1455 memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1456 bytesStolenFromNextBuffer);
1457 len += bytesStolenFromNextBuffer;
1458 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1459 // couldn't steal the whole buffer
1462 bytesStolenFromNextBuffer = 0;
1465 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1468 // Advance any empty buffers immediately after.
1469 if (bytesStolenFromNextBuffer == 0) {
1470 while ((i + buffersStolen + 1) < count &&
1471 vec[i + buffersStolen + 1].iov_len == 0) {
1477 isSet(flags, WriteFlags::CORK) || (i + buffersStolen + 1 < count);
1478 bytes = eorAwareSSLWrite(
1482 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1485 int error = SSL_get_error(ssl_, int(bytes));
1486 if (error == SSL_ERROR_WANT_WRITE) {
1487 // The caller will register for write event if not already.
1488 *partialWritten = uint32_t(offset);
1489 return WriteResult(totalWritten);
1491 auto writeResult = interpretSSLError(int(bytes), error);
1492 if (writeResult.writeReturn < 0) {
1494 } // else fall through to below to correctly record totalWritten
1497 totalWritten += bytes;
1499 if (bytes == (ssize_t)len) {
1500 // The full iovec is written.
1501 (*countWritten) += 1 + buffersStolen;
1505 bytes += offset; // adjust bytes to account for all of v
1506 while (bytes >= (ssize_t)v->iov_len) {
1507 // We combined this buf with part or all of the next one, and
1508 // we managed to write all of this buf but not all of the bytes
1509 // from the next one that we'd hoped to write.
1510 bytes -= v->iov_len;
1514 *partialWritten = uint32_t(bytes);
1515 return WriteResult(totalWritten);
1519 return WriteResult(totalWritten);
1522 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1524 if (eor && trackEor_) {
1525 if (appEorByteNo_) {
1526 // cannot track for more than one app byte EOR
1527 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1529 appEorByteNo_ = appBytesWritten_ + n;
1532 // 1. It is fine to keep updating minEorRawByteNo_.
1533 // 2. It is _min_ in the sense that SSL record will add some overhead.
1534 minEorRawByteNo_ = getRawBytesWritten() + n;
1537 n = sslWriteImpl(ssl, buf, n);
1539 appBytesWritten_ += n;
1540 if (appEorByteNo_) {
1541 if (getRawBytesWritten() >= minEorRawByteNo_) {
1542 minEorRawByteNo_ = 0;
1544 if(appBytesWritten_ == appEorByteNo_) {
1547 CHECK(appBytesWritten_ < appEorByteNo_);
1554 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) {
1555 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1556 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1557 sslSocket->renegotiateAttempted_ = true;
1559 if (where & SSL_CB_READ_ALERT) {
1560 const char* type = SSL_alert_type_string(ret);
1562 const char* desc = SSL_alert_desc_string(ret);
1563 sslSocket->alertsReceived_.emplace_back(
1564 *type, StringPiece(desc, std::strlen(desc)));
1569 int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) {
1573 AsyncSSLSocket* tsslSock;
1575 iov.iov_base = const_cast<char*>(in);
1577 memset(&msg, 0, sizeof(msg));
1581 auto appData = OpenSSLUtils::getBioAppData(b);
1584 tsslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1587 if (tsslSock->trackEor_ && tsslSock->minEorRawByteNo_ &&
1588 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1593 flags |= MSG_NOSIGNAL;
1597 if (tsslSock->corkCurrentWrite_) {
1602 auto result = tsslSock->sendSocketMessage(
1603 OpenSSLUtils::getBioFd(b, nullptr), &msg, flags);
1604 BIO_clear_retry_flags(b);
1605 if (!result.exception && result.writeReturn <= 0) {
1606 if (OpenSSLUtils::getBioShouldRetryWrite(int(result.writeReturn))) {
1607 BIO_set_retry_write(b);
1610 return int(result.writeReturn);
1613 int AsyncSSLSocket::bioRead(BIO* b, char* out, int outl) {
1617 BIO_clear_retry_flags(b);
1619 auto appData = OpenSSLUtils::getBioAppData(b);
1621 auto sslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1623 if (sslSock->preReceivedData_ && !sslSock->preReceivedData_->empty()) {
1624 VLOG(5) << "AsyncSSLSocket::bioRead() this=" << sslSock
1625 << ", reading pre-received data";
1627 Cursor cursor(sslSock->preReceivedData_.get());
1628 auto len = cursor.pullAtMost(out, outl);
1631 queue.append(std::move(sslSock->preReceivedData_));
1632 queue.trimStart(len);
1633 sslSock->preReceivedData_ = queue.move();
1636 auto result = recv(OpenSSLUtils::getBioFd(b, nullptr), out, outl, 0);
1637 if (result <= 0 && OpenSSLUtils::getBioShouldRetryWrite(result)) {
1638 BIO_set_retry_read(b);
1644 int AsyncSSLSocket::sslVerifyCallback(
1646 X509_STORE_CTX* x509Ctx) {
1647 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1648 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1649 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1651 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1652 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1653 return (self->handshakeCallback_) ?
1654 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1658 void AsyncSSLSocket::setPreReceivedData(std::unique_ptr<IOBuf> data) {
1659 CHECK(sslState_ == STATE_UNINIT || sslState_ == STATE_UNENCRYPTED);
1660 CHECK(!preReceivedData_);
1661 preReceivedData_ = std::move(data);
1664 void AsyncSSLSocket::enableClientHelloParsing() {
1665 parseClientHello_ = true;
1666 clientHelloInfo_.reset(new ssl::ClientHelloInfo());
1669 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1670 SSL_set_msg_callback(ssl, nullptr);
1671 SSL_set_msg_callback_arg(ssl, nullptr);
1672 clientHelloInfo_->clientHelloBuf_.clear();
1675 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1682 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1684 sock->resetClientHelloParsing(ssl);
1687 if (contentType != SSL3_RT_HANDSHAKE) {
1694 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1695 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1697 Cursor cursor(clientHelloBuf.front());
1698 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1699 sock->resetClientHelloParsing(ssl);
1703 if (cursor.totalLength() < 3) {
1704 clientHelloBuf.trimEnd(len);
1705 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1709 uint32_t messageLength = cursor.read<uint8_t>();
1710 messageLength <<= 8;
1711 messageLength |= cursor.read<uint8_t>();
1712 messageLength <<= 8;
1713 messageLength |= cursor.read<uint8_t>();
1714 if (cursor.totalLength() < messageLength) {
1715 clientHelloBuf.trimEnd(len);
1716 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1720 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1721 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1723 cursor.skip(4); // gmt_unix_time
1724 cursor.skip(28); // random_bytes
1726 cursor.skip(cursor.read<uint8_t>()); // session_id
1728 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1729 for (int i = 0; i < cipherSuitesLength; i += 2) {
1730 sock->clientHelloInfo_->
1731 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1734 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1735 for (int i = 0; i < compressionMethodsLength; ++i) {
1736 sock->clientHelloInfo_->
1737 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1740 if (cursor.totalLength() > 0) {
1741 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1742 while (extensionsLength) {
1743 ssl::TLSExtension extensionType =
1744 static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>());
1745 sock->clientHelloInfo_->
1746 clientHelloExtensions_.push_back(extensionType);
1747 extensionsLength -= 2;
1748 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1749 extensionsLength -= 2;
1750 extensionsLength -= extensionDataLength;
1752 if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) {
1754 extensionDataLength -= 2;
1755 while (extensionDataLength) {
1756 ssl::HashAlgorithm hashAlg =
1757 static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>());
1758 ssl::SignatureAlgorithm sigAlg =
1759 static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>());
1760 extensionDataLength -= 2;
1761 sock->clientHelloInfo_->
1762 clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1764 } else if (extensionType == ssl::TLSExtension::SUPPORTED_VERSIONS) {
1766 extensionDataLength -= 1;
1767 while (extensionDataLength) {
1768 sock->clientHelloInfo_->clientHelloSupportedVersions_.push_back(
1769 cursor.readBE<uint16_t>());
1770 extensionDataLength -= 2;
1773 cursor.skip(extensionDataLength);
1777 } catch (std::out_of_range&) {
1778 // we'll use what we found and cleanup below.
1779 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1780 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1783 sock->resetClientHelloParsing(ssl);
1786 void AsyncSSLSocket::getSSLClientCiphers(
1787 std::string& clientCiphers,
1788 bool convertToString) const {
1789 std::string ciphers;
1791 if (parseClientHello_ == false
1792 || clientHelloInfo_->clientHelloCipherSuites_.empty()) {
1798 for (auto originalCipherCode : clientHelloInfo_->clientHelloCipherSuites_)
1806 bool nameFound = convertToString;
1808 if (convertToString) {
1809 const auto& name = OpenSSLUtils::getCipherName(originalCipherCode);
1819 std::array<uint8_t, 2>{{
1820 static_cast<uint8_t>((originalCipherCode >> 8) & 0xffL),
1821 static_cast<uint8_t>(originalCipherCode & 0x00ffL) }},
1823 /* append to ciphers = */ true);
1827 clientCiphers = std::move(ciphers);
1830 std::string AsyncSSLSocket::getSSLClientComprMethods() const {
1831 if (!parseClientHello_) {
1834 return folly::join(":", clientHelloInfo_->clientHelloCompressionMethods_);
1837 std::string AsyncSSLSocket::getSSLClientExts() const {
1838 if (!parseClientHello_) {
1841 return folly::join(":", clientHelloInfo_->clientHelloExtensions_);
1844 std::string AsyncSSLSocket::getSSLClientSigAlgs() const {
1845 if (!parseClientHello_) {
1849 std::string sigAlgs;
1850 sigAlgs.reserve(clientHelloInfo_->clientHelloSigAlgs_.size() * 4);
1851 for (size_t i = 0; i < clientHelloInfo_->clientHelloSigAlgs_.size(); i++) {
1853 sigAlgs.push_back(':');
1855 sigAlgs.append(folly::to<std::string>(
1856 clientHelloInfo_->clientHelloSigAlgs_[i].first));
1857 sigAlgs.push_back(',');
1858 sigAlgs.append(folly::to<std::string>(
1859 clientHelloInfo_->clientHelloSigAlgs_[i].second));
1865 std::string AsyncSSLSocket::getSSLClientSupportedVersions() const {
1866 if (!parseClientHello_) {
1869 return folly::join(":", clientHelloInfo_->clientHelloSupportedVersions_);
1872 std::string AsyncSSLSocket::getSSLAlertsReceived() const {
1875 for (const auto& alert : alertsReceived_) {
1879 ret.append(folly::to<std::string>(alert.first, ": ", alert.second));
1885 void AsyncSSLSocket::getSSLSharedCiphers(std::string& sharedCiphers) const {
1886 char ciphersBuffer[1024];
1887 ciphersBuffer[0] = '\0';
1888 SSL_get_shared_ciphers(ssl_, ciphersBuffer, sizeof(ciphersBuffer) - 1);
1889 sharedCiphers = ciphersBuffer;
1892 void AsyncSSLSocket::getSSLServerCiphers(std::string& serverCiphers) const {
1893 serverCiphers = SSL_get_cipher_list(ssl_, 0);
1896 while ((cipher = SSL_get_cipher_list(ssl_, i)) != nullptr) {
1897 serverCiphers.append(":");
1898 serverCiphers.append(cipher);