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