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