2 * Copyright 2016 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/io/async/AsyncSSLSocket.h>
19 #include <folly/io/async/EventBase.h>
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/IOBuf.h>
35 #include <folly/io/Cursor.h>
36 #include <folly/portability/Unistd.h>
38 using folly::SocketAddress;
39 using folly::SSLContext;
41 using std::shared_ptr;
45 using folly::SpinLock;
46 using folly::SpinLockGuard;
47 using folly::io::Cursor;
48 using std::unique_ptr;
52 using folly::AsyncSocket;
53 using folly::AsyncSocketException;
54 using folly::AsyncSSLSocket;
55 using folly::Optional;
56 using folly::SSLContext;
57 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(AsyncSocketException::TIMED_OUT,
107 "SSL connect timed out");
113 sslSocket_->sslConn(this, timeoutLeft);
116 void connectErr(const AsyncSocketException& ex) noexcept override {
117 VLOG(1) << "TCP connect failed: " << ex.what();
122 void handshakeSuc(AsyncSSLSocket* /* sock */) noexcept override {
123 VLOG(7) << "client handshake success";
125 callback_->connectSuccess();
130 void handshakeErr(AsyncSSLSocket* /* socket */,
131 const AsyncSocketException& ex) noexcept override {
132 VLOG(1) << "client handshakeErr: " << ex.what();
137 void fail(const AsyncSocketException &ex) {
138 // fail is a noop if called twice
140 AsyncSSLSocket::ConnectCallback *cb = callback_;
144 sslSocket_->closeNow();
145 // closeNow can call handshakeErr if it hasn't been called already.
146 // So this may have been deleted, no member variable access beyond this
148 // Note that closeNow may invoke writeError callbacks if the socket had
149 // write data pending connection completion.
154 void setup_SSL_CTX(SSL_CTX *ctx) {
155 #ifdef SSL_MODE_RELEASE_BUFFERS
156 SSL_CTX_set_mode(ctx,
157 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
158 SSL_MODE_ENABLE_PARTIAL_WRITE
159 | SSL_MODE_RELEASE_BUFFERS
162 SSL_CTX_set_mode(ctx,
163 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
164 SSL_MODE_ENABLE_PARTIAL_WRITE
167 // SSL_CTX_set_mode is a Macro
168 #ifdef SSL_MODE_WRITE_IOVEC
169 SSL_CTX_set_mode(ctx,
170 SSL_CTX_get_mode(ctx)
171 | SSL_MODE_WRITE_IOVEC);
176 BIO_METHOD sslWriteBioMethod;
178 void* initsslWriteBioMethod(void) {
179 memcpy(&sslWriteBioMethod, BIO_s_socket(), sizeof(sslWriteBioMethod));
180 // override the bwrite method for MSG_EOR support
181 OpenSSLUtils::setCustomBioWriteMethod(
182 &sslWriteBioMethod, AsyncSSLSocket::bioWrite);
184 // Note that the sslWriteBioMethod.type and sslWriteBioMethod.name are not
185 // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
186 // then have specific handlings. The sslWriteBioWrite should be compatible
187 // with the one in openssl.
189 // Return something here to enable AsyncSSLSocket to call this method using
190 // a function-scoped static.
194 } // anonymous namespace
199 * Create a client AsyncSSLSocket
201 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
202 EventBase* evb, bool deferSecurityNegotiation) :
205 handshakeTimeout_(this, evb),
206 connectionTimeout_(this, evb) {
208 if (deferSecurityNegotiation) {
209 sslState_ = STATE_UNENCRYPTED;
214 * Create a server/client AsyncSSLSocket
216 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
217 EventBase* evb, int fd, bool server,
218 bool deferSecurityNegotiation) :
219 AsyncSocket(evb, fd),
222 handshakeTimeout_(this, evb),
223 connectionTimeout_(this, evb) {
226 SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
227 AsyncSSLSocket::sslInfoCallback);
229 if (deferSecurityNegotiation) {
230 sslState_ = STATE_UNENCRYPTED;
234 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
236 * Create a client AsyncSSLSocket and allow tlsext_hostname
237 * to be sent in Client Hello.
239 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
241 const std::string& serverName,
242 bool deferSecurityNegotiation) :
243 AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
244 tlsextHostname_ = serverName;
248 * Create a client AsyncSSLSocket from an already connected fd
249 * and allow tlsext_hostname to be sent in Client Hello.
251 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
252 EventBase* evb, int fd,
253 const std::string& serverName,
254 bool deferSecurityNegotiation) :
255 AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
256 tlsextHostname_ = serverName;
260 AsyncSSLSocket::~AsyncSSLSocket() {
261 VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
262 << ", evb=" << eventBase_ << ", fd=" << fd_
263 << ", state=" << int(state_) << ", sslState="
264 << sslState_ << ", events=" << eventFlags_ << ")";
267 void AsyncSSLSocket::init() {
268 // Do this here to ensure we initialize this once before any use of
269 // AsyncSSLSocket instances and not as part of library load.
270 static const auto sslWriteBioMethodInitializer = initsslWriteBioMethod();
271 (void)sslWriteBioMethodInitializer;
273 setup_SSL_CTX(ctx_->getSSLCtx());
276 void AsyncSSLSocket::closeNow() {
277 // Close the SSL connection.
278 if (ssl_ != nullptr && fd_ != -1) {
279 int rc = SSL_shutdown(ssl_);
281 rc = SSL_shutdown(ssl_);
288 if (sslSession_ != nullptr) {
289 SSL_SESSION_free(sslSession_);
290 sslSession_ = nullptr;
293 sslState_ = STATE_CLOSED;
295 if (handshakeTimeout_.isScheduled()) {
296 handshakeTimeout_.cancelTimeout();
299 DestructorGuard dg(this);
302 AsyncSocketException(
303 AsyncSocketException::END_OF_FILE,
304 "SSL connection closed locally"));
306 if (ssl_ != nullptr) {
312 AsyncSocket::closeNow();
315 void AsyncSSLSocket::shutdownWrite() {
316 // SSL sockets do not support half-shutdown, so just perform a full shutdown.
318 // (Performing a full shutdown here is more desirable than doing nothing at
319 // all. The purpose of shutdownWrite() is normally to notify the other end
320 // of the connection that no more data will be sent. If we do nothing, the
321 // other end will never know that no more data is coming, and this may result
322 // in protocol deadlock.)
326 void AsyncSSLSocket::shutdownWriteNow() {
330 bool AsyncSSLSocket::good() const {
331 return (AsyncSocket::good() &&
332 (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
333 sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
336 // The TAsyncTransport definition of 'good' states that the transport is
337 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
338 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
339 // is connected but we haven't initiated the call to SSL_connect.
340 bool AsyncSSLSocket::connecting() const {
342 (AsyncSocket::connecting() ||
343 (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
344 sslState_ == STATE_CONNECTING))));
347 std::string AsyncSSLSocket::getApplicationProtocol() noexcept {
348 const unsigned char* protoName = nullptr;
349 unsigned protoLength;
350 if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) {
351 return std::string(reinterpret_cast<const char*>(protoName), protoLength);
356 bool AsyncSSLSocket::isEorTrackingEnabled() const {
360 void AsyncSSLSocket::setEorTracking(bool track) {
361 if (trackEor_ != track) {
364 minEorRawByteNo_ = 0;
368 size_t AsyncSSLSocket::getRawBytesWritten() const {
369 // The bio(s) in the write path are in a chain
370 // each bio flushes to the next and finally written into the socket
371 // to get the rawBytesWritten on the socket,
372 // get the write bytes of the last bio
374 if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
377 BIO* next = BIO_next(b);
378 while (next != NULL) {
383 return BIO_number_written(b);
386 size_t AsyncSSLSocket::getRawBytesReceived() const {
388 if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
392 return BIO_number_read(b);
396 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
397 LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
398 << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
399 << "events=" << eventFlags_ << ", server=" << short(server_)
400 << "): " << "sslAccept/Connect() called in invalid "
401 << "state, handshake callback " << handshakeCallback_
402 << ", new callback " << callback;
403 assert(!handshakeTimeout_.isScheduled());
404 sslState_ = STATE_ERROR;
406 AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
407 "sslAccept() called with socket in invalid state");
409 handshakeEndTime_ = std::chrono::steady_clock::now();
411 callback->handshakeErr(this, ex);
414 // Check the socket state not the ssl state here.
415 if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
416 failHandshake(__func__, ex);
420 void AsyncSSLSocket::sslAccept(HandshakeCB* callback, uint32_t timeout,
421 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
422 DestructorGuard dg(this);
423 assert(eventBase_->isInEventBaseThread());
424 verifyPeer_ = verifyPeer;
426 // Make sure we're in the uninitialized state
427 if (!server_ || (sslState_ != STATE_UNINIT &&
428 sslState_ != STATE_UNENCRYPTED) ||
429 handshakeCallback_ != nullptr) {
430 return invalidState(callback);
433 // Cache local and remote socket addresses to keep them available
434 // after socket file descriptor is closed.
435 if (cacheAddrOnFailure_ && -1 != getFd()) {
436 cacheLocalPeerAddr();
439 handshakeStartTime_ = std::chrono::steady_clock::now();
440 // Make end time at least >= start time.
441 handshakeEndTime_ = handshakeStartTime_;
443 sslState_ = STATE_ACCEPTING;
444 handshakeCallback_ = callback;
447 handshakeTimeout_.scheduleTimeout(timeout);
450 /* register for a read operation (waiting for CLIENT HELLO) */
451 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
454 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
455 void AsyncSSLSocket::attachSSLContext(
456 const std::shared_ptr<SSLContext>& ctx) {
458 // Check to ensure we are in client mode. Changing a server's ssl
459 // context doesn't make sense since clients of that server would likely
460 // become confused when the server's context changes.
464 DCHECK(ctx->getSSLCtx());
467 // In order to call attachSSLContext, detachSSLContext must have been
468 // previously called which sets the socket's context to the dummy
469 // context. Thus we must acquire this lock.
470 SpinLockGuard guard(dummyCtxLock);
471 SSL_set_SSL_CTX(ssl_, ctx->getSSLCtx());
474 void AsyncSSLSocket::detachSSLContext() {
477 // We aren't using the initial_ctx for now, and it can introduce race
478 // conditions in the destructor of the SSL object.
479 #ifndef OPENSSL_NO_TLSEXT
480 if (ssl_->initial_ctx) {
481 SSL_CTX_free(ssl_->initial_ctx);
482 ssl_->initial_ctx = nullptr;
485 SpinLockGuard guard(dummyCtxLock);
486 if (nullptr == dummyCtx) {
487 // We need to lazily initialize the dummy context so we don't
488 // accidentally override any programmatic settings to openssl
489 dummyCtx = new SSLContext;
491 // We must remove this socket's references to its context right now
492 // since this socket could get passed to any thread. If the context has
493 // had its locking disabled, just doing a set in attachSSLContext()
494 // would not be thread safe.
495 SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
499 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
500 void AsyncSSLSocket::switchServerSSLContext(
501 const std::shared_ptr<SSLContext>& handshakeCtx) {
503 if (sslState_ != STATE_ACCEPTING) {
504 // We log it here and allow the switch.
505 // It should not affect our re-negotiation support (which
506 // is not supported now).
507 VLOG(6) << "fd=" << getFd()
508 << " renegotation detected when switching SSL_CTX";
511 setup_SSL_CTX(handshakeCtx->getSSLCtx());
512 SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
513 AsyncSSLSocket::sslInfoCallback);
514 handshakeCtx_ = handshakeCtx;
515 SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
518 bool AsyncSSLSocket::isServerNameMatch() const {
525 SSL_SESSION *ss = SSL_get_session(ssl_);
530 if(!ss->tlsext_hostname) {
533 return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
536 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
537 tlsextHostname_ = std::move(serverName);
542 void AsyncSSLSocket::timeoutExpired() noexcept {
543 if (state_ == StateEnum::ESTABLISHED &&
544 (sslState_ == STATE_CACHE_LOOKUP ||
545 sslState_ == STATE_ASYNC_PENDING)) {
546 sslState_ = STATE_ERROR;
547 // We are expecting a callback in restartSSLAccept. The cache lookup
548 // and rsa-call necessarily have pointers to this ssl socket, so delay
549 // the cleanup until he calls us back.
550 } else if (state_ == StateEnum::CONNECTING) {
551 assert(sslState_ == STATE_CONNECTING);
552 DestructorGuard dg(this);
553 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
554 "Fallback connect timed out during TFO");
555 failHandshake(__func__, ex);
557 assert(state_ == StateEnum::ESTABLISHED &&
558 (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
559 DestructorGuard dg(this);
560 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
561 (sslState_ == STATE_CONNECTING) ?
562 "SSL connect timed out" : "SSL accept timed out");
563 failHandshake(__func__, ex);
567 int AsyncSSLSocket::getSSLExDataIndex() {
568 static auto index = SSL_get_ex_new_index(
569 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
573 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
574 return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
575 getSSLExDataIndex()));
578 void AsyncSSLSocket::failHandshake(const char* /* fn */,
579 const AsyncSocketException& ex) {
581 if (handshakeTimeout_.isScheduled()) {
582 handshakeTimeout_.cancelTimeout();
584 invokeHandshakeErr(ex);
588 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
589 handshakeEndTime_ = std::chrono::steady_clock::now();
590 if (handshakeCallback_ != nullptr) {
591 HandshakeCB* callback = handshakeCallback_;
592 handshakeCallback_ = nullptr;
593 callback->handshakeErr(this, ex);
597 void AsyncSSLSocket::invokeHandshakeCB() {
598 handshakeEndTime_ = std::chrono::steady_clock::now();
599 if (handshakeTimeout_.isScheduled()) {
600 handshakeTimeout_.cancelTimeout();
602 if (handshakeCallback_) {
603 HandshakeCB* callback = handshakeCallback_;
604 handshakeCallback_ = nullptr;
605 callback->handshakeSuc(this);
609 void AsyncSSLSocket::cacheLocalPeerAddr() {
610 SocketAddress address;
612 getLocalAddress(&address);
613 getPeerAddress(&address);
614 } catch (const std::system_error& e) {
615 // The handle can be still valid while the connection is already closed.
616 if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
622 void AsyncSSLSocket::connect(ConnectCallback* callback,
623 const folly::SocketAddress& address,
625 const OptionMap &options,
626 const folly::SocketAddress& bindAddr)
629 assert(state_ == StateEnum::UNINIT);
630 assert(sslState_ == STATE_UNINIT);
631 AsyncSSLSocketConnector *connector =
632 new AsyncSSLSocketConnector(this, callback, timeout);
633 AsyncSocket::connect(connector, address, timeout, options, bindAddr);
636 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
637 // apply the settings specified in verifyPeer_
638 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
639 if(ctx_->needsPeerVerification()) {
640 SSL_set_verify(ssl, ctx_->getVerificationMode(),
641 AsyncSSLSocket::sslVerifyCallback);
644 if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
645 verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
646 SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
647 AsyncSSLSocket::sslVerifyCallback);
652 bool AsyncSSLSocket::setupSSLBio() {
653 auto wb = BIO_new(&sslWriteBioMethod);
659 OpenSSLUtils::setBioAppData(wb, this);
660 OpenSSLUtils::setBioFd(wb, fd_, BIO_NOCLOSE);
661 SSL_set_bio(ssl_, wb, wb);
665 void AsyncSSLSocket::sslConn(HandshakeCB* callback, uint64_t timeout,
666 const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
667 DestructorGuard dg(this);
668 assert(eventBase_->isInEventBaseThread());
670 // Cache local and remote socket addresses to keep them available
671 // after socket file descriptor is closed.
672 if (cacheAddrOnFailure_ && -1 != getFd()) {
673 cacheLocalPeerAddr();
676 verifyPeer_ = verifyPeer;
678 // Make sure we're in the uninitialized state
679 if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
680 STATE_UNENCRYPTED) ||
681 handshakeCallback_ != nullptr) {
682 return invalidState(callback);
685 sslState_ = STATE_CONNECTING;
686 handshakeCallback_ = callback;
689 ssl_ = ctx_->createSSL();
690 } catch (std::exception &e) {
691 sslState_ = STATE_ERROR;
692 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
693 "error calling SSLContext::createSSL()");
694 LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
695 << fd_ << "): " << e.what();
696 return failHandshake(__func__, ex);
699 if (!setupSSLBio()) {
700 sslState_ = STATE_ERROR;
701 AsyncSocketException ex(
702 AsyncSocketException::INTERNAL_ERROR, "error creating SSL bio");
703 return failHandshake(__func__, ex);
706 applyVerificationOptions(ssl_);
708 if (sslSession_ != nullptr) {
709 sessionResumptionAttempted_ = true;
710 SSL_set_session(ssl_, sslSession_);
711 SSL_SESSION_free(sslSession_);
712 sslSession_ = nullptr;
714 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
715 if (tlsextHostname_.size()) {
716 SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
720 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
722 handshakeConnectTimeout_ = timeout;
726 // This could be called multiple times, during normal ssl connections
727 // and after TFO fallback.
728 void AsyncSSLSocket::startSSLConnect() {
729 handshakeStartTime_ = std::chrono::steady_clock::now();
730 // Make end time at least >= start time.
731 handshakeEndTime_ = handshakeStartTime_;
732 if (handshakeConnectTimeout_ > 0) {
733 handshakeTimeout_.scheduleTimeout(handshakeConnectTimeout_);
738 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
739 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
740 return SSL_get1_session(ssl_);
746 const SSL* AsyncSSLSocket::getSSL() const {
750 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
751 sslSession_ = session;
752 if (!takeOwnership && session != nullptr) {
753 // Increment the reference count
754 CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
758 void AsyncSSLSocket::getSelectedNextProtocol(
759 const unsigned char** protoName,
761 SSLContext::NextProtocolType* protoType) const {
762 if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
763 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
764 "NPN not supported");
768 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
769 const unsigned char** protoName,
771 SSLContext::NextProtocolType* protoType) const {
772 *protoName = nullptr;
774 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
775 SSL_get0_alpn_selected(ssl_, protoName, protoLen);
778 *protoType = SSLContext::NextProtocolType::ALPN;
783 #ifdef OPENSSL_NPN_NEGOTIATED
784 SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
786 *protoType = SSLContext::NextProtocolType::NPN;
795 bool AsyncSSLSocket::getSSLSessionReused() const {
796 if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
797 return SSL_session_reused(ssl_);
802 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
803 return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
807 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
808 if (ssl == nullptr) {
811 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
812 return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
818 const char *AsyncSSLSocket::getSSLServerName() const {
819 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
820 return getSSLServerNameFromSSL(ssl_);
822 throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
823 "SNI not supported");
827 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
828 return getSSLServerNameFromSSL(ssl_);
831 int AsyncSSLSocket::getSSLVersion() const {
832 return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
835 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
836 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
838 int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
839 return OBJ_nid2ln(nid);
844 int AsyncSSLSocket::getSSLCertSize() const {
846 X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
848 EVP_PKEY *key = X509_get_pubkey(cert);
849 certSize = EVP_PKEY_bits(key);
855 const X509* AsyncSSLSocket::getSelfCert() const {
856 return (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
859 bool AsyncSSLSocket::willBlock(int ret,
861 unsigned long* errErrorOut) noexcept {
863 int error = *sslErrorOut = SSL_get_error(ssl_, ret);
864 if (error == SSL_ERROR_WANT_READ) {
865 // Register for read event if not already.
866 updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
868 } else if (error == SSL_ERROR_WANT_WRITE) {
869 VLOG(3) << "AsyncSSLSocket(fd=" << fd_
870 << ", state=" << int(state_) << ", sslState="
871 << sslState_ << ", events=" << eventFlags_ << "): "
872 << "SSL_ERROR_WANT_WRITE";
873 // Register for write event if not already.
874 updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
876 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
877 } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
878 // We will block but we can't register our own socket. The callback that
879 // triggered this code will re-call handleAccept at the appropriate time.
881 // We can only get here if the linked libssl.so has support for this feature
882 // as well, otherwise SSL_get_error cannot return our error code.
883 sslState_ = STATE_CACHE_LOOKUP;
885 // Unregister for all events while blocked here
886 updateEventRegistration(EventHandler::NONE,
887 EventHandler::READ | EventHandler::WRITE);
889 // The timeout (if set) keeps running here
893 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
894 || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
896 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
897 || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
900 // Our custom openssl function has kicked off an async request to do
901 // rsa/ecdsa private key operation. When that call returns, a callback will
902 // be invoked that will re-call handleAccept.
903 sslState_ = STATE_ASYNC_PENDING;
905 // Unregister for all events while blocked here
906 updateEventRegistration(
908 EventHandler::READ | EventHandler::WRITE
911 // The timeout (if set) keeps running here
914 unsigned long lastError = *errErrorOut = ERR_get_error();
915 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
916 << "state=" << state_ << ", "
917 << "sslState=" << sslState_ << ", "
918 << "events=" << std::hex << eventFlags_ << "): "
919 << "SSL error: " << error << ", "
920 << "errno: " << errno << ", "
921 << "ret: " << ret << ", "
922 << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
923 << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
924 << "func: " << ERR_func_error_string(lastError) << ", "
925 << "reason: " << ERR_reason_error_string(lastError);
930 void AsyncSSLSocket::checkForImmediateRead() noexcept {
931 // openssl may have buffered data that it read from the socket already.
932 // In this case we have to process it immediately, rather than waiting for
933 // the socket to become readable again.
934 if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
935 AsyncSocket::handleRead();
940 AsyncSSLSocket::restartSSLAccept()
942 VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this
943 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
944 << "sslState=" << sslState_ << ", events=" << eventFlags_;
945 DestructorGuard dg(this);
947 sslState_ == STATE_CACHE_LOOKUP ||
948 sslState_ == STATE_ASYNC_PENDING ||
949 sslState_ == STATE_ERROR ||
950 sslState_ == STATE_CLOSED);
951 if (sslState_ == STATE_CLOSED) {
952 // I sure hope whoever closed this socket didn't delete it already,
953 // but this is not strictly speaking an error
956 if (sslState_ == STATE_ERROR) {
957 // go straight to fail if timeout expired during lookup
958 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
959 "SSL accept timed out");
960 failHandshake(__func__, ex);
963 sslState_ = STATE_ACCEPTING;
964 this->handleAccept();
968 AsyncSSLSocket::handleAccept() noexcept {
969 VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
970 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
971 << "sslState=" << sslState_ << ", events=" << eventFlags_;
973 assert(state_ == StateEnum::ESTABLISHED &&
974 sslState_ == STATE_ACCEPTING);
976 /* lazily create the SSL structure */
978 ssl_ = ctx_->createSSL();
979 } catch (std::exception &e) {
980 sslState_ = STATE_ERROR;
981 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
982 "error calling SSLContext::createSSL()");
983 LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
984 << ", fd=" << fd_ << "): " << e.what();
985 return failHandshake(__func__, ex);
988 if (!setupSSLBio()) {
989 sslState_ = STATE_ERROR;
990 AsyncSocketException ex(
991 AsyncSocketException::INTERNAL_ERROR, "error creating write bio");
992 return failHandshake(__func__, ex);
995 SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
997 applyVerificationOptions(ssl_);
1000 if (server_ && parseClientHello_) {
1001 SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1002 SSL_set_msg_callback_arg(ssl_, this);
1005 int ret = SSL_accept(ssl_);
1008 unsigned long errError;
1009 int errnoCopy = errno;
1010 if (willBlock(ret, &sslError, &errError)) {
1013 sslState_ = STATE_ERROR;
1014 SSLException ex(sslError, errError, ret, errnoCopy);
1015 return failHandshake(__func__, ex);
1019 handshakeComplete_ = true;
1020 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1022 // Move into STATE_ESTABLISHED in the normal case that we are in
1024 sslState_ = STATE_ESTABLISHED;
1026 VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1027 << " successfully accepted; state=" << int(state_)
1028 << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1030 // Remember the EventBase we are attached to, before we start invoking any
1031 // callbacks (since the callbacks may call detachEventBase()).
1032 EventBase* originalEventBase = eventBase_;
1034 // Call the accept callback.
1035 invokeHandshakeCB();
1037 // Note that the accept callback may have changed our state.
1038 // (set or unset the read callback, called write(), closed the socket, etc.)
1039 // The following code needs to handle these situations correctly.
1041 // If the socket has been closed, readCallback_ and writeReqHead_ will
1042 // always be nullptr, so that will prevent us from trying to read or write.
1044 // The main thing to check for is if eventBase_ is still originalEventBase.
1045 // If not, we have been detached from this event base, so we shouldn't
1046 // perform any more operations.
1047 if (eventBase_ != originalEventBase) {
1051 AsyncSocket::handleInitialReadWrite();
1055 AsyncSSLSocket::handleConnect() noexcept {
1056 VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this
1057 << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1058 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1060 if (state_ < StateEnum::ESTABLISHED) {
1061 return AsyncSocket::handleConnect();
1065 (state_ == StateEnum::FAST_OPEN || state_ == StateEnum::ESTABLISHED) &&
1066 sslState_ == STATE_CONNECTING);
1069 auto originalState = state_;
1070 int ret = SSL_connect(ssl_);
1073 unsigned long errError;
1074 int errnoCopy = errno;
1075 if (willBlock(ret, &sslError, &errError)) {
1076 // We fell back to connecting state due to TFO
1077 if (state_ == StateEnum::CONNECTING) {
1078 DCHECK_EQ(StateEnum::FAST_OPEN, originalState);
1079 if (handshakeTimeout_.isScheduled()) {
1080 handshakeTimeout_.cancelTimeout();
1085 sslState_ = STATE_ERROR;
1086 SSLException ex(sslError, errError, ret, errnoCopy);
1087 return failHandshake(__func__, ex);
1091 handshakeComplete_ = true;
1092 updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1094 // Move into STATE_ESTABLISHED in the normal case that we are in
1095 // STATE_CONNECTING.
1096 sslState_ = STATE_ESTABLISHED;
1098 VLOG(3) << "AsyncSSLSocket " << this << ": "
1099 << "fd " << fd_ << " successfully connected; "
1100 << "state=" << int(state_) << ", sslState=" << sslState_
1101 << ", events=" << eventFlags_;
1103 // Remember the EventBase we are attached to, before we start invoking any
1104 // callbacks (since the callbacks may call detachEventBase()).
1105 EventBase* originalEventBase = eventBase_;
1107 // Call the handshake callback.
1108 invokeHandshakeCB();
1110 // Note that the connect callback may have changed our state.
1111 // (set or unset the read callback, called write(), closed the socket, etc.)
1112 // The following code needs to handle these situations correctly.
1114 // If the socket has been closed, readCallback_ and writeReqHead_ will
1115 // always be nullptr, so that will prevent us from trying to read or write.
1117 // The main thing to check for is if eventBase_ is still originalEventBase.
1118 // If not, we have been detached from this event base, so we shouldn't
1119 // perform any more operations.
1120 if (eventBase_ != originalEventBase) {
1124 AsyncSocket::handleInitialReadWrite();
1127 void AsyncSSLSocket::invokeConnectErr(const AsyncSocketException& ex) {
1128 connectionTimeout_.cancelTimeout();
1129 AsyncSocket::invokeConnectErr(ex);
1132 void AsyncSSLSocket::invokeConnectSuccess() {
1133 connectionTimeout_.cancelTimeout();
1134 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1135 // If we failed TFO, we'd fall back to trying to connect the socket,
1136 // to setup things like timeouts.
1139 // still invoke the base class since it re-sets the connect time.
1140 AsyncSocket::invokeConnectSuccess();
1143 void AsyncSSLSocket::scheduleConnectTimeout() {
1144 if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1145 // We fell back from TFO, and need to set the timeouts.
1146 // We will not have a connect callback in this case, thus if the timer
1147 // expires we would have no-one to notify.
1148 // Thus we should reset even the connect timers to point to the handshake
1150 assert(connectCallback_ == nullptr);
1151 // We use a different connect timeout here than the handshake timeout, so
1152 // that we can disambiguate the 2 timers.
1153 int timeout = connectTimeout_.count();
1155 if (!connectionTimeout_.scheduleTimeout(timeout)) {
1156 throw AsyncSocketException(
1157 AsyncSocketException::INTERNAL_ERROR,
1158 withAddr("failed to schedule AsyncSSLSocket connect timeout"));
1163 AsyncSocket::scheduleConnectTimeout();
1166 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1167 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1168 // turn on the buffer movable in openssl
1169 if (bufferMovableEnabled_ && ssl_ != nullptr && !isBufferMovable_ &&
1170 callback != nullptr && callback->isBufferMovable()) {
1171 SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1172 isBufferMovable_ = true;
1176 AsyncSocket::setReadCB(callback);
1179 void AsyncSSLSocket::setBufferMovableEnabled(bool enabled) {
1180 bufferMovableEnabled_ = enabled;
1183 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1184 CHECK(readCallback_);
1185 if (isBufferMovable_) {
1189 // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1190 readCallback_->getReadBuffer(buf, buflen);
1195 AsyncSSLSocket::handleRead() noexcept {
1196 VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1197 << ", state=" << int(state_) << ", "
1198 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1199 if (state_ < StateEnum::ESTABLISHED) {
1200 return AsyncSocket::handleRead();
1204 if (sslState_ == STATE_ACCEPTING) {
1209 else if (sslState_ == STATE_CONNECTING) {
1216 AsyncSocket::handleRead();
1219 AsyncSocket::ReadResult
1220 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1221 VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf
1222 << ", buflen=" << *buflen;
1224 if (sslState_ == STATE_UNENCRYPTED) {
1225 return AsyncSocket::performRead(buf, buflen, offset);
1229 if (!isBufferMovable_) {
1230 bytes = SSL_read(ssl_, *buf, *buflen);
1232 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1234 bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1238 if (server_ && renegotiateAttempted_) {
1239 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1240 << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1241 << "): client intitiated SSL renegotiation not permitted";
1244 folly::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION));
1247 int error = SSL_get_error(ssl_, bytes);
1248 if (error == SSL_ERROR_WANT_READ) {
1249 // The caller will register for read event if not already.
1250 if (errno == EWOULDBLOCK || errno == EAGAIN) {
1251 return ReadResult(READ_BLOCKING);
1253 return ReadResult(READ_ERROR);
1255 } else if (error == SSL_ERROR_WANT_WRITE) {
1256 // TODO: Even though we are attempting to read data, SSL_read() may
1257 // need to write data if renegotiation is being performed. We currently
1258 // don't support this and just fail the read.
1259 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1260 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1261 << "): unsupported SSL renegotiation during read";
1264 folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1266 if (zero_return(error, bytes)) {
1267 return ReadResult(bytes);
1269 long errError = ERR_get_error();
1270 VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1271 << "state=" << state_ << ", "
1272 << "sslState=" << sslState_ << ", "
1273 << "events=" << std::hex << eventFlags_ << "): "
1274 << "bytes: " << bytes << ", "
1275 << "error: " << error << ", "
1276 << "errno: " << errno << ", "
1277 << "func: " << ERR_func_error_string(errError) << ", "
1278 << "reason: " << ERR_reason_error_string(errError);
1281 folly::make_unique<SSLException>(error, errError, bytes, errno));
1284 appBytesReceived_ += bytes;
1285 return ReadResult(bytes);
1289 void AsyncSSLSocket::handleWrite() noexcept {
1290 VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1291 << ", state=" << int(state_) << ", "
1292 << "sslState=" << sslState_ << ", events=" << eventFlags_;
1293 if (state_ < StateEnum::ESTABLISHED) {
1294 return AsyncSocket::handleWrite();
1297 if (sslState_ == STATE_ACCEPTING) {
1303 if (sslState_ == STATE_CONNECTING) {
1310 AsyncSocket::handleWrite();
1313 AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {
1314 if (error == SSL_ERROR_WANT_READ) {
1315 // Even though we are attempting to write data, SSL_write() may
1316 // need to read data if renegotiation is being performed. We currently
1317 // don't support this and just fail the write.
1318 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1319 << ", sslState=" << sslState_ << ", events=" << eventFlags_
1321 << "unsupported SSL renegotiation during write";
1324 folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1326 if (zero_return(error, rc)) {
1327 return WriteResult(0);
1329 auto errError = ERR_get_error();
1330 VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1331 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1332 << "SSL error: " << error << ", errno: " << errno
1333 << ", func: " << ERR_func_error_string(errError)
1334 << ", reason: " << ERR_reason_error_string(errError);
1337 folly::make_unique<SSLException>(error, errError, rc, errno));
1341 AsyncSocket::WriteResult AsyncSSLSocket::performWrite(
1345 uint32_t* countWritten,
1346 uint32_t* partialWritten) {
1347 if (sslState_ == STATE_UNENCRYPTED) {
1348 return AsyncSocket::performWrite(
1349 vec, count, flags, countWritten, partialWritten);
1351 if (sslState_ != STATE_ESTABLISHED) {
1352 LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1353 << ", sslState=" << sslState_
1354 << ", events=" << eventFlags_ << "): "
1355 << "TODO: AsyncSSLSocket currently does not support calling "
1356 << "write() before the handshake has fully completed";
1358 WRITE_ERROR, folly::make_unique<SSLException>(SSLError::EARLY_WRITE));
1361 // Declare a buffer used to hold small write requests. It could point to a
1362 // memory block either on stack or on heap. If it is on heap, we release it
1363 // manually when scope exits
1364 char* combinedBuf{nullptr};
1366 // Note, always keep this check consistent with what we do below
1367 if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1368 delete[] combinedBuf;
1373 *partialWritten = 0;
1374 ssize_t totalWritten = 0;
1375 size_t bytesStolenFromNextBuffer = 0;
1376 for (uint32_t i = 0; i < count; i++) {
1377 const iovec* v = vec + i;
1378 size_t offset = bytesStolenFromNextBuffer;
1379 bytesStolenFromNextBuffer = 0;
1380 size_t len = v->iov_len - offset;
1386 buf = ((const char*)v->iov_base) + offset;
1389 uint32_t buffersStolen = 0;
1390 auto sslWriteBuf = buf;
1391 if ((len < minWriteSize_) && ((i + 1) < count)) {
1392 // Combine this buffer with part or all of the next buffers in
1393 // order to avoid really small-grained calls to SSL_write().
1394 // Each call to SSL_write() produces a separate record in
1395 // the egress SSL stream, and we've found that some low-end
1396 // mobile clients can't handle receiving an HTTP response
1397 // header and the first part of the response body in two
1398 // separate SSL records (even if those two records are in
1399 // the same TCP packet).
1401 if (combinedBuf == nullptr) {
1402 if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1403 // Allocate the buffer on heap
1404 combinedBuf = new char[minWriteSize_];
1406 // Allocate the buffer on stack
1407 combinedBuf = (char*)alloca(minWriteSize_);
1410 assert(combinedBuf != nullptr);
1411 sslWriteBuf = combinedBuf;
1413 memcpy(combinedBuf, buf, len);
1415 // INVARIANT: i + buffersStolen == complete chunks serialized
1416 uint32_t nextIndex = i + buffersStolen + 1;
1417 bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1418 minWriteSize_ - len);
1419 memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1420 bytesStolenFromNextBuffer);
1421 len += bytesStolenFromNextBuffer;
1422 if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1423 // couldn't steal the whole buffer
1426 bytesStolenFromNextBuffer = 0;
1429 } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1432 // Advance any empty buffers immediately after.
1433 if (bytesStolenFromNextBuffer == 0) {
1434 while ((i + buffersStolen + 1) < count &&
1435 vec[i + buffersStolen + 1].iov_len == 0) {
1441 isSet(flags, WriteFlags::CORK) || (i + buffersStolen + 1 < count);
1442 bytes = eorAwareSSLWrite(
1446 (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1449 int error = SSL_get_error(ssl_, bytes);
1450 if (error == SSL_ERROR_WANT_WRITE) {
1451 // The caller will register for write event if not already.
1452 *partialWritten = offset;
1453 return WriteResult(totalWritten);
1455 auto writeResult = interpretSSLError(bytes, error);
1456 if (writeResult.writeReturn < 0) {
1458 } // else fall through to below to correctly record totalWritten
1461 totalWritten += bytes;
1463 if (bytes == (ssize_t)len) {
1464 // The full iovec is written.
1465 (*countWritten) += 1 + buffersStolen;
1469 bytes += offset; // adjust bytes to account for all of v
1470 while (bytes >= (ssize_t)v->iov_len) {
1471 // We combined this buf with part or all of the next one, and
1472 // we managed to write all of this buf but not all of the bytes
1473 // from the next one that we'd hoped to write.
1474 bytes -= v->iov_len;
1478 *partialWritten = bytes;
1479 return WriteResult(totalWritten);
1483 return WriteResult(totalWritten);
1486 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1488 if (eor && trackEor_) {
1489 if (appEorByteNo_) {
1490 // cannot track for more than one app byte EOR
1491 CHECK(appEorByteNo_ == appBytesWritten_ + n);
1493 appEorByteNo_ = appBytesWritten_ + n;
1496 // 1. It is fine to keep updating minEorRawByteNo_.
1497 // 2. It is _min_ in the sense that SSL record will add some overhead.
1498 minEorRawByteNo_ = getRawBytesWritten() + n;
1501 n = sslWriteImpl(ssl, buf, n);
1503 appBytesWritten_ += n;
1504 if (appEorByteNo_) {
1505 if (getRawBytesWritten() >= minEorRawByteNo_) {
1506 minEorRawByteNo_ = 0;
1508 if(appBytesWritten_ == appEorByteNo_) {
1511 CHECK(appBytesWritten_ < appEorByteNo_);
1518 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) {
1519 AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1520 if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1521 sslSocket->renegotiateAttempted_ = true;
1523 if (where & SSL_CB_READ_ALERT) {
1524 const char* type = SSL_alert_type_string(ret);
1526 const char* desc = SSL_alert_desc_string(ret);
1527 sslSocket->alertsReceived_.emplace_back(
1528 *type, StringPiece(desc, std::strlen(desc)));
1533 int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) {
1537 AsyncSSLSocket* tsslSock;
1539 iov.iov_base = const_cast<char*>(in);
1541 memset(&msg, 0, sizeof(msg));
1545 auto appData = OpenSSLUtils::getBioAppData(b);
1548 tsslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1551 if (tsslSock->trackEor_ && tsslSock->minEorRawByteNo_ &&
1552 tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1557 flags |= MSG_NOSIGNAL;
1561 if (tsslSock->corkCurrentWrite_) {
1566 auto result = tsslSock->sendSocketMessage(
1567 OpenSSLUtils::getBioFd(b, nullptr), &msg, flags);
1568 BIO_clear_retry_flags(b);
1569 if (!result.exception && result.writeReturn <= 0) {
1570 if (OpenSSLUtils::getBioShouldRetryWrite(result.writeReturn)) {
1571 BIO_set_retry_write(b);
1574 return result.writeReturn;
1577 int AsyncSSLSocket::sslVerifyCallback(
1579 X509_STORE_CTX* x509Ctx) {
1580 SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1581 x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1582 AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1584 VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1585 << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1586 return (self->handshakeCallback_) ?
1587 self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1591 void AsyncSSLSocket::enableClientHelloParsing() {
1592 parseClientHello_ = true;
1593 clientHelloInfo_.reset(new ssl::ClientHelloInfo());
1596 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl) {
1597 SSL_set_msg_callback(ssl, nullptr);
1598 SSL_set_msg_callback_arg(ssl, nullptr);
1599 clientHelloInfo_->clientHelloBuf_.clear();
1602 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1609 AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1611 sock->resetClientHelloParsing(ssl);
1614 if (contentType != SSL3_RT_HANDSHAKE) {
1621 auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1622 clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1624 Cursor cursor(clientHelloBuf.front());
1625 if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1626 sock->resetClientHelloParsing(ssl);
1630 if (cursor.totalLength() < 3) {
1631 clientHelloBuf.trimEnd(len);
1632 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1636 uint32_t messageLength = cursor.read<uint8_t>();
1637 messageLength <<= 8;
1638 messageLength |= cursor.read<uint8_t>();
1639 messageLength <<= 8;
1640 messageLength |= cursor.read<uint8_t>();
1641 if (cursor.totalLength() < messageLength) {
1642 clientHelloBuf.trimEnd(len);
1643 clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1647 sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1648 sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1650 cursor.skip(4); // gmt_unix_time
1651 cursor.skip(28); // random_bytes
1653 cursor.skip(cursor.read<uint8_t>()); // session_id
1655 uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1656 for (int i = 0; i < cipherSuitesLength; i += 2) {
1657 sock->clientHelloInfo_->
1658 clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1661 uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1662 for (int i = 0; i < compressionMethodsLength; ++i) {
1663 sock->clientHelloInfo_->
1664 clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1667 if (cursor.totalLength() > 0) {
1668 uint16_t extensionsLength = cursor.readBE<uint16_t>();
1669 while (extensionsLength) {
1670 ssl::TLSExtension extensionType =
1671 static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>());
1672 sock->clientHelloInfo_->
1673 clientHelloExtensions_.push_back(extensionType);
1674 extensionsLength -= 2;
1675 uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1676 extensionsLength -= 2;
1677 extensionsLength -= extensionDataLength;
1679 if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) {
1681 extensionDataLength -= 2;
1682 while (extensionDataLength) {
1683 ssl::HashAlgorithm hashAlg =
1684 static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>());
1685 ssl::SignatureAlgorithm sigAlg =
1686 static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>());
1687 extensionDataLength -= 2;
1688 sock->clientHelloInfo_->
1689 clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1692 cursor.skip(extensionDataLength);
1696 } catch (std::out_of_range& e) {
1697 // we'll use what we found and cleanup below.
1698 VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1699 << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1702 sock->resetClientHelloParsing(ssl);
1705 void AsyncSSLSocket::getSSLClientCiphers(
1706 std::string& clientCiphers,
1707 bool convertToString) const {
1708 std::string ciphers;
1710 if (parseClientHello_ == false
1711 || clientHelloInfo_->clientHelloCipherSuites_.empty()) {
1717 for (auto originalCipherCode : clientHelloInfo_->clientHelloCipherSuites_)
1725 bool nameFound = convertToString;
1727 if (convertToString) {
1728 const auto& name = OpenSSLUtils::getCipherName(originalCipherCode);
1738 std::array<uint8_t, 2>{{
1739 static_cast<uint8_t>((originalCipherCode >> 8) & 0xffL),
1740 static_cast<uint8_t>(originalCipherCode & 0x00ffL) }},
1742 /* append to ciphers = */ true);
1746 clientCiphers = std::move(ciphers);
1749 std::string AsyncSSLSocket::getSSLClientComprMethods() const {
1750 if (!parseClientHello_) {
1753 return folly::join(":", clientHelloInfo_->clientHelloCompressionMethods_);
1756 std::string AsyncSSLSocket::getSSLClientExts() const {
1757 if (!parseClientHello_) {
1760 return folly::join(":", clientHelloInfo_->clientHelloExtensions_);
1763 std::string AsyncSSLSocket::getSSLClientSigAlgs() const {
1764 if (!parseClientHello_) {
1768 std::string sigAlgs;
1769 sigAlgs.reserve(clientHelloInfo_->clientHelloSigAlgs_.size() * 4);
1770 for (size_t i = 0; i < clientHelloInfo_->clientHelloSigAlgs_.size(); i++) {
1772 sigAlgs.push_back(':');
1774 sigAlgs.append(folly::to<std::string>(
1775 clientHelloInfo_->clientHelloSigAlgs_[i].first));
1776 sigAlgs.push_back(',');
1777 sigAlgs.append(folly::to<std::string>(
1778 clientHelloInfo_->clientHelloSigAlgs_[i].second));
1784 std::string AsyncSSLSocket::getSSLAlertsReceived() const {
1787 for (const auto& alert : alertsReceived_) {
1791 ret.append(folly::to<std::string>(alert.first, ": ", alert.second));
1797 void AsyncSSLSocket::getSSLSharedCiphers(std::string& sharedCiphers) const {
1798 char ciphersBuffer[1024];
1799 ciphersBuffer[0] = '\0';
1800 SSL_get_shared_ciphers(ssl_, ciphersBuffer, sizeof(ciphersBuffer) - 1);
1801 sharedCiphers = ciphersBuffer;
1804 void AsyncSSLSocket::getSSLServerCiphers(std::string& serverCiphers) const {
1805 serverCiphers = SSL_get_cipher_list(ssl_, 0);
1808 while ((cipher = SSL_get_cipher_list(ssl_, i)) != nullptr) {
1809 serverCiphers.append(":");
1810 serverCiphers.append(cipher);