Add logs for TFO succeded
[folly.git] / folly / io / async / AsyncSSLSocket.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <folly/io/async/AsyncSSLSocket.h>
18
19 #include <folly/io/async/EventBase.h>
20 #include <folly/portability/Sockets.h>
21
22 #include <boost/noncopyable.hpp>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <openssl/err.h>
26 #include <openssl/asn1.h>
27 #include <openssl/ssl.h>
28 #include <sys/types.h>
29 #include <chrono>
30
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>
37
38 using folly::SocketAddress;
39 using folly::SSLContext;
40 using std::string;
41 using std::shared_ptr;
42
43 using folly::Endian;
44 using folly::IOBuf;
45 using folly::SpinLock;
46 using folly::SpinLockGuard;
47 using folly::io::Cursor;
48 using std::unique_ptr;
49 using std::bind;
50
51 namespace {
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;
58
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;
63
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;
67
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));
71 }
72
73 class AsyncSSLSocketConnector: public AsyncSocket::ConnectCallback,
74                                 public AsyncSSLSocket::HandshakeCB {
75
76  private:
77   AsyncSSLSocket *sslSocket_;
78   AsyncSSLSocket::ConnectCallback *callback_;
79   int timeout_;
80   int64_t startTime_;
81
82  protected:
83   ~AsyncSSLSocketConnector() override {}
84
85  public:
86   AsyncSSLSocketConnector(AsyncSSLSocket *sslSocket,
87                            AsyncSocket::ConnectCallback *callback,
88                            int timeout) :
89       sslSocket_(sslSocket),
90       callback_(callback),
91       timeout_(timeout),
92       startTime_(std::chrono::duration_cast<std::chrono::milliseconds>(
93                    std::chrono::steady_clock::now().time_since_epoch()).count()) {
94   }
95
96   void connectSuccess() noexcept override {
97     VLOG(7) << "client socket connected";
98
99     int64_t timeoutLeft = 0;
100     if (timeout_ > 0) {
101       auto curTime = std::chrono::duration_cast<std::chrono::milliseconds>(
102         std::chrono::steady_clock::now().time_since_epoch()).count();
103
104       timeoutLeft = timeout_ - (curTime - startTime_);
105       if (timeoutLeft <= 0) {
106         AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
107                                 "SSL connect timed out");
108         fail(ex);
109         delete this;
110         return;
111       }
112     }
113     sslSocket_->sslConn(this, timeoutLeft);
114   }
115
116   void connectErr(const AsyncSocketException& ex) noexcept override {
117     VLOG(1) << "TCP connect failed: " << ex.what();
118     fail(ex);
119     delete this;
120   }
121
122   void handshakeSuc(AsyncSSLSocket* /* sock */) noexcept override {
123     VLOG(7) << "client handshake success";
124     if (callback_) {
125       callback_->connectSuccess();
126     }
127     delete this;
128   }
129
130   void handshakeErr(AsyncSSLSocket* /* socket */,
131                     const AsyncSocketException& ex) noexcept override {
132     VLOG(1) << "client handshakeErr: " << ex.what();
133     fail(ex);
134     delete this;
135   }
136
137   void fail(const AsyncSocketException &ex) {
138     // fail is a noop if called twice
139     if (callback_) {
140       AsyncSSLSocket::ConnectCallback *cb = callback_;
141       callback_ = nullptr;
142
143       cb->connectErr(ex);
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
147       // point
148       // Note that closeNow may invoke writeError callbacks if the socket had
149       // write data pending connection completion.
150     }
151   }
152 };
153
154 // XXX: implement an equivalent to corking for platforms with TCP_NOPUSH?
155 #ifdef TCP_CORK // Linux-only
156 /**
157  * Utility class that corks a TCP socket upon construction or uncorks
158  * the socket upon destruction
159  */
160 class CorkGuard : private boost::noncopyable {
161  public:
162   CorkGuard(int fd, bool multipleWrites, bool haveMore, bool* corked):
163     fd_(fd), haveMore_(haveMore), corked_(corked) {
164     if (*corked_) {
165       // socket is already corked; nothing to do
166       return;
167     }
168     if (multipleWrites || haveMore) {
169       // We are performing multiple writes in this performWrite() call,
170       // and/or there are more calls to performWrite() that will be invoked
171       // later, so enable corking
172       int flag = 1;
173       setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
174       *corked_ = true;
175     }
176   }
177
178   ~CorkGuard() {
179     if (haveMore_) {
180       // more data to come; don't uncork yet
181       return;
182     }
183     if (!*corked_) {
184       // socket isn't corked; nothing to do
185       return;
186     }
187
188     int flag = 0;
189     setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
190     *corked_ = false;
191   }
192
193  private:
194   int fd_;
195   bool haveMore_;
196   bool* corked_;
197 };
198 #else
199 class CorkGuard : private boost::noncopyable {
200  public:
201   CorkGuard(int, bool, bool, bool*) {}
202 };
203 #endif
204
205 void setup_SSL_CTX(SSL_CTX *ctx) {
206 #ifdef SSL_MODE_RELEASE_BUFFERS
207   SSL_CTX_set_mode(ctx,
208                    SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
209                    SSL_MODE_ENABLE_PARTIAL_WRITE
210                    | SSL_MODE_RELEASE_BUFFERS
211                    );
212 #else
213   SSL_CTX_set_mode(ctx,
214                    SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
215                    SSL_MODE_ENABLE_PARTIAL_WRITE
216                    );
217 #endif
218 // SSL_CTX_set_mode is a Macro
219 #ifdef SSL_MODE_WRITE_IOVEC
220   SSL_CTX_set_mode(ctx,
221                    SSL_CTX_get_mode(ctx)
222                    | SSL_MODE_WRITE_IOVEC);
223 #endif
224
225 }
226
227 BIO_METHOD sslWriteBioMethod;
228
229 void* initsslWriteBioMethod(void) {
230   memcpy(&sslWriteBioMethod, BIO_s_socket(), sizeof(sslWriteBioMethod));
231   // override the bwrite method for MSG_EOR support
232   OpenSSLUtils::setCustomBioWriteMethod(
233       &sslWriteBioMethod, AsyncSSLSocket::bioWrite);
234
235   // Note that the sslWriteBioMethod.type and sslWriteBioMethod.name are not
236   // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
237   // then have specific handlings. The sslWriteBioWrite should be compatible
238   // with the one in openssl.
239
240   // Return something here to enable AsyncSSLSocket to call this method using
241   // a function-scoped static.
242   return nullptr;
243 }
244
245 } // anonymous namespace
246
247 namespace folly {
248
249 /**
250  * Create a client AsyncSSLSocket
251  */
252 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
253                                EventBase* evb, bool deferSecurityNegotiation) :
254     AsyncSocket(evb),
255     ctx_(ctx),
256     handshakeTimeout_(this, evb),
257     connectionTimeout_(this, evb) {
258   init();
259   if (deferSecurityNegotiation) {
260     sslState_ = STATE_UNENCRYPTED;
261   }
262 }
263
264 /**
265  * Create a server/client AsyncSSLSocket
266  */
267 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
268                                EventBase* evb, int fd, bool server,
269                                bool deferSecurityNegotiation) :
270     AsyncSocket(evb, fd),
271     server_(server),
272     ctx_(ctx),
273     handshakeTimeout_(this, evb),
274     connectionTimeout_(this, evb) {
275   init();
276   if (server) {
277     SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
278                               AsyncSSLSocket::sslInfoCallback);
279   }
280   if (deferSecurityNegotiation) {
281     sslState_ = STATE_UNENCRYPTED;
282   }
283 }
284
285 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
286 /**
287  * Create a client AsyncSSLSocket and allow tlsext_hostname
288  * to be sent in Client Hello.
289  */
290 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
291                                  EventBase* evb,
292                                const std::string& serverName,
293                                bool deferSecurityNegotiation) :
294     AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
295   tlsextHostname_ = serverName;
296 }
297
298 /**
299  * Create a client AsyncSSLSocket from an already connected fd
300  * and allow tlsext_hostname to be sent in Client Hello.
301  */
302 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
303                                  EventBase* evb, int fd,
304                                const std::string& serverName,
305                                bool deferSecurityNegotiation) :
306     AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
307   tlsextHostname_ = serverName;
308 }
309 #endif
310
311 AsyncSSLSocket::~AsyncSSLSocket() {
312   VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
313           << ", evb=" << eventBase_ << ", fd=" << fd_
314           << ", state=" << int(state_) << ", sslState="
315           << sslState_ << ", events=" << eventFlags_ << ")";
316 }
317
318 void AsyncSSLSocket::init() {
319   // Do this here to ensure we initialize this once before any use of
320   // AsyncSSLSocket instances and not as part of library load.
321   static const auto sslWriteBioMethodInitializer = initsslWriteBioMethod();
322   (void)sslWriteBioMethodInitializer;
323
324   setup_SSL_CTX(ctx_->getSSLCtx());
325 }
326
327 void AsyncSSLSocket::closeNow() {
328   // Close the SSL connection.
329   if (ssl_ != nullptr && fd_ != -1) {
330     int rc = SSL_shutdown(ssl_);
331     if (rc == 0) {
332       rc = SSL_shutdown(ssl_);
333     }
334     if (rc < 0) {
335       ERR_clear_error();
336     }
337   }
338
339   if (sslSession_ != nullptr) {
340     SSL_SESSION_free(sslSession_);
341     sslSession_ = nullptr;
342   }
343
344   sslState_ = STATE_CLOSED;
345
346   if (handshakeTimeout_.isScheduled()) {
347     handshakeTimeout_.cancelTimeout();
348   }
349
350   DestructorGuard dg(this);
351
352   invokeHandshakeErr(
353       AsyncSocketException(
354         AsyncSocketException::END_OF_FILE,
355         "SSL connection closed locally"));
356
357   if (ssl_ != nullptr) {
358     SSL_free(ssl_);
359     ssl_ = nullptr;
360   }
361
362   // Close the socket.
363   AsyncSocket::closeNow();
364 }
365
366 void AsyncSSLSocket::shutdownWrite() {
367   // SSL sockets do not support half-shutdown, so just perform a full shutdown.
368   //
369   // (Performing a full shutdown here is more desirable than doing nothing at
370   // all.  The purpose of shutdownWrite() is normally to notify the other end
371   // of the connection that no more data will be sent.  If we do nothing, the
372   // other end will never know that no more data is coming, and this may result
373   // in protocol deadlock.)
374   close();
375 }
376
377 void AsyncSSLSocket::shutdownWriteNow() {
378   closeNow();
379 }
380
381 bool AsyncSSLSocket::good() const {
382   return (AsyncSocket::good() &&
383           (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
384            sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
385 }
386
387 // The TAsyncTransport definition of 'good' states that the transport is
388 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
389 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
390 // is connected but we haven't initiated the call to SSL_connect.
391 bool AsyncSSLSocket::connecting() const {
392   return (!server_ &&
393           (AsyncSocket::connecting() ||
394            (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
395                                      sslState_ == STATE_CONNECTING))));
396 }
397
398 std::string AsyncSSLSocket::getApplicationProtocol() noexcept {
399   const unsigned char* protoName = nullptr;
400   unsigned protoLength;
401   if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) {
402     return std::string(reinterpret_cast<const char*>(protoName), protoLength);
403   }
404   return "";
405 }
406
407 bool AsyncSSLSocket::isEorTrackingEnabled() const {
408   return trackEor_;
409 }
410
411 void AsyncSSLSocket::setEorTracking(bool track) {
412   if (trackEor_ != track) {
413     trackEor_ = track;
414     appEorByteNo_ = 0;
415     minEorRawByteNo_ = 0;
416   }
417 }
418
419 size_t AsyncSSLSocket::getRawBytesWritten() const {
420   // The bio(s) in the write path are in a chain
421   // each bio flushes to the next and finally written into the socket
422   // to get the rawBytesWritten on the socket,
423   // get the write bytes of the last bio
424   BIO *b;
425   if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
426     return 0;
427   }
428   BIO* next = BIO_next(b);
429   while (next != NULL) {
430     b = next;
431     next = BIO_next(b);
432   }
433
434   return BIO_number_written(b);
435 }
436
437 size_t AsyncSSLSocket::getRawBytesReceived() const {
438   BIO *b;
439   if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
440     return 0;
441   }
442
443   return BIO_number_read(b);
444 }
445
446
447 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
448   LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
449              << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
450              << "events=" << eventFlags_ << ", server=" << short(server_)
451              << "): " << "sslAccept/Connect() called in invalid "
452              << "state, handshake callback " << handshakeCallback_
453              << ", new callback " << callback;
454   assert(!handshakeTimeout_.isScheduled());
455   sslState_ = STATE_ERROR;
456
457   AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
458                          "sslAccept() called with socket in invalid state");
459
460   handshakeEndTime_ = std::chrono::steady_clock::now();
461   if (callback) {
462     callback->handshakeErr(this, ex);
463   }
464
465   // Check the socket state not the ssl state here.
466   if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
467     failHandshake(__func__, ex);
468   }
469 }
470
471 void AsyncSSLSocket::sslAccept(HandshakeCB* callback, uint32_t timeout,
472       const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
473   DestructorGuard dg(this);
474   assert(eventBase_->isInEventBaseThread());
475   verifyPeer_ = verifyPeer;
476
477   // Make sure we're in the uninitialized state
478   if (!server_ || (sslState_ != STATE_UNINIT &&
479                    sslState_ != STATE_UNENCRYPTED) ||
480       handshakeCallback_ != nullptr) {
481     return invalidState(callback);
482   }
483
484   // Cache local and remote socket addresses to keep them available
485   // after socket file descriptor is closed.
486   if (cacheAddrOnFailure_ && -1 != getFd()) {
487     cacheLocalPeerAddr();
488   }
489
490   handshakeStartTime_ = std::chrono::steady_clock::now();
491   // Make end time at least >= start time.
492   handshakeEndTime_ = handshakeStartTime_;
493
494   sslState_ = STATE_ACCEPTING;
495   handshakeCallback_ = callback;
496
497   if (timeout > 0) {
498     handshakeTimeout_.scheduleTimeout(timeout);
499   }
500
501   /* register for a read operation (waiting for CLIENT HELLO) */
502   updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
503 }
504
505 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
506 void AsyncSSLSocket::attachSSLContext(
507   const std::shared_ptr<SSLContext>& ctx) {
508
509   // Check to ensure we are in client mode. Changing a server's ssl
510   // context doesn't make sense since clients of that server would likely
511   // become confused when the server's context changes.
512   DCHECK(!server_);
513   DCHECK(!ctx_);
514   DCHECK(ctx);
515   DCHECK(ctx->getSSLCtx());
516   ctx_ = ctx;
517
518   // In order to call attachSSLContext, detachSSLContext must have been
519   // previously called which sets the socket's context to the dummy
520   // context. Thus we must acquire this lock.
521   SpinLockGuard guard(dummyCtxLock);
522   SSL_set_SSL_CTX(ssl_, ctx->getSSLCtx());
523 }
524
525 void AsyncSSLSocket::detachSSLContext() {
526   DCHECK(ctx_);
527   ctx_.reset();
528   // We aren't using the initial_ctx for now, and it can introduce race
529   // conditions in the destructor of the SSL object.
530 #ifndef OPENSSL_NO_TLSEXT
531   if (ssl_->initial_ctx) {
532     SSL_CTX_free(ssl_->initial_ctx);
533     ssl_->initial_ctx = nullptr;
534   }
535 #endif
536   SpinLockGuard guard(dummyCtxLock);
537   if (nullptr == dummyCtx) {
538     // We need to lazily initialize the dummy context so we don't
539     // accidentally override any programmatic settings to openssl
540     dummyCtx = new SSLContext;
541   }
542   // We must remove this socket's references to its context right now
543   // since this socket could get passed to any thread. If the context has
544   // had its locking disabled, just doing a set in attachSSLContext()
545   // would not be thread safe.
546   SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
547 }
548 #endif
549
550 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
551 void AsyncSSLSocket::switchServerSSLContext(
552   const std::shared_ptr<SSLContext>& handshakeCtx) {
553   CHECK(server_);
554   if (sslState_ != STATE_ACCEPTING) {
555     // We log it here and allow the switch.
556     // It should not affect our re-negotiation support (which
557     // is not supported now).
558     VLOG(6) << "fd=" << getFd()
559             << " renegotation detected when switching SSL_CTX";
560   }
561
562   setup_SSL_CTX(handshakeCtx->getSSLCtx());
563   SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
564                             AsyncSSLSocket::sslInfoCallback);
565   handshakeCtx_ = handshakeCtx;
566   SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
567 }
568
569 bool AsyncSSLSocket::isServerNameMatch() const {
570   CHECK(!server_);
571
572   if (!ssl_) {
573     return false;
574   }
575
576   SSL_SESSION *ss = SSL_get_session(ssl_);
577   if (!ss) {
578     return false;
579   }
580
581   if(!ss->tlsext_hostname) {
582     return false;
583   }
584   return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
585 }
586
587 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
588   tlsextHostname_ = std::move(serverName);
589 }
590
591 #endif
592
593 void AsyncSSLSocket::timeoutExpired() noexcept {
594   if (state_ == StateEnum::ESTABLISHED &&
595       (sslState_ == STATE_CACHE_LOOKUP ||
596        sslState_ == STATE_ASYNC_PENDING)) {
597     sslState_ = STATE_ERROR;
598     // We are expecting a callback in restartSSLAccept.  The cache lookup
599     // and rsa-call necessarily have pointers to this ssl socket, so delay
600     // the cleanup until he calls us back.
601   } else if (state_ == StateEnum::CONNECTING) {
602     assert(sslState_ == STATE_CONNECTING);
603     DestructorGuard dg(this);
604     AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
605                            "Fallback connect timed out during TFO");
606     failHandshake(__func__, ex);
607   } else {
608     assert(state_ == StateEnum::ESTABLISHED &&
609            (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
610     DestructorGuard dg(this);
611     AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
612                            (sslState_ == STATE_CONNECTING) ?
613                            "SSL connect timed out" : "SSL accept timed out");
614     failHandshake(__func__, ex);
615   }
616 }
617
618 int AsyncSSLSocket::getSSLExDataIndex() {
619   static auto index = SSL_get_ex_new_index(
620       0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
621   return index;
622 }
623
624 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
625   return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
626       getSSLExDataIndex()));
627 }
628
629 void AsyncSSLSocket::failHandshake(const char* /* fn */,
630                                    const AsyncSocketException& ex) {
631   startFail();
632   if (handshakeTimeout_.isScheduled()) {
633     handshakeTimeout_.cancelTimeout();
634   }
635   invokeHandshakeErr(ex);
636   finishFail();
637 }
638
639 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
640   handshakeEndTime_ = std::chrono::steady_clock::now();
641   if (handshakeCallback_ != nullptr) {
642     HandshakeCB* callback = handshakeCallback_;
643     handshakeCallback_ = nullptr;
644     callback->handshakeErr(this, ex);
645   }
646 }
647
648 void AsyncSSLSocket::invokeHandshakeCB() {
649   handshakeEndTime_ = std::chrono::steady_clock::now();
650   if (handshakeTimeout_.isScheduled()) {
651     handshakeTimeout_.cancelTimeout();
652   }
653   if (handshakeCallback_) {
654     HandshakeCB* callback = handshakeCallback_;
655     handshakeCallback_ = nullptr;
656     callback->handshakeSuc(this);
657   }
658 }
659
660 void AsyncSSLSocket::cacheLocalPeerAddr() {
661   SocketAddress address;
662   try {
663     getLocalAddress(&address);
664     getPeerAddress(&address);
665   } catch (const std::system_error& e) {
666     // The handle can be still valid while the connection is already closed.
667     if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
668       throw;
669     }
670   }
671 }
672
673 void AsyncSSLSocket::connect(ConnectCallback* callback,
674                               const folly::SocketAddress& address,
675                               int timeout,
676                               const OptionMap &options,
677                               const folly::SocketAddress& bindAddr)
678                               noexcept {
679   assert(!server_);
680   assert(state_ == StateEnum::UNINIT);
681   assert(sslState_ == STATE_UNINIT);
682   AsyncSSLSocketConnector *connector =
683     new AsyncSSLSocketConnector(this, callback, timeout);
684   AsyncSocket::connect(connector, address, timeout, options, bindAddr);
685 }
686
687 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
688   // apply the settings specified in verifyPeer_
689   if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
690     if(ctx_->needsPeerVerification()) {
691       SSL_set_verify(ssl, ctx_->getVerificationMode(),
692         AsyncSSLSocket::sslVerifyCallback);
693     }
694   } else {
695     if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
696         verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
697       SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
698         AsyncSSLSocket::sslVerifyCallback);
699     }
700   }
701 }
702
703 bool AsyncSSLSocket::setupSSLBio() {
704   auto wb = BIO_new(&sslWriteBioMethod);
705
706   if (!wb) {
707     return false;
708   }
709
710   OpenSSLUtils::setBioAppData(wb, this);
711   OpenSSLUtils::setBioFd(wb, fd_, BIO_NOCLOSE);
712   SSL_set_bio(ssl_, wb, wb);
713   return true;
714 }
715
716 void AsyncSSLSocket::sslConn(HandshakeCB* callback, uint64_t timeout,
717         const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
718   DestructorGuard dg(this);
719   assert(eventBase_->isInEventBaseThread());
720
721   // Cache local and remote socket addresses to keep them available
722   // after socket file descriptor is closed.
723   if (cacheAddrOnFailure_ && -1 != getFd()) {
724     cacheLocalPeerAddr();
725   }
726
727   verifyPeer_ = verifyPeer;
728
729   // Make sure we're in the uninitialized state
730   if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
731                   STATE_UNENCRYPTED) ||
732       handshakeCallback_ != nullptr) {
733     return invalidState(callback);
734   }
735
736   sslState_ = STATE_CONNECTING;
737   handshakeCallback_ = callback;
738
739   try {
740     ssl_ = ctx_->createSSL();
741   } catch (std::exception &e) {
742     sslState_ = STATE_ERROR;
743     AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
744                            "error calling SSLContext::createSSL()");
745     LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
746             << fd_ << "): " << e.what();
747     return failHandshake(__func__, ex);
748   }
749
750   if (!setupSSLBio()) {
751     sslState_ = STATE_ERROR;
752     AsyncSocketException ex(
753         AsyncSocketException::INTERNAL_ERROR, "error creating SSL bio");
754     return failHandshake(__func__, ex);
755   }
756
757   applyVerificationOptions(ssl_);
758
759   if (sslSession_ != nullptr) {
760     sessionResumptionAttempted_ = true;
761     SSL_set_session(ssl_, sslSession_);
762     SSL_SESSION_free(sslSession_);
763     sslSession_ = nullptr;
764   }
765 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
766   if (tlsextHostname_.size()) {
767     SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
768   }
769 #endif
770
771   SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
772
773   handshakeConnectTimeout_ = timeout;
774   startSSLConnect();
775 }
776
777 // This could be called multiple times, during normal ssl connections
778 // and after TFO fallback.
779 void AsyncSSLSocket::startSSLConnect() {
780   handshakeStartTime_ = std::chrono::steady_clock::now();
781   // Make end time at least >= start time.
782   handshakeEndTime_ = handshakeStartTime_;
783   if (handshakeConnectTimeout_ > 0) {
784     handshakeTimeout_.scheduleTimeout(handshakeConnectTimeout_);
785   }
786   handleConnect();
787 }
788
789 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
790   if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
791     return SSL_get1_session(ssl_);
792   }
793
794   return sslSession_;
795 }
796
797 const SSL* AsyncSSLSocket::getSSL() const {
798   return ssl_;
799 }
800
801 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
802   sslSession_ = session;
803   if (!takeOwnership && session != nullptr) {
804     // Increment the reference count
805     CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
806   }
807 }
808
809 void AsyncSSLSocket::getSelectedNextProtocol(
810     const unsigned char** protoName,
811     unsigned* protoLen,
812     SSLContext::NextProtocolType* protoType) const {
813   if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
814     throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
815                               "NPN not supported");
816   }
817 }
818
819 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
820     const unsigned char** protoName,
821     unsigned* protoLen,
822     SSLContext::NextProtocolType* protoType) const {
823   *protoName = nullptr;
824   *protoLen = 0;
825 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
826   SSL_get0_alpn_selected(ssl_, protoName, protoLen);
827   if (*protoLen > 0) {
828     if (protoType) {
829       *protoType = SSLContext::NextProtocolType::ALPN;
830     }
831     return true;
832   }
833 #endif
834 #ifdef OPENSSL_NPN_NEGOTIATED
835   SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
836   if (protoType) {
837     *protoType = SSLContext::NextProtocolType::NPN;
838   }
839   return true;
840 #else
841   (void)protoType;
842   return false;
843 #endif
844 }
845
846 bool AsyncSSLSocket::getSSLSessionReused() const {
847   if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
848     return SSL_session_reused(ssl_);
849   }
850   return false;
851 }
852
853 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
854   return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
855 }
856
857 /* static */
858 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
859   if (ssl == nullptr) {
860     return nullptr;
861   }
862 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
863   return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
864 #else
865   return nullptr;
866 #endif
867 }
868
869 const char *AsyncSSLSocket::getSSLServerName() const {
870 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
871   return getSSLServerNameFromSSL(ssl_);
872 #else
873   throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
874                              "SNI not supported");
875 #endif
876 }
877
878 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
879   return getSSLServerNameFromSSL(ssl_);
880 }
881
882 int AsyncSSLSocket::getSSLVersion() const {
883   return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
884 }
885
886 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
887   X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
888   if (cert) {
889     int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
890     return OBJ_nid2ln(nid);
891   }
892   return nullptr;
893 }
894
895 int AsyncSSLSocket::getSSLCertSize() const {
896   int certSize = 0;
897   X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
898   if (cert) {
899     EVP_PKEY *key = X509_get_pubkey(cert);
900     certSize = EVP_PKEY_bits(key);
901     EVP_PKEY_free(key);
902   }
903   return certSize;
904 }
905
906 const X509* AsyncSSLSocket::getSelfCert() const {
907   return (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
908 }
909
910 bool AsyncSSLSocket::willBlock(int ret,
911                                int* sslErrorOut,
912                                unsigned long* errErrorOut) noexcept {
913   *errErrorOut = 0;
914   int error = *sslErrorOut = SSL_get_error(ssl_, ret);
915   if (error == SSL_ERROR_WANT_READ) {
916     // Register for read event if not already.
917     updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
918     return true;
919   } else if (error == SSL_ERROR_WANT_WRITE) {
920     VLOG(3) << "AsyncSSLSocket(fd=" << fd_
921             << ", state=" << int(state_) << ", sslState="
922             << sslState_ << ", events=" << eventFlags_ << "): "
923             << "SSL_ERROR_WANT_WRITE";
924     // Register for write event if not already.
925     updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
926     return true;
927 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
928   } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
929     // We will block but we can't register our own socket.  The callback that
930     // triggered this code will re-call handleAccept at the appropriate time.
931
932     // We can only get here if the linked libssl.so has support for this feature
933     // as well, otherwise SSL_get_error cannot return our error code.
934     sslState_ = STATE_CACHE_LOOKUP;
935
936     // Unregister for all events while blocked here
937     updateEventRegistration(EventHandler::NONE,
938                             EventHandler::READ | EventHandler::WRITE);
939
940     // The timeout (if set) keeps running here
941     return true;
942 #endif
943   } else if (0
944 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
945       || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
946 #endif
947 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
948       || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
949 #endif
950       ) {
951     // Our custom openssl function has kicked off an async request to do
952     // rsa/ecdsa private key operation.  When that call returns, a callback will
953     // be invoked that will re-call handleAccept.
954     sslState_ = STATE_ASYNC_PENDING;
955
956     // Unregister for all events while blocked here
957     updateEventRegistration(
958       EventHandler::NONE,
959       EventHandler::READ | EventHandler::WRITE
960     );
961
962     // The timeout (if set) keeps running here
963     return true;
964   } else {
965     unsigned long lastError = *errErrorOut = ERR_get_error();
966     VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
967             << "state=" << state_ << ", "
968             << "sslState=" << sslState_ << ", "
969             << "events=" << std::hex << eventFlags_ << "): "
970             << "SSL error: " << error << ", "
971             << "errno: " << errno << ", "
972             << "ret: " << ret << ", "
973             << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
974             << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
975             << "func: " << ERR_func_error_string(lastError) << ", "
976             << "reason: " << ERR_reason_error_string(lastError);
977     return false;
978   }
979 }
980
981 void AsyncSSLSocket::checkForImmediateRead() noexcept {
982   // openssl may have buffered data that it read from the socket already.
983   // In this case we have to process it immediately, rather than waiting for
984   // the socket to become readable again.
985   if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
986     AsyncSocket::handleRead();
987   }
988 }
989
990 void
991 AsyncSSLSocket::restartSSLAccept()
992 {
993   VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this
994           << ", fd=" << fd_ << ", state=" << int(state_) << ", "
995           << "sslState=" << sslState_ << ", events=" << eventFlags_;
996   DestructorGuard dg(this);
997   assert(
998     sslState_ == STATE_CACHE_LOOKUP ||
999     sslState_ == STATE_ASYNC_PENDING ||
1000     sslState_ == STATE_ERROR ||
1001     sslState_ == STATE_CLOSED);
1002   if (sslState_ == STATE_CLOSED) {
1003     // I sure hope whoever closed this socket didn't delete it already,
1004     // but this is not strictly speaking an error
1005     return;
1006   }
1007   if (sslState_ == STATE_ERROR) {
1008     // go straight to fail if timeout expired during lookup
1009     AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
1010                            "SSL accept timed out");
1011     failHandshake(__func__, ex);
1012     return;
1013   }
1014   sslState_ = STATE_ACCEPTING;
1015   this->handleAccept();
1016 }
1017
1018 void
1019 AsyncSSLSocket::handleAccept() noexcept {
1020   VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
1021           << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1022           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1023   assert(server_);
1024   assert(state_ == StateEnum::ESTABLISHED &&
1025          sslState_ == STATE_ACCEPTING);
1026   if (!ssl_) {
1027     /* lazily create the SSL structure */
1028     try {
1029       ssl_ = ctx_->createSSL();
1030     } catch (std::exception &e) {
1031       sslState_ = STATE_ERROR;
1032       AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1033                              "error calling SSLContext::createSSL()");
1034       LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
1035                  << ", fd=" << fd_ << "): " << e.what();
1036       return failHandshake(__func__, ex);
1037     }
1038
1039     if (!setupSSLBio()) {
1040       sslState_ = STATE_ERROR;
1041       AsyncSocketException ex(
1042           AsyncSocketException::INTERNAL_ERROR, "error creating write bio");
1043       return failHandshake(__func__, ex);
1044     }
1045
1046     SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
1047
1048     applyVerificationOptions(ssl_);
1049   }
1050
1051   if (server_ && parseClientHello_) {
1052     SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1053     SSL_set_msg_callback_arg(ssl_, this);
1054   }
1055
1056   int ret = SSL_accept(ssl_);
1057   if (ret <= 0) {
1058     int sslError;
1059     unsigned long errError;
1060     int errnoCopy = errno;
1061     if (willBlock(ret, &sslError, &errError)) {
1062       return;
1063     } else {
1064       sslState_ = STATE_ERROR;
1065       SSLException ex(sslError, errError, ret, errnoCopy);
1066       return failHandshake(__func__, ex);
1067     }
1068   }
1069
1070   handshakeComplete_ = true;
1071   updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1072
1073   // Move into STATE_ESTABLISHED in the normal case that we are in
1074   // STATE_ACCEPTING.
1075   sslState_ = STATE_ESTABLISHED;
1076
1077   VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1078           << " successfully accepted; state=" << int(state_)
1079           << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1080
1081   // Remember the EventBase we are attached to, before we start invoking any
1082   // callbacks (since the callbacks may call detachEventBase()).
1083   EventBase* originalEventBase = eventBase_;
1084
1085   // Call the accept callback.
1086   invokeHandshakeCB();
1087
1088   // Note that the accept callback may have changed our state.
1089   // (set or unset the read callback, called write(), closed the socket, etc.)
1090   // The following code needs to handle these situations correctly.
1091   //
1092   // If the socket has been closed, readCallback_ and writeReqHead_ will
1093   // always be nullptr, so that will prevent us from trying to read or write.
1094   //
1095   // The main thing to check for is if eventBase_ is still originalEventBase.
1096   // If not, we have been detached from this event base, so we shouldn't
1097   // perform any more operations.
1098   if (eventBase_ != originalEventBase) {
1099     return;
1100   }
1101
1102   AsyncSocket::handleInitialReadWrite();
1103 }
1104
1105 void
1106 AsyncSSLSocket::handleConnect() noexcept {
1107   VLOG(3) <<  "AsyncSSLSocket::handleConnect() this=" << this
1108           << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1109           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1110   assert(!server_);
1111   if (state_ < StateEnum::ESTABLISHED) {
1112     return AsyncSocket::handleConnect();
1113   }
1114
1115   assert(
1116       (state_ == StateEnum::FAST_OPEN || state_ == StateEnum::ESTABLISHED) &&
1117       sslState_ == STATE_CONNECTING);
1118   assert(ssl_);
1119
1120   auto originalState = state_;
1121   int ret = SSL_connect(ssl_);
1122   if (ret <= 0) {
1123     int sslError;
1124     unsigned long errError;
1125     int errnoCopy = errno;
1126     if (willBlock(ret, &sslError, &errError)) {
1127       // We fell back to connecting state due to TFO
1128       if (state_ == StateEnum::CONNECTING) {
1129         DCHECK_EQ(StateEnum::FAST_OPEN, originalState);
1130         if (handshakeTimeout_.isScheduled()) {
1131           handshakeTimeout_.cancelTimeout();
1132         }
1133       }
1134       return;
1135     } else {
1136       sslState_ = STATE_ERROR;
1137       SSLException ex(sslError, errError, ret, errnoCopy);
1138       return failHandshake(__func__, ex);
1139     }
1140   }
1141
1142   handshakeComplete_ = true;
1143   updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1144
1145   // Move into STATE_ESTABLISHED in the normal case that we are in
1146   // STATE_CONNECTING.
1147   sslState_ = STATE_ESTABLISHED;
1148
1149   VLOG(3) << "AsyncSSLSocket " << this << ": "
1150           << "fd " << fd_ << " successfully connected; "
1151           << "state=" << int(state_) << ", sslState=" << sslState_
1152           << ", events=" << eventFlags_;
1153
1154   // Remember the EventBase we are attached to, before we start invoking any
1155   // callbacks (since the callbacks may call detachEventBase()).
1156   EventBase* originalEventBase = eventBase_;
1157
1158   // Call the handshake callback.
1159   invokeHandshakeCB();
1160
1161   // Note that the connect callback may have changed our state.
1162   // (set or unset the read callback, called write(), closed the socket, etc.)
1163   // The following code needs to handle these situations correctly.
1164   //
1165   // If the socket has been closed, readCallback_ and writeReqHead_ will
1166   // always be nullptr, so that will prevent us from trying to read or write.
1167   //
1168   // The main thing to check for is if eventBase_ is still originalEventBase.
1169   // If not, we have been detached from this event base, so we shouldn't
1170   // perform any more operations.
1171   if (eventBase_ != originalEventBase) {
1172     return;
1173   }
1174
1175   AsyncSocket::handleInitialReadWrite();
1176 }
1177
1178 void AsyncSSLSocket::invokeConnectErr(const AsyncSocketException& ex) {
1179   connectionTimeout_.cancelTimeout();
1180   AsyncSocket::invokeConnectErr(ex);
1181 }
1182
1183 void AsyncSSLSocket::invokeConnectSuccess() {
1184   connectionTimeout_.cancelTimeout();
1185   if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1186     // If we failed TFO, we'd fall back to trying to connect the socket,
1187     // to setup things like timeouts.
1188     startSSLConnect();
1189   }
1190   // still invoke the base class since it re-sets the connect time.
1191   AsyncSocket::invokeConnectSuccess();
1192 }
1193
1194 void AsyncSSLSocket::scheduleConnectTimeout() {
1195   if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1196     // We fell back from TFO, and need to set the timeouts.
1197     // We will not have a connect callback in this case, thus if the timer
1198     // expires we would have no-one to notify.
1199     // Thus we should reset even the connect timers to point to the handshake
1200     // timeouts.
1201     assert(connectCallback_ == nullptr);
1202     // We use a different connect timeout here than the handshake timeout, so
1203     // that we can disambiguate the 2 timers.
1204     int timeout = connectTimeout_.count();
1205     if (timeout > 0) {
1206       if (!connectionTimeout_.scheduleTimeout(timeout)) {
1207         throw AsyncSocketException(
1208             AsyncSocketException::INTERNAL_ERROR,
1209             withAddr("failed to schedule AsyncSSLSocket connect timeout"));
1210       }
1211     }
1212     return;
1213   }
1214   AsyncSocket::scheduleConnectTimeout();
1215 }
1216
1217 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1218 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1219   // turn on the buffer movable in openssl
1220   if (bufferMovableEnabled_ && ssl_ != nullptr && !isBufferMovable_ &&
1221       callback != nullptr && callback->isBufferMovable()) {
1222     SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1223     isBufferMovable_ = true;
1224   }
1225 #endif
1226
1227   AsyncSocket::setReadCB(callback);
1228 }
1229
1230 void AsyncSSLSocket::setBufferMovableEnabled(bool enabled) {
1231   bufferMovableEnabled_ = enabled;
1232 }
1233
1234 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) noexcept {
1235   CHECK(readCallback_);
1236   if (isBufferMovable_) {
1237     *buf = nullptr;
1238     *buflen = 0;
1239   } else {
1240     // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1241     readCallback_->getReadBuffer(buf, buflen);
1242   }
1243 }
1244
1245 void
1246 AsyncSSLSocket::handleRead() noexcept {
1247   VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1248           << ", state=" << int(state_) << ", "
1249           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1250   if (state_ < StateEnum::ESTABLISHED) {
1251     return AsyncSocket::handleRead();
1252   }
1253
1254
1255   if (sslState_ == STATE_ACCEPTING) {
1256     assert(server_);
1257     handleAccept();
1258     return;
1259   }
1260   else if (sslState_ == STATE_CONNECTING) {
1261     assert(!server_);
1262     handleConnect();
1263     return;
1264   }
1265
1266   // Normal read
1267   AsyncSocket::handleRead();
1268 }
1269
1270 AsyncSocket::ReadResult
1271 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1272   VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf
1273           << ", buflen=" << *buflen;
1274
1275   if (sslState_ == STATE_UNENCRYPTED) {
1276     return AsyncSocket::performRead(buf, buflen, offset);
1277   }
1278
1279   ssize_t bytes = 0;
1280   if (!isBufferMovable_) {
1281     bytes = SSL_read(ssl_, *buf, *buflen);
1282   }
1283 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1284   else {
1285     bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1286   }
1287 #endif
1288
1289   if (server_ && renegotiateAttempted_) {
1290     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1291                << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1292                << "): client intitiated SSL renegotiation not permitted";
1293     return ReadResult(
1294         READ_ERROR,
1295         folly::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION));
1296   }
1297   if (bytes <= 0) {
1298     int error = SSL_get_error(ssl_, bytes);
1299     if (error == SSL_ERROR_WANT_READ) {
1300       // The caller will register for read event if not already.
1301       if (errno == EWOULDBLOCK || errno == EAGAIN) {
1302         return ReadResult(READ_BLOCKING);
1303       } else {
1304         return ReadResult(READ_ERROR);
1305       }
1306     } else if (error == SSL_ERROR_WANT_WRITE) {
1307       // TODO: Even though we are attempting to read data, SSL_read() may
1308       // need to write data if renegotiation is being performed.  We currently
1309       // don't support this and just fail the read.
1310       LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1311                  << ", sslState=" << sslState_ << ", events=" << eventFlags_
1312                  << "): unsupported SSL renegotiation during read";
1313       return ReadResult(
1314           READ_ERROR,
1315           folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1316     } else {
1317       if (zero_return(error, bytes)) {
1318         return ReadResult(bytes);
1319       }
1320       long errError = ERR_get_error();
1321       VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1322               << "state=" << state_ << ", "
1323               << "sslState=" << sslState_ << ", "
1324               << "events=" << std::hex << eventFlags_ << "): "
1325               << "bytes: " << bytes << ", "
1326               << "error: " << error << ", "
1327               << "errno: " << errno << ", "
1328               << "func: " << ERR_func_error_string(errError) << ", "
1329               << "reason: " << ERR_reason_error_string(errError);
1330       return ReadResult(
1331           READ_ERROR,
1332           folly::make_unique<SSLException>(error, errError, bytes, errno));
1333     }
1334   } else {
1335     appBytesReceived_ += bytes;
1336     return ReadResult(bytes);
1337   }
1338 }
1339
1340 void AsyncSSLSocket::handleWrite() noexcept {
1341   VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1342           << ", state=" << int(state_) << ", "
1343           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1344   if (state_ < StateEnum::ESTABLISHED) {
1345     return AsyncSocket::handleWrite();
1346   }
1347
1348   if (sslState_ == STATE_ACCEPTING) {
1349     assert(server_);
1350     handleAccept();
1351     return;
1352   }
1353
1354   if (sslState_ == STATE_CONNECTING) {
1355     assert(!server_);
1356     handleConnect();
1357     return;
1358   }
1359
1360   // Normal write
1361   AsyncSocket::handleWrite();
1362 }
1363
1364 AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {
1365   if (error == SSL_ERROR_WANT_READ) {
1366     // Even though we are attempting to write data, SSL_write() may
1367     // need to read data if renegotiation is being performed.  We currently
1368     // don't support this and just fail the write.
1369     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1370                << ", sslState=" << sslState_ << ", events=" << eventFlags_
1371                << "): "
1372                << "unsupported SSL renegotiation during write";
1373     return WriteResult(
1374         WRITE_ERROR,
1375         folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1376   } else {
1377     if (zero_return(error, rc)) {
1378       return WriteResult(0);
1379     }
1380     auto errError = ERR_get_error();
1381     VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1382             << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1383             << "SSL error: " << error << ", errno: " << errno
1384             << ", func: " << ERR_func_error_string(errError)
1385             << ", reason: " << ERR_reason_error_string(errError);
1386     return WriteResult(
1387         WRITE_ERROR,
1388         folly::make_unique<SSLException>(error, errError, rc, errno));
1389   }
1390 }
1391
1392 AsyncSocket::WriteResult AsyncSSLSocket::performWrite(
1393     const iovec* vec,
1394     uint32_t count,
1395     WriteFlags flags,
1396     uint32_t* countWritten,
1397     uint32_t* partialWritten) {
1398   if (sslState_ == STATE_UNENCRYPTED) {
1399     return AsyncSocket::performWrite(
1400       vec, count, flags, countWritten, partialWritten);
1401   }
1402   if (sslState_ != STATE_ESTABLISHED) {
1403     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1404                << ", sslState=" << sslState_
1405                << ", events=" << eventFlags_ << "): "
1406                << "TODO: AsyncSSLSocket currently does not support calling "
1407                << "write() before the handshake has fully completed";
1408     return WriteResult(
1409         WRITE_ERROR, folly::make_unique<SSLException>(SSLError::EARLY_WRITE));
1410   }
1411
1412   bool cork = isSet(flags, WriteFlags::CORK);
1413   CorkGuard guard(fd_, count > 1, cork, &corked_);
1414
1415   // Declare a buffer used to hold small write requests.  It could point to a
1416   // memory block either on stack or on heap. If it is on heap, we release it
1417   // manually when scope exits
1418   char* combinedBuf{nullptr};
1419   SCOPE_EXIT {
1420     // Note, always keep this check consistent with what we do below
1421     if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1422       delete[] combinedBuf;
1423     }
1424   };
1425
1426   *countWritten = 0;
1427   *partialWritten = 0;
1428   ssize_t totalWritten = 0;
1429   size_t bytesStolenFromNextBuffer = 0;
1430   for (uint32_t i = 0; i < count; i++) {
1431     const iovec* v = vec + i;
1432     size_t offset = bytesStolenFromNextBuffer;
1433     bytesStolenFromNextBuffer = 0;
1434     size_t len = v->iov_len - offset;
1435     const void* buf;
1436     if (len == 0) {
1437       (*countWritten)++;
1438       continue;
1439     }
1440     buf = ((const char*)v->iov_base) + offset;
1441
1442     ssize_t bytes;
1443     uint32_t buffersStolen = 0;
1444     if ((len < minWriteSize_) && ((i + 1) < count)) {
1445       // Combine this buffer with part or all of the next buffers in
1446       // order to avoid really small-grained calls to SSL_write().
1447       // Each call to SSL_write() produces a separate record in
1448       // the egress SSL stream, and we've found that some low-end
1449       // mobile clients can't handle receiving an HTTP response
1450       // header and the first part of the response body in two
1451       // separate SSL records (even if those two records are in
1452       // the same TCP packet).
1453
1454       if (combinedBuf == nullptr) {
1455         if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1456           // Allocate the buffer on heap
1457           combinedBuf = new char[minWriteSize_];
1458         } else {
1459           // Allocate the buffer on stack
1460           combinedBuf = (char*)alloca(minWriteSize_);
1461         }
1462       }
1463       assert(combinedBuf != nullptr);
1464
1465       memcpy(combinedBuf, buf, len);
1466       do {
1467         // INVARIANT: i + buffersStolen == complete chunks serialized
1468         uint32_t nextIndex = i + buffersStolen + 1;
1469         bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1470                                              minWriteSize_ - len);
1471         memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1472                bytesStolenFromNextBuffer);
1473         len += bytesStolenFromNextBuffer;
1474         if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1475           // couldn't steal the whole buffer
1476           break;
1477         } else {
1478           bytesStolenFromNextBuffer = 0;
1479           buffersStolen++;
1480         }
1481       } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1482       bytes = eorAwareSSLWrite(
1483         ssl_, combinedBuf, len,
1484         (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1485
1486     } else {
1487       bytes = eorAwareSSLWrite(ssl_, buf, len,
1488                            (isSet(flags, WriteFlags::EOR) && i + 1 == count));
1489     }
1490
1491     if (bytes <= 0) {
1492       int error = SSL_get_error(ssl_, bytes);
1493       if (error == SSL_ERROR_WANT_WRITE) {
1494         // The caller will register for write event if not already.
1495         *partialWritten = offset;
1496         return WriteResult(totalWritten);
1497       }
1498       auto writeResult = interpretSSLError(bytes, error);
1499       if (writeResult.writeReturn < 0) {
1500         return writeResult;
1501       } // else fall through to below to correctly record totalWritten
1502     }
1503
1504     totalWritten += bytes;
1505
1506     if (bytes == (ssize_t)len) {
1507       // The full iovec is written.
1508       (*countWritten) += 1 + buffersStolen;
1509       i += buffersStolen;
1510       // continue
1511     } else {
1512       bytes += offset; // adjust bytes to account for all of v
1513       while (bytes >= (ssize_t)v->iov_len) {
1514         // We combined this buf with part or all of the next one, and
1515         // we managed to write all of this buf but not all of the bytes
1516         // from the next one that we'd hoped to write.
1517         bytes -= v->iov_len;
1518         (*countWritten)++;
1519         v = &(vec[++i]);
1520       }
1521       *partialWritten = bytes;
1522       return WriteResult(totalWritten);
1523     }
1524   }
1525
1526   return WriteResult(totalWritten);
1527 }
1528
1529 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1530                                       bool eor) {
1531   if (eor && trackEor_) {
1532     if (appEorByteNo_) {
1533       // cannot track for more than one app byte EOR
1534       CHECK(appEorByteNo_ == appBytesWritten_ + n);
1535     } else {
1536       appEorByteNo_ = appBytesWritten_ + n;
1537     }
1538
1539     // 1. It is fine to keep updating minEorRawByteNo_.
1540     // 2. It is _min_ in the sense that SSL record will add some overhead.
1541     minEorRawByteNo_ = getRawBytesWritten() + n;
1542   }
1543
1544   n = sslWriteImpl(ssl, buf, n);
1545   if (n > 0) {
1546     appBytesWritten_ += n;
1547     if (appEorByteNo_) {
1548       if (getRawBytesWritten() >= minEorRawByteNo_) {
1549         minEorRawByteNo_ = 0;
1550       }
1551       if(appBytesWritten_ == appEorByteNo_) {
1552         appEorByteNo_ = 0;
1553       } else {
1554         CHECK(appBytesWritten_ < appEorByteNo_);
1555       }
1556     }
1557   }
1558   return n;
1559 }
1560
1561 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) {
1562   AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1563   if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1564     sslSocket->renegotiateAttempted_ = true;
1565   }
1566   if (where & SSL_CB_READ_ALERT) {
1567     const char* type = SSL_alert_type_string(ret);
1568     if (type) {
1569       const char* desc = SSL_alert_desc_string(ret);
1570       sslSocket->alertsReceived_.emplace_back(
1571           *type, StringPiece(desc, std::strlen(desc)));
1572     }
1573   }
1574 }
1575
1576 int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) {
1577   struct msghdr msg;
1578   struct iovec iov;
1579   int flags = 0;
1580   AsyncSSLSocket* tsslSock;
1581
1582   iov.iov_base = const_cast<char*>(in);
1583   iov.iov_len = inl;
1584   memset(&msg, 0, sizeof(msg));
1585   msg.msg_iov = &iov;
1586   msg.msg_iovlen = 1;
1587
1588   auto appData = OpenSSLUtils::getBioAppData(b);
1589   CHECK(appData);
1590
1591   tsslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1592   CHECK(tsslSock);
1593
1594   if (tsslSock->trackEor_ && tsslSock->minEorRawByteNo_ &&
1595       tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1596     flags = MSG_EOR;
1597   }
1598
1599 #ifdef MSG_NOSIGNAL
1600   flags |= MSG_NOSIGNAL;
1601 #endif
1602
1603   auto result = tsslSock->sendSocketMessage(
1604       OpenSSLUtils::getBioFd(b, nullptr), &msg, flags);
1605   BIO_clear_retry_flags(b);
1606   if (!result.exception && result.writeReturn <= 0) {
1607     if (OpenSSLUtils::getBioShouldRetryWrite(result.writeReturn)) {
1608       BIO_set_retry_write(b);
1609     }
1610   }
1611   return result.writeReturn;
1612 }
1613
1614 int AsyncSSLSocket::sslVerifyCallback(
1615     int preverifyOk,
1616     X509_STORE_CTX* x509Ctx) {
1617   SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1618     x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1619   AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1620
1621   VLOG(3) <<  "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1622           << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1623   return (self->handshakeCallback_) ?
1624     self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1625     preverifyOk;
1626 }
1627
1628 void AsyncSSLSocket::enableClientHelloParsing()  {
1629     parseClientHello_ = true;
1630     clientHelloInfo_.reset(new ssl::ClientHelloInfo());
1631 }
1632
1633 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl)  {
1634   SSL_set_msg_callback(ssl, nullptr);
1635   SSL_set_msg_callback_arg(ssl, nullptr);
1636   clientHelloInfo_->clientHelloBuf_.clear();
1637 }
1638
1639 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1640                                                 int /* version */,
1641                                                 int contentType,
1642                                                 const void* buf,
1643                                                 size_t len,
1644                                                 SSL* ssl,
1645                                                 void* arg) {
1646   AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1647   if (written != 0) {
1648     sock->resetClientHelloParsing(ssl);
1649     return;
1650   }
1651   if (contentType != SSL3_RT_HANDSHAKE) {
1652     return;
1653   }
1654   if (len == 0) {
1655     return;
1656   }
1657
1658   auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1659   clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1660   try {
1661     Cursor cursor(clientHelloBuf.front());
1662     if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1663       sock->resetClientHelloParsing(ssl);
1664       return;
1665     }
1666
1667     if (cursor.totalLength() < 3) {
1668       clientHelloBuf.trimEnd(len);
1669       clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1670       return;
1671     }
1672
1673     uint32_t messageLength = cursor.read<uint8_t>();
1674     messageLength <<= 8;
1675     messageLength |= cursor.read<uint8_t>();
1676     messageLength <<= 8;
1677     messageLength |= cursor.read<uint8_t>();
1678     if (cursor.totalLength() < messageLength) {
1679       clientHelloBuf.trimEnd(len);
1680       clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1681       return;
1682     }
1683
1684     sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1685     sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1686
1687     cursor.skip(4); // gmt_unix_time
1688     cursor.skip(28); // random_bytes
1689
1690     cursor.skip(cursor.read<uint8_t>()); // session_id
1691
1692     uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1693     for (int i = 0; i < cipherSuitesLength; i += 2) {
1694       sock->clientHelloInfo_->
1695         clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1696     }
1697
1698     uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1699     for (int i = 0; i < compressionMethodsLength; ++i) {
1700       sock->clientHelloInfo_->
1701         clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1702     }
1703
1704     if (cursor.totalLength() > 0) {
1705       uint16_t extensionsLength = cursor.readBE<uint16_t>();
1706       while (extensionsLength) {
1707         ssl::TLSExtension extensionType =
1708             static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>());
1709         sock->clientHelloInfo_->
1710           clientHelloExtensions_.push_back(extensionType);
1711         extensionsLength -= 2;
1712         uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1713         extensionsLength -= 2;
1714         extensionsLength -= extensionDataLength;
1715
1716         if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) {
1717           cursor.skip(2);
1718           extensionDataLength -= 2;
1719           while (extensionDataLength) {
1720             ssl::HashAlgorithm hashAlg =
1721                 static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>());
1722             ssl::SignatureAlgorithm sigAlg =
1723                 static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>());
1724             extensionDataLength -= 2;
1725             sock->clientHelloInfo_->
1726               clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1727           }
1728         } else {
1729           cursor.skip(extensionDataLength);
1730         }
1731       }
1732     }
1733   } catch (std::out_of_range& e) {
1734     // we'll use what we found and cleanup below.
1735     VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1736       << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1737   }
1738
1739   sock->resetClientHelloParsing(ssl);
1740 }
1741
1742 } // namespace