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