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 <sys/types.h>
28 #include <folly/Bits.h>
29 #include <folly/SocketAddress.h>
30 #include <folly/SpinLock.h>
31 #include <folly/io/Cursor.h>
32 #include <folly/io/IOBuf.h>
33 #include <folly/portability/OpenSSL.h>
35 using folly::SocketAddress;
36 using folly::SSLContext;
38 using std::shared_ptr;
42 using folly::SpinLock;
43 using folly::SpinLockGuard;
44 using folly::io::Cursor;
45 using std::unique_ptr;
49 using folly::AsyncSocket;
50 using folly::AsyncSocketException;
51 using folly::AsyncSSLSocket;
52 using folly::Optional;
53 using folly::SSLContext;
54 // For OpenSSL portability API
55 using namespace folly::ssl;
56 using folly::ssl::OpenSSLUtils;
59 // We have one single dummy SSL context so that we can implement attach
60 // and detach methods in a thread safe fashion without modifying opnessl.
61 static SSLContext *dummyCtx = nullptr;
62 static SpinLock dummyCtxLock;
64 // If given min write size is less than this, buffer will be allocated on
65 // stack, otherwise it is allocated on heap
66 const size_t MAX_STACK_BUF_SIZE = 2048;
68 // This converts "illegal" shutdowns into ZERO_RETURN
69 inline bool zero_return(int error, int rc) {
70 return (error == SSL_ERROR_ZERO_RETURN || (rc == 0 && errno == 0));
73 class AsyncSSLSocketConnector: public AsyncSocket::ConnectCallback,
74 public AsyncSSLSocket::HandshakeCB {
77 AsyncSSLSocket *sslSocket_;
78 AsyncSSLSocket::ConnectCallback *callback_;
83 ~AsyncSSLSocketConnector() override {}
86 AsyncSSLSocketConnector(AsyncSSLSocket *sslSocket,
87 AsyncSocket::ConnectCallback *callback,
89 sslSocket_(sslSocket),
92 startTime_(std::chrono::duration_cast<std::chrono::milliseconds>(
93 std::chrono::steady_clock::now().time_since_epoch()).count()) {
96 void connectSuccess() noexcept override {
97 VLOG(7) << "client socket connected";
99 int64_t timeoutLeft = 0;
101 auto curTime = std::chrono::duration_cast<std::chrono::milliseconds>(
102 std::chrono::steady_clock::now().time_since_epoch()).count();
104 timeoutLeft = timeout_ - (curTime - startTime_);
105 if (timeoutLeft <= 0) {
106 AsyncSocketException ex(
107 AsyncSocketException::TIMED_OUT,
108 folly::sformat("SSL connect timed out after {}ms", timeout_));
114 sslSocket_->sslConn(this, std::chrono::milliseconds(timeoutLeft));
117 void connectErr(const AsyncSocketException& ex) noexcept override {
118 VLOG(1) << "TCP connect failed: " << ex.what();
123 void handshakeSuc(AsyncSSLSocket* /* sock */) noexcept override {
124 VLOG(7) << "client handshake success";
126 callback_->connectSuccess();
131 void handshakeErr(AsyncSSLSocket* /* socket */,
132 const AsyncSocketException& ex) noexcept override {
133 VLOG(1) << "client handshakeErr: " << ex.what();
138 void fail(const AsyncSocketException &ex) {
139 // fail is a noop if called twice
141 AsyncSSLSocket::ConnectCallback *cb = callback_;
145 sslSocket_->closeNow();
146 // closeNow can call handshakeErr if it hasn't been called already.
147 // So this may have been deleted, no member variable access beyond this
149 // Note that closeNow may invoke writeError callbacks if the socket had
150 // write data pending connection completion.
155 void setup_SSL_CTX(SSL_CTX *ctx) {
156 #ifdef SSL_MODE_RELEASE_BUFFERS
157 SSL_CTX_set_mode(ctx,
158 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
159 SSL_MODE_ENABLE_PARTIAL_WRITE
160 | SSL_MODE_RELEASE_BUFFERS
163 SSL_CTX_set_mode(ctx,
164 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
165 SSL_MODE_ENABLE_PARTIAL_WRITE
168 // SSL_CTX_set_mode is a Macro
169 #ifdef SSL_MODE_WRITE_IOVEC
170 SSL_CTX_set_mode(ctx,
171 SSL_CTX_get_mode(ctx)
172 | SSL_MODE_WRITE_IOVEC);
177 // Note: This is a Leaky Meyer's Singleton. The reason we can't use a non-leaky
178 // thing is because we will be setting this BIO_METHOD* inside BIOs owned by
179 // various SSL objects which may get callbacks even during teardown. We may
180 // eventually try to fix this
181 static BIO_METHOD* getSSLBioMethod() {
182 static auto const instance = OpenSSLUtils::newSocketBioMethod().release();
186 void* initsslBioMethod(void) {
187 auto sslBioMethod = getSSLBioMethod();
188 // override the bwrite method for MSG_EOR support
189 OpenSSLUtils::setCustomBioWriteMethod(sslBioMethod, AsyncSSLSocket::bioWrite);
190 OpenSSLUtils::setCustomBioReadMethod(sslBioMethod, AsyncSSLSocket::bioRead);
192 // Note that the sslBioMethod.type and sslBioMethod.name are not
193 // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
194 // then have specific handlings. The sslWriteBioWrite should be compatible
195 // with the one in openssl.
197 // Return something here to enable AsyncSSLSocket to call this method using
198 // a function-scoped static.
207 * Create a client AsyncSSLSocket
209 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
210 EventBase* evb, bool deferSecurityNegotiation) :
213 handshakeTimeout_(this, evb),
214 connectionTimeout_(this, evb) {
216 if (deferSecurityNegotiation) {
217 sslState_ = STATE_UNENCRYPTED;
222 * Create a server/client AsyncSSLSocket
224 AsyncSSLSocket::AsyncSSLSocket(
225 const shared_ptr<SSLContext>& ctx,
229 bool deferSecurityNegotiation)
230 : AsyncSocket(evb, fd),
233 handshakeTimeout_(this, evb),
234 connectionTimeout_(this, evb) {
235 noTransparentTls_ = true;
238 SSL_CTX_set_info_callback(
239 ctx_->getSSLCtx(), AsyncSSLSocket::sslInfoCallback);
241 if (deferSecurityNegotiation) {
242 sslState_ = STATE_UNENCRYPTED;
246 AsyncSSLSocket::AsyncSSLSocket(
247 const shared_ptr<SSLContext>& ctx,
248 AsyncSocket::UniquePtr oldAsyncSocket,
250 bool deferSecurityNegotiation)
251 : AsyncSocket(std::move(oldAsyncSocket)),
254 handshakeTimeout_(this, AsyncSocket::getEventBase()),
255 connectionTimeout_(this, AsyncSocket::getEventBase()) {
256 noTransparentTls_ = true;
259 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
260 AsyncSSLSocket::sslInfoCallback);
262 if (deferSecurityNegotiation) {
263 sslState_ = STATE_UNENCRYPTED;
267 #if FOLLY_OPENSSL_HAS_SNI
269 * Create a client AsyncSSLSocket and allow tlsext_hostname
270 * to be sent in Client Hello.
272 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
274 const std::string& serverName,
275 bool deferSecurityNegotiation) :
276 AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
277 tlsextHostname_ = serverName;
281 * Create a client AsyncSSLSocket from an already connected fd
282 * and allow tlsext_hostname to be sent in Client Hello.
284 AsyncSSLSocket::AsyncSSLSocket(
285 const shared_ptr<SSLContext>& ctx,
288 const std::string& serverName,
289 bool deferSecurityNegotiation)
290 : AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
291 tlsextHostname_ = serverName;
293 #endif // FOLLY_OPENSSL_HAS_SNI
295 AsyncSSLSocket::~AsyncSSLSocket() {
296 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
297 << ", evb=" << eventBase_ << ", fd=" << fd_
298 << ", state=" << int(state_) << ", sslState="
299 << sslState_ << ", events=" << eventFlags_ << ")";
302 void AsyncSSLSocket::init() {
303 // Do this here to ensure we initialize this once before any use of
304 // AsyncSSLSocket instances and not as part of library load.
305 static const auto sslBioMethodInitializer = initsslBioMethod();
306 (void)sslBioMethodInitializer;
308 setup_SSL_CTX(ctx_->getSSLCtx());
311 void AsyncSSLSocket::closeNow() {
312 // Close the SSL connection.
313 if (ssl_ != nullptr && fd_ != -1) {
314 int rc = SSL_shutdown(ssl_);
316 rc = SSL_shutdown(ssl_);
323 if (sslSession_ != nullptr) {
324 SSL_SESSION_free(sslSession_);
325 sslSession_ = nullptr;
328 sslState_ = STATE_CLOSED;
330 if (handshakeTimeout_.isScheduled()) {
331 handshakeTimeout_.cancelTimeout();
334 DestructorGuard dg(this);
337 AsyncSocketException(
338 AsyncSocketException::END_OF_FILE,
339 "SSL connection closed locally"));
341 if (ssl_ != nullptr) {
347 AsyncSocket::closeNow();
350 void AsyncSSLSocket::shutdownWrite() {
351 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
353 // (Performing a full shutdown here is more desirable than doing nothing at
354 // all. The purpose of shutdownWrite() is normally to notify the other end
355 // of the connection that no more data will be sent. If we do nothing, the
356 // other end will never know that no more data is coming, and this may result
357 // in protocol deadlock.)
361 void AsyncSSLSocket::shutdownWriteNow() {
365 bool AsyncSSLSocket::good() const {
366 return (AsyncSocket::good() &&
367 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
368 sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
371 // The TAsyncTransport definition of 'good' states that the transport is
372 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
373 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
374 // is connected but we haven't initiated the call to SSL_connect.
375 bool AsyncSSLSocket::connecting() const {
377 (AsyncSocket::connecting() ||
378 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
379 sslState_ == STATE_CONNECTING))));
382 std::string AsyncSSLSocket::getApplicationProtocol() noexcept {
383 const unsigned char* protoName = nullptr;
384 unsigned protoLength;
385 if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) {
386 return std::string(reinterpret_cast<const char*>(protoName), protoLength);
391 void AsyncSSLSocket::setEorTracking(bool track) {
392 if (isEorTrackingEnabled() != track) {
393 AsyncSocket::setEorTracking(track);
395 minEorRawByteNo_ = 0;
399 size_t AsyncSSLSocket::getRawBytesWritten() const {
400 // The bio(s) in the write path are in a chain
401 // each bio flushes to the next and finally written into the socket
402 // to get the rawBytesWritten on the socket,
403 // get the write bytes of the last bio
405 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
408 BIO* next = BIO_next(b);
409 while (next != nullptr) {
414 return BIO_number_written(b);
417 size_t AsyncSSLSocket::getRawBytesReceived() const {
419 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
423 return BIO_number_read(b);
427 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
428 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
429 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
430 << "events=" << eventFlags_ << ", server=" << short(server_)
431 << "): " << "sslAccept/Connect() called in invalid "
432 << "state, handshake callback " << handshakeCallback_
433 << ", new callback " << callback;
434 assert(!handshakeTimeout_.isScheduled());
435 sslState_ = STATE_ERROR;
437 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
438 "sslAccept() called with socket in invalid state");
440 handshakeEndTime_ = std::chrono::steady_clock::now();
442 callback->handshakeErr(this, ex);
445 failHandshake(__func__, ex);
448 void AsyncSSLSocket::sslAccept(
449 HandshakeCB* callback,
450 std::chrono::milliseconds timeout,
451 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
452 DestructorGuard dg(this);
453 eventBase_->dcheckIsInEventBaseThread();
454 verifyPeer_ = verifyPeer;
456 // Make sure we're in the uninitialized state
458 (sslState_ != STATE_UNINIT && sslState_ != STATE_UNENCRYPTED) ||
459 handshakeCallback_ != nullptr) {
460 return invalidState(callback);
463 // Cache local and remote socket addresses to keep them available
464 // after socket file descriptor is closed.
465 if (cacheAddrOnFailure_) {
469 handshakeStartTime_ = std::chrono::steady_clock::now();
470 // Make end time at least >= start time.
471 handshakeEndTime_ = handshakeStartTime_;
473 sslState_ = STATE_ACCEPTING;
474 handshakeCallback_ = callback;
476 if (timeout > std::chrono::milliseconds::zero()) {
477 handshakeTimeout_.scheduleTimeout(timeout);
480 /* register for a read operation (waiting for CLIENT HELLO) */
481 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
483 checkForImmediateRead();
486 void AsyncSSLSocket::attachSSLContext(
487 const std::shared_ptr<SSLContext>& ctx) {
489 // Check to ensure we are in client mode. Changing a server's ssl
490 // context doesn't make sense since clients of that server would likely
491 // become confused when the server's context changes.
495 DCHECK(ctx->getSSLCtx());
498 // It's possible this could be attached before ssl_ is set up
503 // In order to call attachSSLContext, detachSSLContext must have been
504 // previously called.
505 // We need to update the initial_ctx if necessary
506 // The 'initial_ctx' inside an SSL* points to the context that it was created
507 // with, which is also where session callbacks and servername callbacks
509 // When we switch to a different SSL_CTX, we want to update the initial_ctx as
510 // well so that any callbacks don't go to a different object
511 // NOTE: this will only work if we have access to ssl_ internals, so it may
513 // OpenSSL version >= 1.1.0
514 auto sslCtx = ctx->getSSLCtx();
515 OpenSSLUtils::setSSLInitialCtx(ssl_, sslCtx);
516 // Detach sets the socket's context to the dummy context. Thus we must acquire
518 SpinLockGuard guard(dummyCtxLock);
519 SSL_set_SSL_CTX(ssl_, sslCtx);
522 void AsyncSSLSocket::detachSSLContext() {
525 // It's possible for this to be called before ssl_ has been
530 // The 'initial_ctx' inside an SSL* points to the context that it was created
531 // with, which is also where session callbacks and servername callbacks
533 // Detach the initial_ctx as well. It will be reattached in attachSSLContext
534 // it is used for session info.
535 // NOTE: this will only work if we have access to ssl_ internals, so it may
537 // OpenSSL version >= 1.1.0
538 SSL_CTX* initialCtx = OpenSSLUtils::getSSLInitialCtx(ssl_);
540 SSL_CTX_free(initialCtx);
541 OpenSSLUtils::setSSLInitialCtx(ssl_, nullptr);
544 SpinLockGuard guard(dummyCtxLock);
545 if (nullptr == dummyCtx) {
546 // We need to lazily initialize the dummy context so we don't
547 // accidentally override any programmatic settings to openssl
548 dummyCtx = new SSLContext;
550 // We must remove this socket's references to its context right now
551 // since this socket could get passed to any thread. If the context has
552 // had its locking disabled, just doing a set in attachSSLContext()
553 // would not be thread safe.
554 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
557 #if FOLLY_OPENSSL_HAS_SNI
558 void AsyncSSLSocket::switchServerSSLContext(
559 const std::shared_ptr<SSLContext>& handshakeCtx) {
561 if (sslState_ != STATE_ACCEPTING) {
562 // We log it here and allow the switch.
563 // It should not affect our re-negotiation support (which
564 // is not supported now).
565 VLOG(6) << "fd=" << getFd()
566 << " renegotation detected when switching SSL_CTX";
569 setup_SSL_CTX(handshakeCtx->getSSLCtx());
570 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
571 AsyncSSLSocket::sslInfoCallback);
572 handshakeCtx_ = handshakeCtx;
573 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
576 bool AsyncSSLSocket::isServerNameMatch() const {
583 SSL_SESSION *ss = SSL_get_session(ssl_);
588 auto tlsextHostname = SSL_SESSION_get0_hostname(ss);
589 return (tlsextHostname && !tlsextHostname_.compare(tlsextHostname));
592 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
593 tlsextHostname_ = std::move(serverName);
596 #endif // FOLLY_OPENSSL_HAS_SNI
598 void AsyncSSLSocket::timeoutExpired(
599 std::chrono::milliseconds timeout) noexcept {
600 if (state_ == StateEnum::ESTABLISHED &&
601 (sslState_ == STATE_CACHE_LOOKUP || sslState_ == STATE_ASYNC_PENDING)) {
602 sslState_ = STATE_ERROR;
603 // We are expecting a callback in restartSSLAccept. The cache lookup
604 // and rsa-call necessarily have pointers to this ssl socket, so delay
605 // the cleanup until he calls us back.
606 } else if (state_ == StateEnum::CONNECTING) {
607 assert(sslState_ == STATE_CONNECTING);
608 DestructorGuard dg(this);
609 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
610 "Fallback connect timed out during TFO");
611 failHandshake(__func__, ex);
613 assert(state_ == StateEnum::ESTABLISHED &&
614 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
615 DestructorGuard dg(this);
616 AsyncSocketException ex(
617 AsyncSocketException::TIMED_OUT,
619 "SSL {} timed out after {}ms",
620 (sslState_ == STATE_CONNECTING) ? "connect" : "accept",
622 failHandshake(__func__, ex);
626 int AsyncSSLSocket::getSSLExDataIndex() {
627 static auto index = SSL_get_ex_new_index(
628 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
632 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
633 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
634 getSSLExDataIndex()));
637 void AsyncSSLSocket::failHandshake(const char* /* fn */,
638 const AsyncSocketException& ex) {
640 if (handshakeTimeout_.isScheduled()) {
641 handshakeTimeout_.cancelTimeout();
643 invokeHandshakeErr(ex);
647 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
648 handshakeEndTime_ = std::chrono::steady_clock::now();
649 if (handshakeCallback_ != nullptr) {
650 HandshakeCB* callback = handshakeCallback_;
651 handshakeCallback_ = nullptr;
652 callback->handshakeErr(this, ex);
656 void AsyncSSLSocket::invokeHandshakeCB() {
657 handshakeEndTime_ = std::chrono::steady_clock::now();
658 if (handshakeTimeout_.isScheduled()) {
659 handshakeTimeout_.cancelTimeout();
661 if (handshakeCallback_) {
662 HandshakeCB* callback = handshakeCallback_;
663 handshakeCallback_ = nullptr;
664 callback->handshakeSuc(this);
668 void AsyncSSLSocket::connect(
669 ConnectCallback* callback,
670 const folly::SocketAddress& address,
672 const OptionMap& options,
673 const folly::SocketAddress& bindAddr) noexcept {
674 auto timeoutChrono = std::chrono::milliseconds(timeout);
675 connect(callback, address, timeoutChrono, timeoutChrono, options, bindAddr);
678 void AsyncSSLSocket::connect(
679 ConnectCallback* callback,
680 const folly::SocketAddress& address,
681 std::chrono::milliseconds connectTimeout,
682 std::chrono::milliseconds totalConnectTimeout,
683 const OptionMap& options,
684 const folly::SocketAddress& bindAddr) noexcept {
686 assert(state_ == StateEnum::UNINIT);
687 assert(sslState_ == STATE_UNINIT || sslState_ == STATE_UNENCRYPTED);
688 noTransparentTls_ = true;
689 totalConnectTimeout_ = totalConnectTimeout;
690 if (sslState_ != STATE_UNENCRYPTED) {
691 callback = new AsyncSSLSocketConnector(
692 this, callback, int(totalConnectTimeout.count()));
694 AsyncSocket::connect(
695 callback, address, int(connectTimeout.count()), options, bindAddr);
698 bool AsyncSSLSocket::needsPeerVerification() const {
699 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
700 return ctx_->needsPeerVerification();
703 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
704 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
707 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
708 // apply the settings specified in verifyPeer_
709 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
710 if(ctx_->needsPeerVerification()) {
711 SSL_set_verify(ssl, ctx_->getVerificationMode(),
712 AsyncSSLSocket::sslVerifyCallback);
715 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
716 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
717 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
718 AsyncSSLSocket::sslVerifyCallback);
723 bool AsyncSSLSocket::setupSSLBio() {
724 auto sslBio = BIO_new(getSSLBioMethod());
730 OpenSSLUtils::setBioAppData(sslBio, this);
731 OpenSSLUtils::setBioFd(sslBio, fd_, BIO_NOCLOSE);
732 SSL_set_bio(ssl_, sslBio, sslBio);
736 void AsyncSSLSocket::sslConn(
737 HandshakeCB* callback,
738 std::chrono::milliseconds timeout,
739 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
740 DestructorGuard dg(this);
741 eventBase_->dcheckIsInEventBaseThread();
743 // Cache local and remote socket addresses to keep them available
744 // after socket file descriptor is closed.
745 if (cacheAddrOnFailure_) {
749 verifyPeer_ = verifyPeer;
751 // Make sure we're in the uninitialized state
752 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
753 STATE_UNENCRYPTED) ||
754 handshakeCallback_ != nullptr) {
755 return invalidState(callback);
758 sslState_ = STATE_CONNECTING;
759 handshakeCallback_ = callback;
762 ssl_ = ctx_->createSSL();
763 } catch (std::exception &e) {
764 sslState_ = STATE_ERROR;
765 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
766 "error calling SSLContext::createSSL()");
767 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
768 << fd_ << "): " << e.what();
769 return failHandshake(__func__, ex);
772 if (!setupSSLBio()) {
773 sslState_ = STATE_ERROR;
774 AsyncSocketException ex(
775 AsyncSocketException::INTERNAL_ERROR, "error creating SSL bio");
776 return failHandshake(__func__, ex);
779 applyVerificationOptions(ssl_);
781 if (sslSession_ != nullptr) {
782 sessionResumptionAttempted_ = true;
783 SSL_set_session(ssl_, sslSession_);
784 SSL_SESSION_free(sslSession_);
785 sslSession_ = nullptr;
787 #if FOLLY_OPENSSL_HAS_SNI
788 if (tlsextHostname_.size()) {
789 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
793 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
795 handshakeConnectTimeout_ = timeout;
799 // This could be called multiple times, during normal ssl connections
800 // and after TFO fallback.
801 void AsyncSSLSocket::startSSLConnect() {
802 handshakeStartTime_ = std::chrono::steady_clock::now();
803 // Make end time at least >= start time.
804 handshakeEndTime_ = handshakeStartTime_;
805 if (handshakeConnectTimeout_ > std::chrono::milliseconds::zero()) {
806 handshakeTimeout_.scheduleTimeout(handshakeConnectTimeout_);
811 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
812 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
813 return SSL_get1_session(ssl_);
819 const SSL* AsyncSSLSocket::getSSL() const {
823 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
824 sslSession_ = session;
825 if (!takeOwnership && session != nullptr) {
826 // Increment the reference count
827 // This API exists in BoringSSL and OpenSSL 1.1.0
828 SSL_SESSION_up_ref(session);
832 void AsyncSSLSocket::getSelectedNextProtocol(
833 const unsigned char** protoName,
835 SSLContext::NextProtocolType* protoType) const {
836 if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
837 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
838 "NPN not supported");
842 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
843 const unsigned char** protoName,
845 SSLContext::NextProtocolType* protoType) const {
846 *protoName = nullptr;
848 #if FOLLY_OPENSSL_HAS_ALPN
849 SSL_get0_alpn_selected(ssl_, protoName, protoLen);
852 *protoType = SSLContext::NextProtocolType::ALPN;
857 #ifdef OPENSSL_NPN_NEGOTIATED
858 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
860 *protoType = SSLContext::NextProtocolType::NPN;
869 bool AsyncSSLSocket::getSSLSessionReused() const {
870 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
871 return SSL_session_reused(ssl_);
876 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
877 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
881 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
882 if (ssl == nullptr) {
885 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
886 return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
892 const char *AsyncSSLSocket::getSSLServerName() const {
893 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
894 return getSSLServerNameFromSSL(ssl_);
896 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
897 "SNI not supported");
901 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
902 return getSSLServerNameFromSSL(ssl_);
905 int AsyncSSLSocket::getSSLVersion() const {
906 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
909 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
910 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
912 int nid = X509_get_signature_nid(cert);
913 return OBJ_nid2ln(nid);
918 int AsyncSSLSocket::getSSLCertSize() const {
920 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
922 EVP_PKEY *key = X509_get_pubkey(cert);
923 certSize = EVP_PKEY_bits(key);
929 const X509* AsyncSSLSocket::getSelfCert() const {
930 return (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
933 bool AsyncSSLSocket::willBlock(int ret,
935 unsigned long* errErrorOut) noexcept {
937 int error = *sslErrorOut = SSL_get_error(ssl_, ret);
938 if (error == SSL_ERROR_WANT_READ) {
939 // Register for read event if not already.
940 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
942 } else if (error == SSL_ERROR_WANT_WRITE) {
943 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
944 << ", state=" << int(state_) << ", sslState="
945 << sslState_ << ", events=" << eventFlags_ << "): "
946 << "SSL_ERROR_WANT_WRITE";
947 // Register for write event if not already.
948 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
950 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
951 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
952 // We will block but we can't register our own socket. The callback that
953 // triggered this code will re-call handleAccept at the appropriate time.
955 // We can only get here if the linked libssl.so has support for this feature
956 // as well, otherwise SSL_get_error cannot return our error code.
957 sslState_ = STATE_CACHE_LOOKUP;
959 // Unregister for all events while blocked here
960 updateEventRegistration(EventHandler::NONE,
961 EventHandler::READ | EventHandler::WRITE);
963 // The timeout (if set) keeps running here
967 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
968 || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
970 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
971 || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
974 // Our custom openssl function has kicked off an async request to do
975 // rsa/ecdsa private key operation. When that call returns, a callback will
976 // be invoked that will re-call handleAccept.
977 sslState_ = STATE_ASYNC_PENDING;
979 // Unregister for all events while blocked here
980 updateEventRegistration(
982 EventHandler::READ | EventHandler::WRITE
985 // The timeout (if set) keeps running here
988 unsigned long lastError = *errErrorOut = ERR_get_error();
989 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
990 << "state=" << state_ << ", "
991 << "sslState=" << sslState_ << ", "
992 << "events=" << std::hex << eventFlags_ << "): "
993 << "SSL error: " << error << ", "
994 << "errno: " << errno << ", "
995 << "ret: " << ret << ", "
996 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
997 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
998 << "func: " << ERR_func_error_string(lastError) << ", "
999 << "reason: " << ERR_reason_error_string(lastError);
1004 void AsyncSSLSocket::checkForImmediateRead() noexcept {
1005 // openssl may have buffered data that it read from the socket already.
1006 // In this case we have to process it immediately, rather than waiting for
1007 // the socket to become readable again.
1008 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
1009 AsyncSocket::handleRead();
1011 AsyncSocket::checkForImmediateRead();
1016 AsyncSSLSocket::restartSSLAccept()
1018 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this
1019 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1020 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1021 DestructorGuard dg(this);
1023 sslState_ == STATE_CACHE_LOOKUP ||
1024 sslState_ == STATE_ASYNC_PENDING ||
1025 sslState_ == STATE_ERROR ||
1026 sslState_ == STATE_CLOSED);
1027 if (sslState_ == STATE_CLOSED) {
1028 // I sure hope whoever closed this socket didn't delete it already,
1029 // but this is not strictly speaking an error
1032 if (sslState_ == STATE_ERROR) {
1033 // go straight to fail if timeout expired during lookup
1034 AsyncSocketException ex(
1035 AsyncSocketException::TIMED_OUT, "SSL accept timed out");
1036 failHandshake(__func__, ex);
1039 sslState_ = STATE_ACCEPTING;
1040 this->handleAccept();
1044 AsyncSSLSocket::handleAccept() noexcept {
1045 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
1046 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1047 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1049 assert(state_ == StateEnum::ESTABLISHED &&
1050 sslState_ == STATE_ACCEPTING);
1052 /* lazily create the SSL structure */
1054 ssl_ = ctx_->createSSL();
1055 } catch (std::exception &e) {
1056 sslState_ = STATE_ERROR;
1057 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1058 "error calling SSLContext::createSSL()");
1059 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
1060 << ", fd=" << fd_ << "): " << e.what();
1061 return failHandshake(__func__, ex);
1064 if (!setupSSLBio()) {
1065 sslState_ = STATE_ERROR;
1066 AsyncSocketException ex(
1067 AsyncSocketException::INTERNAL_ERROR, "error creating write bio");
1068 return failHandshake(__func__, ex);
1071 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
1073 applyVerificationOptions(ssl_);
1076 if (server_ && parseClientHello_) {
1077 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1078 SSL_set_msg_callback_arg(ssl_, this);
1081 int ret = SSL_accept(ssl_);
1084 unsigned long errError;
1085 int errnoCopy = errno;
1086 if (willBlock(ret, &sslError, &errError)) {
1089 sslState_ = STATE_ERROR;
1090 SSLException ex(sslError, errError, ret, errnoCopy);
1091 return failHandshake(__func__, ex);
1095 handshakeComplete_ = true;
1096 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1098 // Move into STATE_ESTABLISHED in the normal case that we are in
1100 sslState_ = STATE_ESTABLISHED;
1102 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1103 << " successfully accepted; state=" << int(state_)
1104 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1106 // Remember the EventBase we are attached to, before we start invoking any
1107 // callbacks (since the callbacks may call detachEventBase()).
1108 EventBase* originalEventBase = eventBase_;
1110 // Call the accept callback.
1111 invokeHandshakeCB();
1113 // Note that the accept callback may have changed our state.
1114 // (set or unset the read callback, called write(), closed the socket, etc.)
1115 // The following code needs to handle these situations correctly.
1117 // If the socket has been closed, readCallback_ and writeReqHead_ will
1118 // always be nullptr, so that will prevent us from trying to read or write.
1120 // The main thing to check for is if eventBase_ is still originalEventBase.
1121 // If not, we have been detached from this event base, so we shouldn't
1122 // perform any more operations.
1123 if (eventBase_ != originalEventBase) {
1127 AsyncSocket::handleInitialReadWrite();
1131 AsyncSSLSocket::handleConnect() noexcept {
1132 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1133 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1134 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1136 if (state_ < StateEnum::ESTABLISHED) {
1137 return AsyncSocket::handleConnect();
1141 (state_ == StateEnum::FAST_OPEN || state_ == StateEnum::ESTABLISHED) &&
1142 sslState_ == STATE_CONNECTING);
1145 auto originalState = state_;
1146 int ret = SSL_connect(ssl_);
1149 unsigned long errError;
1150 int errnoCopy = errno;
1151 if (willBlock(ret, &sslError, &errError)) {
1152 // We fell back to connecting state due to TFO
1153 if (state_ == StateEnum::CONNECTING) {
1154 DCHECK_EQ(StateEnum::FAST_OPEN, originalState);
1155 if (handshakeTimeout_.isScheduled()) {
1156 handshakeTimeout_.cancelTimeout();
1161 sslState_ = STATE_ERROR;
1162 SSLException ex(sslError, errError, ret, errnoCopy);
1163 return failHandshake(__func__, ex);
1167 handshakeComplete_ = true;
1168 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1170 // Move into STATE_ESTABLISHED in the normal case that we are in
1171 // STATE_CONNECTING.
1172 sslState_ = STATE_ESTABLISHED;
1174 VLOG(3) << "AsyncSSLSocket " << this << ": "
1175 << "fd " << fd_ << " successfully connected; "
1176 << "state=" << int(state_) << ", sslState=" << sslState_
1177 << ", events=" << eventFlags_;
1179 // Remember the EventBase we are attached to, before we start invoking any
1180 // callbacks (since the callbacks may call detachEventBase()).
1181 EventBase* originalEventBase = eventBase_;
1183 // Call the handshake callback.
1184 invokeHandshakeCB();
1186 // Note that the connect callback may have changed our state.
1187 // (set or unset the read callback, called write(), closed the socket, etc.)
1188 // The following code needs to handle these situations correctly.
1190 // If the socket has been closed, readCallback_ and writeReqHead_ will
1191 // always be nullptr, so that will prevent us from trying to read or write.
1193 // The main thing to check for is if eventBase_ is still originalEventBase.
1194 // If not, we have been detached from this event base, so we shouldn't
1195 // perform any more operations.
1196 if (eventBase_ != originalEventBase) {
1200 AsyncSocket::handleInitialReadWrite();
1203 void AsyncSSLSocket::invokeConnectErr(const AsyncSocketException& ex) {
1204 connectionTimeout_.cancelTimeout();
1205 AsyncSocket::invokeConnectErr(ex);
1206 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1207 if (handshakeTimeout_.isScheduled()) {
1208 handshakeTimeout_.cancelTimeout();
1210 // If we fell back to connecting state during TFO and the connection
1211 // failed, it would be an SSL failure as well.
1212 invokeHandshakeErr(ex);
1216 void AsyncSSLSocket::invokeConnectSuccess() {
1217 connectionTimeout_.cancelTimeout();
1218 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1219 assert(tfoAttempted_);
1220 // If we failed TFO, we'd fall back to trying to connect the socket,
1221 // to setup things like timeouts.
1224 // still invoke the base class since it re-sets the connect time.
1225 AsyncSocket::invokeConnectSuccess();
1228 void AsyncSSLSocket::scheduleConnectTimeout() {
1229 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1230 // We fell back from TFO, and need to set the timeouts.
1231 // We will not have a connect callback in this case, thus if the timer
1232 // expires we would have no-one to notify.
1233 // Thus we should reset even the connect timers to point to the handshake
1235 assert(connectCallback_ == nullptr);
1236 // We use a different connect timeout here than the handshake timeout, so
1237 // that we can disambiguate the 2 timers.
1238 if (connectTimeout_.count() > 0) {
1239 if (!connectionTimeout_.scheduleTimeout(connectTimeout_)) {
1240 throw AsyncSocketException(
1241 AsyncSocketException::INTERNAL_ERROR,
1242 withAddr("failed to schedule AsyncSSLSocket connect timeout"));
1247 AsyncSocket::scheduleConnectTimeout();
1250 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1251 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1252 // turn on the buffer movable in openssl
1253 if (bufferMovableEnabled_ && ssl_ != nullptr && !isBufferMovable_ &&
1254 callback != nullptr && callback->isBufferMovable()) {
1255 SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1256 isBufferMovable_ = true;
1260 AsyncSocket::setReadCB(callback);
1263 void AsyncSSLSocket::setBufferMovableEnabled(bool enabled) {
1264 bufferMovableEnabled_ = enabled;
1267 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1268 CHECK(readCallback_);
1269 if (isBufferMovable_) {
1273 // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1274 readCallback_->getReadBuffer(buf, buflen);
1279 AsyncSSLSocket::handleRead() noexcept {
1280 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1281 << ", state=" << int(state_) << ", "
1282 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1283 if (state_ < StateEnum::ESTABLISHED) {
1284 return AsyncSocket::handleRead();
1288 if (sslState_ == STATE_ACCEPTING) {
1293 else if (sslState_ == STATE_CONNECTING) {
1300 AsyncSocket::handleRead();
1303 AsyncSocket::ReadResult
1304 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1305 VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf
1306 << ", buflen=" << *buflen;
1308 if (sslState_ == STATE_UNENCRYPTED) {
1309 return AsyncSocket::performRead(buf, buflen, offset);
1313 if (!isBufferMovable_) {
1314 bytes = SSL_read(ssl_, *buf, int(*buflen));
1316 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1318 bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1322 if (server_ && renegotiateAttempted_) {
1323 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1324 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1325 << "): client intitiated SSL renegotiation not permitted";
1328 std::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION));
1331 int error = SSL_get_error(ssl_, bytes);
1332 if (error == SSL_ERROR_WANT_READ) {
1333 // The caller will register for read event if not already.
1334 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1335 return ReadResult(READ_BLOCKING);
1337 return ReadResult(READ_ERROR);
1339 } else if (error == SSL_ERROR_WANT_WRITE) {
1340 // TODO: Even though we are attempting to read data, SSL_read() may
1341 // need to write data if renegotiation is being performed. We currently
1342 // don't support this and just fail the read.
1343 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1344 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1345 << "): unsupported SSL renegotiation during read";
1348 std::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1350 if (zero_return(error, bytes)) {
1351 return ReadResult(bytes);
1353 auto errError = ERR_get_error();
1354 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1355 << "state=" << state_ << ", "
1356 << "sslState=" << sslState_ << ", "
1357 << "events=" << std::hex << eventFlags_ << "): "
1358 << "bytes: " << bytes << ", "
1359 << "error: " << error << ", "
1360 << "errno: " << errno << ", "
1361 << "func: " << ERR_func_error_string(errError) << ", "
1362 << "reason: " << ERR_reason_error_string(errError);
1365 std::make_unique<SSLException>(error, errError, bytes, errno));
1368 appBytesReceived_ += bytes;
1369 return ReadResult(bytes);
1373 void AsyncSSLSocket::handleWrite() noexcept {
1374 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1375 << ", state=" << int(state_) << ", "
1376 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1377 if (state_ < StateEnum::ESTABLISHED) {
1378 return AsyncSocket::handleWrite();
1381 if (sslState_ == STATE_ACCEPTING) {
1387 if (sslState_ == STATE_CONNECTING) {
1394 AsyncSocket::handleWrite();
1397 AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {
1398 if (error == SSL_ERROR_WANT_READ) {
1399 // Even though we are attempting to write data, SSL_write() may
1400 // need to read data if renegotiation is being performed. We currently
1401 // don't support this and just fail the write.
1402 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1403 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1405 << "unsupported SSL renegotiation during write";
1408 std::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1410 if (zero_return(error, rc)) {
1411 return WriteResult(0);
1413 auto errError = ERR_get_error();
1414 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1415 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1416 << "SSL error: " << error << ", errno: " << errno
1417 << ", func: " << ERR_func_error_string(errError)
1418 << ", reason: " << ERR_reason_error_string(errError);
1421 std::make_unique<SSLException>(error, errError, rc, errno));
1425 AsyncSocket::WriteResult AsyncSSLSocket::performWrite(
1429 uint32_t* countWritten,
1430 uint32_t* partialWritten) {
1431 if (sslState_ == STATE_UNENCRYPTED) {
1432 return AsyncSocket::performWrite(
1433 vec, count, flags, countWritten, partialWritten);
1435 if (sslState_ != STATE_ESTABLISHED) {
1436 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1437 << ", sslState=" << sslState_
1438 << ", events=" << eventFlags_ << "): "
1439 << "TODO: AsyncSSLSocket currently does not support calling "
1440 << "write() before the handshake has fully completed";
1442 WRITE_ERROR, std::make_unique<SSLException>(SSLError::EARLY_WRITE));
1445 // Declare a buffer used to hold small write requests. It could point to a
1446 // memory block either on stack or on heap. If it is on heap, we release it
1447 // manually when scope exits
1448 char* combinedBuf{nullptr};
1450 // Note, always keep this check consistent with what we do below
1451 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1452 delete[] combinedBuf;
1457 *partialWritten = 0;
1458 ssize_t totalWritten = 0;
1459 size_t bytesStolenFromNextBuffer = 0;
1460 for (uint32_t i = 0; i < count; i++) {
1461 const iovec* v = vec + i;
1462 size_t offset = bytesStolenFromNextBuffer;
1463 bytesStolenFromNextBuffer = 0;
1464 size_t len = v->iov_len - offset;
1470 buf = ((const char*)v->iov_base) + offset;
1473 uint32_t buffersStolen = 0;
1474 auto sslWriteBuf = buf;
1475 if ((len < minWriteSize_) && ((i + 1) < count)) {
1476 // Combine this buffer with part or all of the next buffers in
1477 // order to avoid really small-grained calls to SSL_write().
1478 // Each call to SSL_write() produces a separate record in
1479 // the egress SSL stream, and we've found that some low-end
1480 // mobile clients can't handle receiving an HTTP response
1481 // header and the first part of the response body in two
1482 // separate SSL records (even if those two records are in
1483 // the same TCP packet).
1485 if (combinedBuf == nullptr) {
1486 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1487 // Allocate the buffer on heap
1488 combinedBuf = new char[minWriteSize_];
1490 // Allocate the buffer on stack
1491 combinedBuf = (char*)alloca(minWriteSize_);
1494 assert(combinedBuf != nullptr);
1495 sslWriteBuf = combinedBuf;
1497 memcpy(combinedBuf, buf, len);
1499 // INVARIANT: i + buffersStolen == complete chunks serialized
1500 uint32_t nextIndex = i + buffersStolen + 1;
1501 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1502 minWriteSize_ - len);
1503 if (bytesStolenFromNextBuffer > 0) {
1504 assert(vec[nextIndex].iov_base != nullptr);
1507 vec[nextIndex].iov_base,
1508 bytesStolenFromNextBuffer);
1510 len += bytesStolenFromNextBuffer;
1511 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1512 // couldn't steal the whole buffer
1515 bytesStolenFromNextBuffer = 0;
1518 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1521 // Advance any empty buffers immediately after.
1522 if (bytesStolenFromNextBuffer == 0) {
1523 while ((i + buffersStolen + 1) < count &&
1524 vec[i + buffersStolen + 1].iov_len == 0) {
1530 isSet(flags, WriteFlags::CORK) || (i + buffersStolen + 1 < count);
1531 bytes = eorAwareSSLWrite(
1535 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1538 int error = SSL_get_error(ssl_, int(bytes));
1539 if (error == SSL_ERROR_WANT_WRITE) {
1540 // The caller will register for write event if not already.
1541 *partialWritten = uint32_t(offset);
1542 return WriteResult(totalWritten);
1544 auto writeResult = interpretSSLError(int(bytes), error);
1545 if (writeResult.writeReturn < 0) {
1547 } // else fall through to below to correctly record totalWritten
1550 totalWritten += bytes;
1552 if (bytes == (ssize_t)len) {
1553 // The full iovec is written.
1554 (*countWritten) += 1 + buffersStolen;
1558 bytes += offset; // adjust bytes to account for all of v
1559 while (bytes >= (ssize_t)v->iov_len) {
1560 // We combined this buf with part or all of the next one, and
1561 // we managed to write all of this buf but not all of the bytes
1562 // from the next one that we'd hoped to write.
1563 bytes -= v->iov_len;
1567 *partialWritten = uint32_t(bytes);
1568 return WriteResult(totalWritten);
1572 return WriteResult(totalWritten);
1575 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1577 if (eor && isEorTrackingEnabled()) {
1578 if (appEorByteNo_) {
1579 // cannot track for more than one app byte EOR
1580 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1582 appEorByteNo_ = appBytesWritten_ + n;
1585 // 1. It is fine to keep updating minEorRawByteNo_.
1586 // 2. It is _min_ in the sense that SSL record will add some overhead.
1587 minEorRawByteNo_ = getRawBytesWritten() + n;
1590 n = sslWriteImpl(ssl, buf, n);
1592 appBytesWritten_ += n;
1593 if (appEorByteNo_) {
1594 if (getRawBytesWritten() >= minEorRawByteNo_) {
1595 minEorRawByteNo_ = 0;
1597 if(appBytesWritten_ == appEorByteNo_) {
1600 CHECK(appBytesWritten_ < appEorByteNo_);
1607 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) {
1608 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1609 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1610 sslSocket->renegotiateAttempted_ = true;
1612 if (where & SSL_CB_READ_ALERT) {
1613 const char* type = SSL_alert_type_string(ret);
1615 const char* desc = SSL_alert_desc_string(ret);
1616 sslSocket->alertsReceived_.emplace_back(
1617 *type, StringPiece(desc, std::strlen(desc)));
1622 int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) {
1625 AsyncSSLSocket* tsslSock;
1627 iov.iov_base = const_cast<char*>(in);
1628 iov.iov_len = size_t(inl);
1629 memset(&msg, 0, sizeof(msg));
1633 auto appData = OpenSSLUtils::getBioAppData(b);
1636 tsslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1639 WriteFlags flags = WriteFlags::NONE;
1640 if (tsslSock->isEorTrackingEnabled() && tsslSock->minEorRawByteNo_ &&
1641 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1642 flags |= WriteFlags::EOR;
1645 if (tsslSock->corkCurrentWrite_) {
1646 flags |= WriteFlags::CORK;
1649 int msg_flags = tsslSock->getSendMsgParamsCB()->getFlags(flags);
1650 msg.msg_controllen =
1651 tsslSock->getSendMsgParamsCB()->getAncillaryDataSize(flags);
1652 CHECK_GE(AsyncSocket::SendMsgParamsCallback::maxAncillaryDataSize,
1653 msg.msg_controllen);
1654 if (msg.msg_controllen != 0) {
1655 msg.msg_control = reinterpret_cast<char*>(alloca(msg.msg_controllen));
1656 tsslSock->getSendMsgParamsCB()->getAncillaryData(flags, msg.msg_control);
1659 auto result = tsslSock->sendSocketMessage(
1660 OpenSSLUtils::getBioFd(b, nullptr), &msg, msg_flags);
1661 BIO_clear_retry_flags(b);
1662 if (!result.exception && result.writeReturn <= 0) {
1663 if (OpenSSLUtils::getBioShouldRetryWrite(int(result.writeReturn))) {
1664 BIO_set_retry_write(b);
1667 return int(result.writeReturn);
1670 int AsyncSSLSocket::bioRead(BIO* b, char* out, int outl) {
1674 BIO_clear_retry_flags(b);
1676 auto appData = OpenSSLUtils::getBioAppData(b);
1678 auto sslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1680 if (sslSock->preReceivedData_ && !sslSock->preReceivedData_->empty()) {
1681 VLOG(5) << "AsyncSSLSocket::bioRead() this=" << sslSock
1682 << ", reading pre-received data";
1684 Cursor cursor(sslSock->preReceivedData_.get());
1685 auto len = cursor.pullAtMost(out, outl);
1688 queue.append(std::move(sslSock->preReceivedData_));
1689 queue.trimStart(len);
1690 sslSock->preReceivedData_ = queue.move();
1691 return static_cast<int>(len);
1693 auto result = int(recv(OpenSSLUtils::getBioFd(b, nullptr), out, outl, 0));
1694 if (result <= 0 && OpenSSLUtils::getBioShouldRetryWrite(result)) {
1695 BIO_set_retry_read(b);
1701 int AsyncSSLSocket::sslVerifyCallback(
1703 X509_STORE_CTX* x509Ctx) {
1704 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1705 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1706 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1708 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1709 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1710 return (self->handshakeCallback_) ?
1711 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1715 void AsyncSSLSocket::enableClientHelloParsing() {
1716 parseClientHello_ = true;
1717 clientHelloInfo_.reset(new ssl::ClientHelloInfo());
1720 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1721 SSL_set_msg_callback(ssl, nullptr);
1722 SSL_set_msg_callback_arg(ssl, nullptr);
1723 clientHelloInfo_->clientHelloBuf_.clear();
1726 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1733 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1735 sock->resetClientHelloParsing(ssl);
1738 if (contentType != SSL3_RT_HANDSHAKE) {
1745 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1746 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1748 Cursor cursor(clientHelloBuf.front());
1749 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1750 sock->resetClientHelloParsing(ssl);
1754 if (cursor.totalLength() < 3) {
1755 clientHelloBuf.trimEnd(len);
1756 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1760 uint32_t messageLength = cursor.read<uint8_t>();
1761 messageLength <<= 8;
1762 messageLength |= cursor.read<uint8_t>();
1763 messageLength <<= 8;
1764 messageLength |= cursor.read<uint8_t>();
1765 if (cursor.totalLength() < messageLength) {
1766 clientHelloBuf.trimEnd(len);
1767 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1771 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1772 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1774 cursor.skip(4); // gmt_unix_time
1775 cursor.skip(28); // random_bytes
1777 cursor.skip(cursor.read<uint8_t>()); // session_id
1779 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1780 for (int i = 0; i < cipherSuitesLength; i += 2) {
1781 sock->clientHelloInfo_->
1782 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1785 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1786 for (int i = 0; i < compressionMethodsLength; ++i) {
1787 sock->clientHelloInfo_->
1788 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1791 if (cursor.totalLength() > 0) {
1792 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1793 while (extensionsLength) {
1794 ssl::TLSExtension extensionType =
1795 static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>());
1796 sock->clientHelloInfo_->
1797 clientHelloExtensions_.push_back(extensionType);
1798 extensionsLength -= 2;
1799 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1800 extensionsLength -= 2;
1801 extensionsLength -= extensionDataLength;
1803 if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) {
1805 extensionDataLength -= 2;
1806 while (extensionDataLength) {
1807 ssl::HashAlgorithm hashAlg =
1808 static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>());
1809 ssl::SignatureAlgorithm sigAlg =
1810 static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>());
1811 extensionDataLength -= 2;
1812 sock->clientHelloInfo_->
1813 clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1815 } else if (extensionType == ssl::TLSExtension::SUPPORTED_VERSIONS) {
1817 extensionDataLength -= 1;
1818 while (extensionDataLength) {
1819 sock->clientHelloInfo_->clientHelloSupportedVersions_.push_back(
1820 cursor.readBE<uint16_t>());
1821 extensionDataLength -= 2;
1824 cursor.skip(extensionDataLength);
1828 } catch (std::out_of_range&) {
1829 // we'll use what we found and cleanup below.
1830 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1831 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1834 sock->resetClientHelloParsing(ssl);
1837 void AsyncSSLSocket::getSSLClientCiphers(
1838 std::string& clientCiphers,
1839 bool convertToString) const {
1840 std::string ciphers;
1842 if (parseClientHello_ == false
1843 || clientHelloInfo_->clientHelloCipherSuites_.empty()) {
1849 for (auto originalCipherCode : clientHelloInfo_->clientHelloCipherSuites_)
1857 bool nameFound = convertToString;
1859 if (convertToString) {
1860 const auto& name = OpenSSLUtils::getCipherName(originalCipherCode);
1870 std::array<uint8_t, 2>{{
1871 static_cast<uint8_t>((originalCipherCode >> 8) & 0xffL),
1872 static_cast<uint8_t>(originalCipherCode & 0x00ffL) }},
1874 /* append to ciphers = */ true);
1878 clientCiphers = std::move(ciphers);
1881 std::string AsyncSSLSocket::getSSLClientComprMethods() const {
1882 if (!parseClientHello_) {
1885 return folly::join(":", clientHelloInfo_->clientHelloCompressionMethods_);
1888 std::string AsyncSSLSocket::getSSLClientExts() const {
1889 if (!parseClientHello_) {
1892 return folly::join(":", clientHelloInfo_->clientHelloExtensions_);
1895 std::string AsyncSSLSocket::getSSLClientSigAlgs() const {
1896 if (!parseClientHello_) {
1900 std::string sigAlgs;
1901 sigAlgs.reserve(clientHelloInfo_->clientHelloSigAlgs_.size() * 4);
1902 for (size_t i = 0; i < clientHelloInfo_->clientHelloSigAlgs_.size(); i++) {
1904 sigAlgs.push_back(':');
1906 sigAlgs.append(folly::to<std::string>(
1907 clientHelloInfo_->clientHelloSigAlgs_[i].first));
1908 sigAlgs.push_back(',');
1909 sigAlgs.append(folly::to<std::string>(
1910 clientHelloInfo_->clientHelloSigAlgs_[i].second));
1916 std::string AsyncSSLSocket::getSSLClientSupportedVersions() const {
1917 if (!parseClientHello_) {
1920 return folly::join(":", clientHelloInfo_->clientHelloSupportedVersions_);
1923 std::string AsyncSSLSocket::getSSLAlertsReceived() const {
1926 for (const auto& alert : alertsReceived_) {
1930 ret.append(folly::to<std::string>(alert.first, ": ", alert.second));
1936 void AsyncSSLSocket::setSSLCertVerificationAlert(std::string alert) {
1937 sslVerificationAlert_ = std::move(alert);
1940 std::string AsyncSSLSocket::getSSLCertVerificationAlert() const {
1941 return sslVerificationAlert_;
1944 void AsyncSSLSocket::getSSLSharedCiphers(std::string& sharedCiphers) const {
1945 char ciphersBuffer[1024];
1946 ciphersBuffer[0] = '\0';
1947 SSL_get_shared_ciphers(ssl_, ciphersBuffer, sizeof(ciphersBuffer) - 1);
1948 sharedCiphers = ciphersBuffer;
1951 void AsyncSSLSocket::getSSLServerCiphers(std::string& serverCiphers) const {
1952 serverCiphers = SSL_get_cipher_list(ssl_, 0);
1955 while ((cipher = SSL_get_cipher_list(ssl_, i)) != nullptr) {
1956 serverCiphers.append(":");
1957 serverCiphers.append(cipher);