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