aa34b1a08764a7ee9f9e7bf7d45149c714d98fc7
[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 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
160                    );
161 #else
162   SSL_CTX_set_mode(ctx,
163                    SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
164                    SSL_MODE_ENABLE_PARTIAL_WRITE
165                    );
166 #endif
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);
172 #endif
173
174 }
175
176 BIO_METHOD sslWriteBioMethod;
177
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);
183
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.
188
189   // Return something here to enable AsyncSSLSocket to call this method using
190   // a function-scoped static.
191   return nullptr;
192 }
193
194 } // anonymous namespace
195
196 namespace folly {
197
198 /**
199  * Create a client AsyncSSLSocket
200  */
201 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
202                                EventBase* evb, bool deferSecurityNegotiation) :
203     AsyncSocket(evb),
204     ctx_(ctx),
205     handshakeTimeout_(this, evb),
206     connectionTimeout_(this, evb) {
207   init();
208   if (deferSecurityNegotiation) {
209     sslState_ = STATE_UNENCRYPTED;
210   }
211 }
212
213 /**
214  * Create a server/client AsyncSSLSocket
215  */
216 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
217                                EventBase* evb, int fd, bool server,
218                                bool deferSecurityNegotiation) :
219     AsyncSocket(evb, fd),
220     server_(server),
221     ctx_(ctx),
222     handshakeTimeout_(this, evb),
223     connectionTimeout_(this, evb) {
224   init();
225   if (server) {
226     SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
227                               AsyncSSLSocket::sslInfoCallback);
228   }
229   if (deferSecurityNegotiation) {
230     sslState_ = STATE_UNENCRYPTED;
231   }
232 }
233
234 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
235 /**
236  * Create a client AsyncSSLSocket and allow tlsext_hostname
237  * to be sent in Client Hello.
238  */
239 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
240                                  EventBase* evb,
241                                const std::string& serverName,
242                                bool deferSecurityNegotiation) :
243     AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
244   tlsextHostname_ = serverName;
245 }
246
247 /**
248  * Create a client AsyncSSLSocket from an already connected fd
249  * and allow tlsext_hostname to be sent in Client Hello.
250  */
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;
257 }
258 #endif
259
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_ << ")";
265 }
266
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;
272
273   setup_SSL_CTX(ctx_->getSSLCtx());
274 }
275
276 void AsyncSSLSocket::closeNow() {
277   // Close the SSL connection.
278   if (ssl_ != nullptr && fd_ != -1) {
279     int rc = SSL_shutdown(ssl_);
280     if (rc == 0) {
281       rc = SSL_shutdown(ssl_);
282     }
283     if (rc < 0) {
284       ERR_clear_error();
285     }
286   }
287
288   if (sslSession_ != nullptr) {
289     SSL_SESSION_free(sslSession_);
290     sslSession_ = nullptr;
291   }
292
293   sslState_ = STATE_CLOSED;
294
295   if (handshakeTimeout_.isScheduled()) {
296     handshakeTimeout_.cancelTimeout();
297   }
298
299   DestructorGuard dg(this);
300
301   invokeHandshakeErr(
302       AsyncSocketException(
303         AsyncSocketException::END_OF_FILE,
304         "SSL connection closed locally"));
305
306   if (ssl_ != nullptr) {
307     SSL_free(ssl_);
308     ssl_ = nullptr;
309   }
310
311   // Close the socket.
312   AsyncSocket::closeNow();
313 }
314
315 void AsyncSSLSocket::shutdownWrite() {
316   // SSL sockets do not support half-shutdown, so just perform a full shutdown.
317   //
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.)
323   close();
324 }
325
326 void AsyncSSLSocket::shutdownWriteNow() {
327   closeNow();
328 }
329
330 bool AsyncSSLSocket::good() const {
331   return (AsyncSocket::good() &&
332           (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
333            sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
334 }
335
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 {
341   return (!server_ &&
342           (AsyncSocket::connecting() ||
343            (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
344                                      sslState_ == STATE_CONNECTING))));
345 }
346
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);
352   }
353   return "";
354 }
355
356 bool AsyncSSLSocket::isEorTrackingEnabled() const {
357   return trackEor_;
358 }
359
360 void AsyncSSLSocket::setEorTracking(bool track) {
361   if (trackEor_ != track) {
362     trackEor_ = track;
363     appEorByteNo_ = 0;
364     minEorRawByteNo_ = 0;
365   }
366 }
367
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
373   BIO *b;
374   if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
375     return 0;
376   }
377   BIO* next = BIO_next(b);
378   while (next != NULL) {
379     b = next;
380     next = BIO_next(b);
381   }
382
383   return BIO_number_written(b);
384 }
385
386 size_t AsyncSSLSocket::getRawBytesReceived() const {
387   BIO *b;
388   if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
389     return 0;
390   }
391
392   return BIO_number_read(b);
393 }
394
395
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;
405
406   AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
407                          "sslAccept() called with socket in invalid state");
408
409   handshakeEndTime_ = std::chrono::steady_clock::now();
410   if (callback) {
411     callback->handshakeErr(this, ex);
412   }
413
414   // Check the socket state not the ssl state here.
415   if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
416     failHandshake(__func__, ex);
417   }
418 }
419
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;
425
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);
431   }
432
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();
437   }
438
439   handshakeStartTime_ = std::chrono::steady_clock::now();
440   // Make end time at least >= start time.
441   handshakeEndTime_ = handshakeStartTime_;
442
443   sslState_ = STATE_ACCEPTING;
444   handshakeCallback_ = callback;
445
446   if (timeout > 0) {
447     handshakeTimeout_.scheduleTimeout(timeout);
448   }
449
450   /* register for a read operation (waiting for CLIENT HELLO) */
451   updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
452 }
453
454 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
455 void AsyncSSLSocket::attachSSLContext(
456   const std::shared_ptr<SSLContext>& ctx) {
457
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.
461   DCHECK(!server_);
462   DCHECK(!ctx_);
463   DCHECK(ctx);
464   DCHECK(ctx->getSSLCtx());
465   ctx_ = ctx;
466
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());
472 }
473
474 void AsyncSSLSocket::detachSSLContext() {
475   DCHECK(ctx_);
476   ctx_.reset();
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;
483   }
484 #endif
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;
490   }
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());
496 }
497 #endif
498
499 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
500 void AsyncSSLSocket::switchServerSSLContext(
501   const std::shared_ptr<SSLContext>& handshakeCtx) {
502   CHECK(server_);
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";
509   }
510
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());
516 }
517
518 bool AsyncSSLSocket::isServerNameMatch() const {
519   CHECK(!server_);
520
521   if (!ssl_) {
522     return false;
523   }
524
525   SSL_SESSION *ss = SSL_get_session(ssl_);
526   if (!ss) {
527     return false;
528   }
529
530   if(!ss->tlsext_hostname) {
531     return false;
532   }
533   return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
534 }
535
536 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
537   tlsextHostname_ = std::move(serverName);
538 }
539
540 #endif
541
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);
556   } else {
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);
564   }
565 }
566
567 int AsyncSSLSocket::getSSLExDataIndex() {
568   static auto index = SSL_get_ex_new_index(
569       0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
570   return index;
571 }
572
573 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
574   return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
575       getSSLExDataIndex()));
576 }
577
578 void AsyncSSLSocket::failHandshake(const char* /* fn */,
579                                    const AsyncSocketException& ex) {
580   startFail();
581   if (handshakeTimeout_.isScheduled()) {
582     handshakeTimeout_.cancelTimeout();
583   }
584   invokeHandshakeErr(ex);
585   finishFail();
586 }
587
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);
594   }
595 }
596
597 void AsyncSSLSocket::invokeHandshakeCB() {
598   handshakeEndTime_ = std::chrono::steady_clock::now();
599   if (handshakeTimeout_.isScheduled()) {
600     handshakeTimeout_.cancelTimeout();
601   }
602   if (handshakeCallback_) {
603     HandshakeCB* callback = handshakeCallback_;
604     handshakeCallback_ = nullptr;
605     callback->handshakeSuc(this);
606   }
607 }
608
609 void AsyncSSLSocket::cacheLocalPeerAddr() {
610   SocketAddress address;
611   try {
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())) {
617       throw;
618     }
619   }
620 }
621
622 void AsyncSSLSocket::connect(ConnectCallback* callback,
623                               const folly::SocketAddress& address,
624                               int timeout,
625                               const OptionMap &options,
626                               const folly::SocketAddress& bindAddr)
627                               noexcept {
628   assert(!server_);
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);
634 }
635
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);
642     }
643   } else {
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);
648     }
649   }
650 }
651
652 bool AsyncSSLSocket::setupSSLBio() {
653   auto wb = BIO_new(&sslWriteBioMethod);
654
655   if (!wb) {
656     return false;
657   }
658
659   OpenSSLUtils::setBioAppData(wb, this);
660   OpenSSLUtils::setBioFd(wb, fd_, BIO_NOCLOSE);
661   SSL_set_bio(ssl_, wb, wb);
662   return true;
663 }
664
665 void AsyncSSLSocket::sslConn(HandshakeCB* callback, uint64_t timeout,
666         const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
667   DestructorGuard dg(this);
668   assert(eventBase_->isInEventBaseThread());
669
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();
674   }
675
676   verifyPeer_ = verifyPeer;
677
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);
683   }
684
685   sslState_ = STATE_CONNECTING;
686   handshakeCallback_ = callback;
687
688   try {
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);
697   }
698
699   if (!setupSSLBio()) {
700     sslState_ = STATE_ERROR;
701     AsyncSocketException ex(
702         AsyncSocketException::INTERNAL_ERROR, "error creating SSL bio");
703     return failHandshake(__func__, ex);
704   }
705
706   applyVerificationOptions(ssl_);
707
708   if (sslSession_ != nullptr) {
709     sessionResumptionAttempted_ = true;
710     SSL_set_session(ssl_, sslSession_);
711     SSL_SESSION_free(sslSession_);
712     sslSession_ = nullptr;
713   }
714 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
715   if (tlsextHostname_.size()) {
716     SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
717   }
718 #endif
719
720   SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
721
722   handshakeConnectTimeout_ = timeout;
723   startSSLConnect();
724 }
725
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(
734         std::chrono::milliseconds(handshakeConnectTimeout_));
735   }
736   handleConnect();
737 }
738
739 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
740   if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
741     return SSL_get1_session(ssl_);
742   }
743
744   return sslSession_;
745 }
746
747 const SSL* AsyncSSLSocket::getSSL() const {
748   return ssl_;
749 }
750
751 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
752   sslSession_ = session;
753   if (!takeOwnership && session != nullptr) {
754     // Increment the reference count
755     CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
756   }
757 }
758
759 void AsyncSSLSocket::getSelectedNextProtocol(
760     const unsigned char** protoName,
761     unsigned* protoLen,
762     SSLContext::NextProtocolType* protoType) const {
763   if (!getSelectedNextProtocolNoThrow(protoName, protoLen, protoType)) {
764     throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
765                               "NPN not supported");
766   }
767 }
768
769 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
770     const unsigned char** protoName,
771     unsigned* protoLen,
772     SSLContext::NextProtocolType* protoType) const {
773   *protoName = nullptr;
774   *protoLen = 0;
775 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
776   SSL_get0_alpn_selected(ssl_, protoName, protoLen);
777   if (*protoLen > 0) {
778     if (protoType) {
779       *protoType = SSLContext::NextProtocolType::ALPN;
780     }
781     return true;
782   }
783 #endif
784 #ifdef OPENSSL_NPN_NEGOTIATED
785   SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
786   if (protoType) {
787     *protoType = SSLContext::NextProtocolType::NPN;
788   }
789   return true;
790 #else
791   (void)protoType;
792   return false;
793 #endif
794 }
795
796 bool AsyncSSLSocket::getSSLSessionReused() const {
797   if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
798     return SSL_session_reused(ssl_);
799   }
800   return false;
801 }
802
803 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
804   return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
805 }
806
807 /* static */
808 const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) {
809   if (ssl == nullptr) {
810     return nullptr;
811   }
812 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
813   return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
814 #else
815   return nullptr;
816 #endif
817 }
818
819 const char *AsyncSSLSocket::getSSLServerName() const {
820 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
821   return getSSLServerNameFromSSL(ssl_);
822 #else
823   throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
824                              "SNI not supported");
825 #endif
826 }
827
828 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
829   return getSSLServerNameFromSSL(ssl_);
830 }
831
832 int AsyncSSLSocket::getSSLVersion() const {
833   return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
834 }
835
836 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
837   X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
838   if (cert) {
839     int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
840     return OBJ_nid2ln(nid);
841   }
842   return nullptr;
843 }
844
845 int AsyncSSLSocket::getSSLCertSize() const {
846   int certSize = 0;
847   X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
848   if (cert) {
849     EVP_PKEY *key = X509_get_pubkey(cert);
850     certSize = EVP_PKEY_bits(key);
851     EVP_PKEY_free(key);
852   }
853   return certSize;
854 }
855
856 const X509* AsyncSSLSocket::getSelfCert() const {
857   return (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
858 }
859
860 bool AsyncSSLSocket::willBlock(int ret,
861                                int* sslErrorOut,
862                                unsigned long* errErrorOut) noexcept {
863   *errErrorOut = 0;
864   int error = *sslErrorOut = SSL_get_error(ssl_, ret);
865   if (error == SSL_ERROR_WANT_READ) {
866     // Register for read event if not already.
867     updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
868     return true;
869   } else if (error == SSL_ERROR_WANT_WRITE) {
870     VLOG(3) << "AsyncSSLSocket(fd=" << fd_
871             << ", state=" << int(state_) << ", sslState="
872             << sslState_ << ", events=" << eventFlags_ << "): "
873             << "SSL_ERROR_WANT_WRITE";
874     // Register for write event if not already.
875     updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
876     return true;
877 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
878   } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
879     // We will block but we can't register our own socket.  The callback that
880     // triggered this code will re-call handleAccept at the appropriate time.
881
882     // We can only get here if the linked libssl.so has support for this feature
883     // as well, otherwise SSL_get_error cannot return our error code.
884     sslState_ = STATE_CACHE_LOOKUP;
885
886     // Unregister for all events while blocked here
887     updateEventRegistration(EventHandler::NONE,
888                             EventHandler::READ | EventHandler::WRITE);
889
890     // The timeout (if set) keeps running here
891     return true;
892 #endif
893   } else if (0
894 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
895       || error == SSL_ERROR_WANT_RSA_ASYNC_PENDING
896 #endif
897 #ifdef SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
898       || error == SSL_ERROR_WANT_ECDSA_ASYNC_PENDING
899 #endif
900       ) {
901     // Our custom openssl function has kicked off an async request to do
902     // rsa/ecdsa private key operation.  When that call returns, a callback will
903     // be invoked that will re-call handleAccept.
904     sslState_ = STATE_ASYNC_PENDING;
905
906     // Unregister for all events while blocked here
907     updateEventRegistration(
908       EventHandler::NONE,
909       EventHandler::READ | EventHandler::WRITE
910     );
911
912     // The timeout (if set) keeps running here
913     return true;
914   } else {
915     unsigned long lastError = *errErrorOut = ERR_get_error();
916     VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
917             << "state=" << state_ << ", "
918             << "sslState=" << sslState_ << ", "
919             << "events=" << std::hex << eventFlags_ << "): "
920             << "SSL error: " << error << ", "
921             << "errno: " << errno << ", "
922             << "ret: " << ret << ", "
923             << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
924             << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
925             << "func: " << ERR_func_error_string(lastError) << ", "
926             << "reason: " << ERR_reason_error_string(lastError);
927     return false;
928   }
929 }
930
931 void AsyncSSLSocket::checkForImmediateRead() noexcept {
932   // openssl may have buffered data that it read from the socket already.
933   // In this case we have to process it immediately, rather than waiting for
934   // the socket to become readable again.
935   if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
936     AsyncSocket::handleRead();
937   }
938 }
939
940 void
941 AsyncSSLSocket::restartSSLAccept()
942 {
943   VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this
944           << ", fd=" << fd_ << ", state=" << int(state_) << ", "
945           << "sslState=" << sslState_ << ", events=" << eventFlags_;
946   DestructorGuard dg(this);
947   assert(
948     sslState_ == STATE_CACHE_LOOKUP ||
949     sslState_ == STATE_ASYNC_PENDING ||
950     sslState_ == STATE_ERROR ||
951     sslState_ == STATE_CLOSED);
952   if (sslState_ == STATE_CLOSED) {
953     // I sure hope whoever closed this socket didn't delete it already,
954     // but this is not strictly speaking an error
955     return;
956   }
957   if (sslState_ == STATE_ERROR) {
958     // go straight to fail if timeout expired during lookup
959     AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
960                            "SSL accept timed out");
961     failHandshake(__func__, ex);
962     return;
963   }
964   sslState_ = STATE_ACCEPTING;
965   this->handleAccept();
966 }
967
968 void
969 AsyncSSLSocket::handleAccept() noexcept {
970   VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
971           << ", fd=" << fd_ << ", state=" << int(state_) << ", "
972           << "sslState=" << sslState_ << ", events=" << eventFlags_;
973   assert(server_);
974   assert(state_ == StateEnum::ESTABLISHED &&
975          sslState_ == STATE_ACCEPTING);
976   if (!ssl_) {
977     /* lazily create the SSL structure */
978     try {
979       ssl_ = ctx_->createSSL();
980     } catch (std::exception &e) {
981       sslState_ = STATE_ERROR;
982       AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
983                              "error calling SSLContext::createSSL()");
984       LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
985                  << ", fd=" << fd_ << "): " << e.what();
986       return failHandshake(__func__, ex);
987     }
988
989     if (!setupSSLBio()) {
990       sslState_ = STATE_ERROR;
991       AsyncSocketException ex(
992           AsyncSocketException::INTERNAL_ERROR, "error creating write bio");
993       return failHandshake(__func__, ex);
994     }
995
996     SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
997
998     applyVerificationOptions(ssl_);
999   }
1000
1001   if (server_ && parseClientHello_) {
1002     SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
1003     SSL_set_msg_callback_arg(ssl_, this);
1004   }
1005
1006   int ret = SSL_accept(ssl_);
1007   if (ret <= 0) {
1008     int sslError;
1009     unsigned long errError;
1010     int errnoCopy = errno;
1011     if (willBlock(ret, &sslError, &errError)) {
1012       return;
1013     } else {
1014       sslState_ = STATE_ERROR;
1015       SSLException ex(sslError, errError, ret, errnoCopy);
1016       return failHandshake(__func__, ex);
1017     }
1018   }
1019
1020   handshakeComplete_ = true;
1021   updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1022
1023   // Move into STATE_ESTABLISHED in the normal case that we are in
1024   // STATE_ACCEPTING.
1025   sslState_ = STATE_ESTABLISHED;
1026
1027   VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
1028           << " successfully accepted; state=" << int(state_)
1029           << ", sslState=" << sslState_ << ", events=" << eventFlags_;
1030
1031   // Remember the EventBase we are attached to, before we start invoking any
1032   // callbacks (since the callbacks may call detachEventBase()).
1033   EventBase* originalEventBase = eventBase_;
1034
1035   // Call the accept callback.
1036   invokeHandshakeCB();
1037
1038   // Note that the accept callback may have changed our state.
1039   // (set or unset the read callback, called write(), closed the socket, etc.)
1040   // The following code needs to handle these situations correctly.
1041   //
1042   // If the socket has been closed, readCallback_ and writeReqHead_ will
1043   // always be nullptr, so that will prevent us from trying to read or write.
1044   //
1045   // The main thing to check for is if eventBase_ is still originalEventBase.
1046   // If not, we have been detached from this event base, so we shouldn't
1047   // perform any more operations.
1048   if (eventBase_ != originalEventBase) {
1049     return;
1050   }
1051
1052   AsyncSocket::handleInitialReadWrite();
1053 }
1054
1055 void
1056 AsyncSSLSocket::handleConnect() noexcept {
1057   VLOG(3) <<  "AsyncSSLSocket::handleConnect() this=" << this
1058           << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1059           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1060   assert(!server_);
1061   if (state_ < StateEnum::ESTABLISHED) {
1062     return AsyncSocket::handleConnect();
1063   }
1064
1065   assert(
1066       (state_ == StateEnum::FAST_OPEN || state_ == StateEnum::ESTABLISHED) &&
1067       sslState_ == STATE_CONNECTING);
1068   assert(ssl_);
1069
1070   auto originalState = state_;
1071   int ret = SSL_connect(ssl_);
1072   if (ret <= 0) {
1073     int sslError;
1074     unsigned long errError;
1075     int errnoCopy = errno;
1076     if (willBlock(ret, &sslError, &errError)) {
1077       // We fell back to connecting state due to TFO
1078       if (state_ == StateEnum::CONNECTING) {
1079         DCHECK_EQ(StateEnum::FAST_OPEN, originalState);
1080         if (handshakeTimeout_.isScheduled()) {
1081           handshakeTimeout_.cancelTimeout();
1082         }
1083       }
1084       return;
1085     } else {
1086       sslState_ = STATE_ERROR;
1087       SSLException ex(sslError, errError, ret, errnoCopy);
1088       return failHandshake(__func__, ex);
1089     }
1090   }
1091
1092   handshakeComplete_ = true;
1093   updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1094
1095   // Move into STATE_ESTABLISHED in the normal case that we are in
1096   // STATE_CONNECTING.
1097   sslState_ = STATE_ESTABLISHED;
1098
1099   VLOG(3) << "AsyncSSLSocket " << this << ": "
1100           << "fd " << fd_ << " successfully connected; "
1101           << "state=" << int(state_) << ", sslState=" << sslState_
1102           << ", events=" << eventFlags_;
1103
1104   // Remember the EventBase we are attached to, before we start invoking any
1105   // callbacks (since the callbacks may call detachEventBase()).
1106   EventBase* originalEventBase = eventBase_;
1107
1108   // Call the handshake callback.
1109   invokeHandshakeCB();
1110
1111   // Note that the connect callback may have changed our state.
1112   // (set or unset the read callback, called write(), closed the socket, etc.)
1113   // The following code needs to handle these situations correctly.
1114   //
1115   // If the socket has been closed, readCallback_ and writeReqHead_ will
1116   // always be nullptr, so that will prevent us from trying to read or write.
1117   //
1118   // The main thing to check for is if eventBase_ is still originalEventBase.
1119   // If not, we have been detached from this event base, so we shouldn't
1120   // perform any more operations.
1121   if (eventBase_ != originalEventBase) {
1122     return;
1123   }
1124
1125   AsyncSocket::handleInitialReadWrite();
1126 }
1127
1128 void AsyncSSLSocket::invokeConnectErr(const AsyncSocketException& ex) {
1129   connectionTimeout_.cancelTimeout();
1130   AsyncSocket::invokeConnectErr(ex);
1131   if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1132     if (handshakeTimeout_.isScheduled()) {
1133       handshakeTimeout_.cancelTimeout();
1134     }
1135     // If we fell back to connecting state during TFO and the connection
1136     // failed, it would be an SSL failure as well.
1137     invokeHandshakeErr(ex);
1138   }
1139 }
1140
1141 void AsyncSSLSocket::invokeConnectSuccess() {
1142   connectionTimeout_.cancelTimeout();
1143   if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1144     assert(tfoAttempted_);
1145     // If we failed TFO, we'd fall back to trying to connect the socket,
1146     // to setup things like timeouts.
1147     startSSLConnect();
1148   }
1149   // still invoke the base class since it re-sets the connect time.
1150   AsyncSocket::invokeConnectSuccess();
1151 }
1152
1153 void AsyncSSLSocket::scheduleConnectTimeout() {
1154   if (sslState_ == SSLStateEnum::STATE_CONNECTING) {
1155     // We fell back from TFO, and need to set the timeouts.
1156     // We will not have a connect callback in this case, thus if the timer
1157     // expires we would have no-one to notify.
1158     // Thus we should reset even the connect timers to point to the handshake
1159     // timeouts.
1160     assert(connectCallback_ == nullptr);
1161     // We use a different connect timeout here than the handshake timeout, so
1162     // that we can disambiguate the 2 timers.
1163     if (connectTimeout_.count() > 0) {
1164       if (!connectionTimeout_.scheduleTimeout(connectTimeout_)) {
1165         throw AsyncSocketException(
1166             AsyncSocketException::INTERNAL_ERROR,
1167             withAddr("failed to schedule AsyncSSLSocket connect timeout"));
1168       }
1169     }
1170     return;
1171   }
1172   AsyncSocket::scheduleConnectTimeout();
1173 }
1174
1175 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1176 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1177   // turn on the buffer movable in openssl
1178   if (bufferMovableEnabled_ && ssl_ != nullptr && !isBufferMovable_ &&
1179       callback != nullptr && callback->isBufferMovable()) {
1180     SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1181     isBufferMovable_ = true;
1182   }
1183 #endif
1184
1185   AsyncSocket::setReadCB(callback);
1186 }
1187
1188 void AsyncSSLSocket::setBufferMovableEnabled(bool enabled) {
1189   bufferMovableEnabled_ = enabled;
1190 }
1191
1192 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1193   CHECK(readCallback_);
1194   if (isBufferMovable_) {
1195     *buf = nullptr;
1196     *buflen = 0;
1197   } else {
1198     // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1199     readCallback_->getReadBuffer(buf, buflen);
1200   }
1201 }
1202
1203 void
1204 AsyncSSLSocket::handleRead() noexcept {
1205   VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1206           << ", state=" << int(state_) << ", "
1207           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1208   if (state_ < StateEnum::ESTABLISHED) {
1209     return AsyncSocket::handleRead();
1210   }
1211
1212
1213   if (sslState_ == STATE_ACCEPTING) {
1214     assert(server_);
1215     handleAccept();
1216     return;
1217   }
1218   else if (sslState_ == STATE_CONNECTING) {
1219     assert(!server_);
1220     handleConnect();
1221     return;
1222   }
1223
1224   // Normal read
1225   AsyncSocket::handleRead();
1226 }
1227
1228 AsyncSocket::ReadResult
1229 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1230   VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf
1231           << ", buflen=" << *buflen;
1232
1233   if (sslState_ == STATE_UNENCRYPTED) {
1234     return AsyncSocket::performRead(buf, buflen, offset);
1235   }
1236
1237   int bytes = 0;
1238   if (!isBufferMovable_) {
1239     bytes = SSL_read(ssl_, *buf, int(*buflen));
1240   }
1241 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1242   else {
1243     bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1244   }
1245 #endif
1246
1247   if (server_ && renegotiateAttempted_) {
1248     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1249                << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1250                << "): client intitiated SSL renegotiation not permitted";
1251     return ReadResult(
1252         READ_ERROR,
1253         folly::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION));
1254   }
1255   if (bytes <= 0) {
1256     int error = SSL_get_error(ssl_, bytes);
1257     if (error == SSL_ERROR_WANT_READ) {
1258       // The caller will register for read event if not already.
1259       if (errno == EWOULDBLOCK || errno == EAGAIN) {
1260         return ReadResult(READ_BLOCKING);
1261       } else {
1262         return ReadResult(READ_ERROR);
1263       }
1264     } else if (error == SSL_ERROR_WANT_WRITE) {
1265       // TODO: Even though we are attempting to read data, SSL_read() may
1266       // need to write data if renegotiation is being performed.  We currently
1267       // don't support this and just fail the read.
1268       LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1269                  << ", sslState=" << sslState_ << ", events=" << eventFlags_
1270                  << "): unsupported SSL renegotiation during read";
1271       return ReadResult(
1272           READ_ERROR,
1273           folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1274     } else {
1275       if (zero_return(error, bytes)) {
1276         return ReadResult(bytes);
1277       }
1278       long errError = ERR_get_error();
1279       VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1280               << "state=" << state_ << ", "
1281               << "sslState=" << sslState_ << ", "
1282               << "events=" << std::hex << eventFlags_ << "): "
1283               << "bytes: " << bytes << ", "
1284               << "error: " << error << ", "
1285               << "errno: " << errno << ", "
1286               << "func: " << ERR_func_error_string(errError) << ", "
1287               << "reason: " << ERR_reason_error_string(errError);
1288       return ReadResult(
1289           READ_ERROR,
1290           folly::make_unique<SSLException>(error, errError, bytes, errno));
1291     }
1292   } else {
1293     appBytesReceived_ += bytes;
1294     return ReadResult(bytes);
1295   }
1296 }
1297
1298 void AsyncSSLSocket::handleWrite() noexcept {
1299   VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1300           << ", state=" << int(state_) << ", "
1301           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1302   if (state_ < StateEnum::ESTABLISHED) {
1303     return AsyncSocket::handleWrite();
1304   }
1305
1306   if (sslState_ == STATE_ACCEPTING) {
1307     assert(server_);
1308     handleAccept();
1309     return;
1310   }
1311
1312   if (sslState_ == STATE_CONNECTING) {
1313     assert(!server_);
1314     handleConnect();
1315     return;
1316   }
1317
1318   // Normal write
1319   AsyncSocket::handleWrite();
1320 }
1321
1322 AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {
1323   if (error == SSL_ERROR_WANT_READ) {
1324     // Even though we are attempting to write data, SSL_write() may
1325     // need to read data if renegotiation is being performed.  We currently
1326     // don't support this and just fail the write.
1327     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1328                << ", sslState=" << sslState_ << ", events=" << eventFlags_
1329                << "): "
1330                << "unsupported SSL renegotiation during write";
1331     return WriteResult(
1332         WRITE_ERROR,
1333         folly::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION));
1334   } else {
1335     if (zero_return(error, rc)) {
1336       return WriteResult(0);
1337     }
1338     auto errError = ERR_get_error();
1339     VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1340             << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1341             << "SSL error: " << error << ", errno: " << errno
1342             << ", func: " << ERR_func_error_string(errError)
1343             << ", reason: " << ERR_reason_error_string(errError);
1344     return WriteResult(
1345         WRITE_ERROR,
1346         folly::make_unique<SSLException>(error, errError, rc, errno));
1347   }
1348 }
1349
1350 AsyncSocket::WriteResult AsyncSSLSocket::performWrite(
1351     const iovec* vec,
1352     uint32_t count,
1353     WriteFlags flags,
1354     uint32_t* countWritten,
1355     uint32_t* partialWritten) {
1356   if (sslState_ == STATE_UNENCRYPTED) {
1357     return AsyncSocket::performWrite(
1358       vec, count, flags, countWritten, partialWritten);
1359   }
1360   if (sslState_ != STATE_ESTABLISHED) {
1361     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1362                << ", sslState=" << sslState_
1363                << ", events=" << eventFlags_ << "): "
1364                << "TODO: AsyncSSLSocket currently does not support calling "
1365                << "write() before the handshake has fully completed";
1366     return WriteResult(
1367         WRITE_ERROR, folly::make_unique<SSLException>(SSLError::EARLY_WRITE));
1368   }
1369
1370   // Declare a buffer used to hold small write requests.  It could point to a
1371   // memory block either on stack or on heap. If it is on heap, we release it
1372   // manually when scope exits
1373   char* combinedBuf{nullptr};
1374   SCOPE_EXIT {
1375     // Note, always keep this check consistent with what we do below
1376     if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1377       delete[] combinedBuf;
1378     }
1379   };
1380
1381   *countWritten = 0;
1382   *partialWritten = 0;
1383   ssize_t totalWritten = 0;
1384   size_t bytesStolenFromNextBuffer = 0;
1385   for (uint32_t i = 0; i < count; i++) {
1386     const iovec* v = vec + i;
1387     size_t offset = bytesStolenFromNextBuffer;
1388     bytesStolenFromNextBuffer = 0;
1389     size_t len = v->iov_len - offset;
1390     const void* buf;
1391     if (len == 0) {
1392       (*countWritten)++;
1393       continue;
1394     }
1395     buf = ((const char*)v->iov_base) + offset;
1396
1397     ssize_t bytes;
1398     uint32_t buffersStolen = 0;
1399     auto sslWriteBuf = buf;
1400     if ((len < minWriteSize_) && ((i + 1) < count)) {
1401       // Combine this buffer with part or all of the next buffers in
1402       // order to avoid really small-grained calls to SSL_write().
1403       // Each call to SSL_write() produces a separate record in
1404       // the egress SSL stream, and we've found that some low-end
1405       // mobile clients can't handle receiving an HTTP response
1406       // header and the first part of the response body in two
1407       // separate SSL records (even if those two records are in
1408       // the same TCP packet).
1409
1410       if (combinedBuf == nullptr) {
1411         if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1412           // Allocate the buffer on heap
1413           combinedBuf = new char[minWriteSize_];
1414         } else {
1415           // Allocate the buffer on stack
1416           combinedBuf = (char*)alloca(minWriteSize_);
1417         }
1418       }
1419       assert(combinedBuf != nullptr);
1420       sslWriteBuf = combinedBuf;
1421
1422       memcpy(combinedBuf, buf, len);
1423       do {
1424         // INVARIANT: i + buffersStolen == complete chunks serialized
1425         uint32_t nextIndex = i + buffersStolen + 1;
1426         bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1427                                              minWriteSize_ - len);
1428         memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1429                bytesStolenFromNextBuffer);
1430         len += bytesStolenFromNextBuffer;
1431         if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1432           // couldn't steal the whole buffer
1433           break;
1434         } else {
1435           bytesStolenFromNextBuffer = 0;
1436           buffersStolen++;
1437         }
1438       } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1439     }
1440
1441     // Advance any empty buffers immediately after.
1442     if (bytesStolenFromNextBuffer == 0) {
1443       while ((i + buffersStolen + 1) < count &&
1444              vec[i + buffersStolen + 1].iov_len == 0) {
1445         buffersStolen++;
1446       }
1447     }
1448
1449     corkCurrentWrite_ =
1450         isSet(flags, WriteFlags::CORK) || (i + buffersStolen + 1 < count);
1451     bytes = eorAwareSSLWrite(
1452         ssl_,
1453         sslWriteBuf,
1454         int(len),
1455         (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1456
1457     if (bytes <= 0) {
1458       int error = SSL_get_error(ssl_, int(bytes));
1459       if (error == SSL_ERROR_WANT_WRITE) {
1460         // The caller will register for write event if not already.
1461         *partialWritten = uint32_t(offset);
1462         return WriteResult(totalWritten);
1463       }
1464       auto writeResult = interpretSSLError(int(bytes), error);
1465       if (writeResult.writeReturn < 0) {
1466         return writeResult;
1467       } // else fall through to below to correctly record totalWritten
1468     }
1469
1470     totalWritten += bytes;
1471
1472     if (bytes == (ssize_t)len) {
1473       // The full iovec is written.
1474       (*countWritten) += 1 + buffersStolen;
1475       i += buffersStolen;
1476       // continue
1477     } else {
1478       bytes += offset; // adjust bytes to account for all of v
1479       while (bytes >= (ssize_t)v->iov_len) {
1480         // We combined this buf with part or all of the next one, and
1481         // we managed to write all of this buf but not all of the bytes
1482         // from the next one that we'd hoped to write.
1483         bytes -= v->iov_len;
1484         (*countWritten)++;
1485         v = &(vec[++i]);
1486       }
1487       *partialWritten = uint32_t(bytes);
1488       return WriteResult(totalWritten);
1489     }
1490   }
1491
1492   return WriteResult(totalWritten);
1493 }
1494
1495 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1496                                       bool eor) {
1497   if (eor && trackEor_) {
1498     if (appEorByteNo_) {
1499       // cannot track for more than one app byte EOR
1500       CHECK(appEorByteNo_ == appBytesWritten_ + n);
1501     } else {
1502       appEorByteNo_ = appBytesWritten_ + n;
1503     }
1504
1505     // 1. It is fine to keep updating minEorRawByteNo_.
1506     // 2. It is _min_ in the sense that SSL record will add some overhead.
1507     minEorRawByteNo_ = getRawBytesWritten() + n;
1508   }
1509
1510   n = sslWriteImpl(ssl, buf, n);
1511   if (n > 0) {
1512     appBytesWritten_ += n;
1513     if (appEorByteNo_) {
1514       if (getRawBytesWritten() >= minEorRawByteNo_) {
1515         minEorRawByteNo_ = 0;
1516       }
1517       if(appBytesWritten_ == appEorByteNo_) {
1518         appEorByteNo_ = 0;
1519       } else {
1520         CHECK(appBytesWritten_ < appEorByteNo_);
1521       }
1522     }
1523   }
1524   return n;
1525 }
1526
1527 void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) {
1528   AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1529   if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1530     sslSocket->renegotiateAttempted_ = true;
1531   }
1532   if (where & SSL_CB_READ_ALERT) {
1533     const char* type = SSL_alert_type_string(ret);
1534     if (type) {
1535       const char* desc = SSL_alert_desc_string(ret);
1536       sslSocket->alertsReceived_.emplace_back(
1537           *type, StringPiece(desc, std::strlen(desc)));
1538     }
1539   }
1540 }
1541
1542 int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) {
1543   struct msghdr msg;
1544   struct iovec iov;
1545   int flags = 0;
1546   AsyncSSLSocket* tsslSock;
1547
1548   iov.iov_base = const_cast<char*>(in);
1549   iov.iov_len = inl;
1550   memset(&msg, 0, sizeof(msg));
1551   msg.msg_iov = &iov;
1552   msg.msg_iovlen = 1;
1553
1554   auto appData = OpenSSLUtils::getBioAppData(b);
1555   CHECK(appData);
1556
1557   tsslSock = reinterpret_cast<AsyncSSLSocket*>(appData);
1558   CHECK(tsslSock);
1559
1560   if (tsslSock->trackEor_ && tsslSock->minEorRawByteNo_ &&
1561       tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1562     flags = MSG_EOR;
1563   }
1564
1565 #ifdef MSG_NOSIGNAL
1566   flags |= MSG_NOSIGNAL;
1567 #endif
1568
1569 #ifdef MSG_MORE
1570   if (tsslSock->corkCurrentWrite_) {
1571     flags |= MSG_MORE;
1572   }
1573 #endif
1574
1575   auto result = tsslSock->sendSocketMessage(
1576       OpenSSLUtils::getBioFd(b, nullptr), &msg, flags);
1577   BIO_clear_retry_flags(b);
1578   if (!result.exception && result.writeReturn <= 0) {
1579     if (OpenSSLUtils::getBioShouldRetryWrite(int(result.writeReturn))) {
1580       BIO_set_retry_write(b);
1581     }
1582   }
1583   return int(result.writeReturn);
1584 }
1585
1586 int AsyncSSLSocket::sslVerifyCallback(
1587     int preverifyOk,
1588     X509_STORE_CTX* x509Ctx) {
1589   SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1590     x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1591   AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1592
1593   VLOG(3) <<  "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1594           << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1595   return (self->handshakeCallback_) ?
1596     self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1597     preverifyOk;
1598 }
1599
1600 void AsyncSSLSocket::enableClientHelloParsing()  {
1601     parseClientHello_ = true;
1602     clientHelloInfo_.reset(new ssl::ClientHelloInfo());
1603 }
1604
1605 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl)  {
1606   SSL_set_msg_callback(ssl, nullptr);
1607   SSL_set_msg_callback_arg(ssl, nullptr);
1608   clientHelloInfo_->clientHelloBuf_.clear();
1609 }
1610
1611 void AsyncSSLSocket::clientHelloParsingCallback(int written,
1612                                                 int /* version */,
1613                                                 int contentType,
1614                                                 const void* buf,
1615                                                 size_t len,
1616                                                 SSL* ssl,
1617                                                 void* arg) {
1618   AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1619   if (written != 0) {
1620     sock->resetClientHelloParsing(ssl);
1621     return;
1622   }
1623   if (contentType != SSL3_RT_HANDSHAKE) {
1624     return;
1625   }
1626   if (len == 0) {
1627     return;
1628   }
1629
1630   auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1631   clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1632   try {
1633     Cursor cursor(clientHelloBuf.front());
1634     if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1635       sock->resetClientHelloParsing(ssl);
1636       return;
1637     }
1638
1639     if (cursor.totalLength() < 3) {
1640       clientHelloBuf.trimEnd(len);
1641       clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1642       return;
1643     }
1644
1645     uint32_t messageLength = cursor.read<uint8_t>();
1646     messageLength <<= 8;
1647     messageLength |= cursor.read<uint8_t>();
1648     messageLength <<= 8;
1649     messageLength |= cursor.read<uint8_t>();
1650     if (cursor.totalLength() < messageLength) {
1651       clientHelloBuf.trimEnd(len);
1652       clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1653       return;
1654     }
1655
1656     sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1657     sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1658
1659     cursor.skip(4); // gmt_unix_time
1660     cursor.skip(28); // random_bytes
1661
1662     cursor.skip(cursor.read<uint8_t>()); // session_id
1663
1664     uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1665     for (int i = 0; i < cipherSuitesLength; i += 2) {
1666       sock->clientHelloInfo_->
1667         clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1668     }
1669
1670     uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1671     for (int i = 0; i < compressionMethodsLength; ++i) {
1672       sock->clientHelloInfo_->
1673         clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1674     }
1675
1676     if (cursor.totalLength() > 0) {
1677       uint16_t extensionsLength = cursor.readBE<uint16_t>();
1678       while (extensionsLength) {
1679         ssl::TLSExtension extensionType =
1680             static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>());
1681         sock->clientHelloInfo_->
1682           clientHelloExtensions_.push_back(extensionType);
1683         extensionsLength -= 2;
1684         uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1685         extensionsLength -= 2;
1686         extensionsLength -= extensionDataLength;
1687
1688         if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) {
1689           cursor.skip(2);
1690           extensionDataLength -= 2;
1691           while (extensionDataLength) {
1692             ssl::HashAlgorithm hashAlg =
1693                 static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>());
1694             ssl::SignatureAlgorithm sigAlg =
1695                 static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>());
1696             extensionDataLength -= 2;
1697             sock->clientHelloInfo_->
1698               clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1699           }
1700         } else if (extensionType == ssl::TLSExtension::SUPPORTED_VERSIONS) {
1701           cursor.skip(1);
1702           extensionDataLength -= 1;
1703           while (extensionDataLength) {
1704             sock->clientHelloInfo_->clientHelloSupportedVersions_.push_back(
1705                 cursor.readBE<uint16_t>());
1706             extensionDataLength -= 2;
1707           }
1708         } else {
1709           cursor.skip(extensionDataLength);
1710         }
1711       }
1712     }
1713   } catch (std::out_of_range&) {
1714     // we'll use what we found and cleanup below.
1715     VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1716       << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1717   }
1718
1719   sock->resetClientHelloParsing(ssl);
1720 }
1721
1722 void AsyncSSLSocket::getSSLClientCiphers(
1723     std::string& clientCiphers,
1724     bool convertToString) const {
1725   std::string ciphers;
1726
1727   if (parseClientHello_ == false
1728       || clientHelloInfo_->clientHelloCipherSuites_.empty()) {
1729     clientCiphers = "";
1730     return;
1731   }
1732
1733   bool first = true;
1734   for (auto originalCipherCode : clientHelloInfo_->clientHelloCipherSuites_)
1735   {
1736     if (first) {
1737       first = false;
1738     } else {
1739       ciphers +=  ":";
1740     }
1741
1742     bool nameFound = convertToString;
1743
1744     if (convertToString) {
1745       const auto& name = OpenSSLUtils::getCipherName(originalCipherCode);
1746       if (name.empty()) {
1747         nameFound = false;
1748       } else {
1749         ciphers += name;
1750       }
1751     }
1752
1753     if (!nameFound) {
1754       folly::hexlify(
1755           std::array<uint8_t, 2>{{
1756               static_cast<uint8_t>((originalCipherCode >> 8) & 0xffL),
1757               static_cast<uint8_t>(originalCipherCode & 0x00ffL) }},
1758           ciphers,
1759           /* append to ciphers = */ true);
1760     }
1761   }
1762
1763   clientCiphers = std::move(ciphers);
1764 }
1765
1766 std::string AsyncSSLSocket::getSSLClientComprMethods() const {
1767   if (!parseClientHello_) {
1768     return "";
1769   }
1770   return folly::join(":", clientHelloInfo_->clientHelloCompressionMethods_);
1771 }
1772
1773 std::string AsyncSSLSocket::getSSLClientExts() const {
1774   if (!parseClientHello_) {
1775     return "";
1776   }
1777   return folly::join(":", clientHelloInfo_->clientHelloExtensions_);
1778 }
1779
1780 std::string AsyncSSLSocket::getSSLClientSigAlgs() const {
1781   if (!parseClientHello_) {
1782     return "";
1783   }
1784
1785   std::string sigAlgs;
1786   sigAlgs.reserve(clientHelloInfo_->clientHelloSigAlgs_.size() * 4);
1787   for (size_t i = 0; i < clientHelloInfo_->clientHelloSigAlgs_.size(); i++) {
1788     if (i) {
1789       sigAlgs.push_back(':');
1790     }
1791     sigAlgs.append(folly::to<std::string>(
1792         clientHelloInfo_->clientHelloSigAlgs_[i].first));
1793     sigAlgs.push_back(',');
1794     sigAlgs.append(folly::to<std::string>(
1795         clientHelloInfo_->clientHelloSigAlgs_[i].second));
1796   }
1797
1798   return sigAlgs;
1799 }
1800
1801 std::string AsyncSSLSocket::getSSLClientSupportedVersions() const {
1802   if (!parseClientHello_) {
1803     return "";
1804   }
1805   return folly::join(":", clientHelloInfo_->clientHelloSupportedVersions_);
1806 }
1807
1808 std::string AsyncSSLSocket::getSSLAlertsReceived() const {
1809   std::string ret;
1810
1811   for (const auto& alert : alertsReceived_) {
1812     if (!ret.empty()) {
1813       ret.append(",");
1814     }
1815     ret.append(folly::to<std::string>(alert.first, ": ", alert.second));
1816   }
1817
1818   return ret;
1819 }
1820
1821 void AsyncSSLSocket::getSSLSharedCiphers(std::string& sharedCiphers) const {
1822   char ciphersBuffer[1024];
1823   ciphersBuffer[0] = '\0';
1824   SSL_get_shared_ciphers(ssl_, ciphersBuffer, sizeof(ciphersBuffer) - 1);
1825   sharedCiphers = ciphersBuffer;
1826 }
1827
1828 void AsyncSSLSocket::getSSLServerCiphers(std::string& serverCiphers) const {
1829   serverCiphers = SSL_get_cipher_list(ssl_, 0);
1830   int i = 1;
1831   const char *cipher;
1832   while ((cipher = SSL_get_cipher_list(ssl_, i)) != nullptr) {
1833     serverCiphers.append(":");
1834     serverCiphers.append(cipher);
1835     i++;
1836   }
1837 }
1838
1839 } // namespace