AsyncSSLSocket StartTLS
[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   virtual ~AsyncSSLSocketConnector() {
88   }
89
90  public:
91   AsyncSSLSocketConnector(AsyncSSLSocket *sslSocket,
92                            AsyncSocket::ConnectCallback *callback,
93                            int timeout) :
94       sslSocket_(sslSocket),
95       callback_(callback),
96       timeout_(timeout),
97       startTime_(std::chrono::duration_cast<std::chrono::milliseconds>(
98                    std::chrono::steady_clock::now().time_since_epoch()).count()) {
99   }
100
101   virtual void connectSuccess() noexcept {
102     VLOG(7) << "client socket connected";
103
104     int64_t timeoutLeft = 0;
105     if (timeout_ > 0) {
106       auto curTime = std::chrono::duration_cast<std::chrono::milliseconds>(
107         std::chrono::steady_clock::now().time_since_epoch()).count();
108
109       timeoutLeft = timeout_ - (curTime - startTime_);
110       if (timeoutLeft <= 0) {
111         AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
112                                 "SSL connect timed out");
113         fail(ex);
114         delete this;
115         return;
116       }
117     }
118     sslSocket_->sslConn(this, timeoutLeft);
119   }
120
121   virtual void connectErr(const AsyncSocketException& ex) noexcept {
122     LOG(ERROR) << "TCP connect failed: " <<  ex.what();
123     fail(ex);
124     delete this;
125   }
126
127   virtual void handshakeSuc(AsyncSSLSocket *sock) noexcept {
128     VLOG(7) << "client handshake success";
129     if (callback_) {
130       callback_->connectSuccess();
131     }
132     delete this;
133   }
134
135   virtual void handshakeErr(AsyncSSLSocket *socket,
136                               const AsyncSocketException& ex) noexcept {
137     LOG(ERROR) << "client handshakeErr: " << ex.what();
138     fail(ex);
139     delete this;
140   }
141
142   void fail(const AsyncSocketException &ex) {
143     // fail is a noop if called twice
144     if (callback_) {
145       AsyncSSLSocket::ConnectCallback *cb = callback_;
146       callback_ = nullptr;
147
148       cb->connectErr(ex);
149       sslSocket_->closeNow();
150       // closeNow can call handshakeErr if it hasn't been called already.
151       // So this may have been deleted, no member variable access beyond this
152       // point
153       // Note that closeNow may invoke writeError callbacks if the socket had
154       // write data pending connection completion.
155     }
156   }
157 };
158
159 // XXX: implement an equivalent to corking for platforms with TCP_NOPUSH?
160 #ifdef TCP_CORK // Linux-only
161 /**
162  * Utility class that corks a TCP socket upon construction or uncorks
163  * the socket upon destruction
164  */
165 class CorkGuard : private boost::noncopyable {
166  public:
167   CorkGuard(int fd, bool multipleWrites, bool haveMore, bool* corked):
168     fd_(fd), haveMore_(haveMore), corked_(corked) {
169     if (*corked_) {
170       // socket is already corked; nothing to do
171       return;
172     }
173     if (multipleWrites || haveMore) {
174       // We are performing multiple writes in this performWrite() call,
175       // and/or there are more calls to performWrite() that will be invoked
176       // later, so enable corking
177       int flag = 1;
178       setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
179       *corked_ = true;
180     }
181   }
182
183   ~CorkGuard() {
184     if (haveMore_) {
185       // more data to come; don't uncork yet
186       return;
187     }
188     if (!*corked_) {
189       // socket isn't corked; nothing to do
190       return;
191     }
192
193     int flag = 0;
194     setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
195     *corked_ = false;
196   }
197
198  private:
199   int fd_;
200   bool haveMore_;
201   bool* corked_;
202 };
203 #else
204 class CorkGuard : private boost::noncopyable {
205  public:
206   CorkGuard(int, bool, bool, bool*) {}
207 };
208 #endif
209
210 void setup_SSL_CTX(SSL_CTX *ctx) {
211 #ifdef SSL_MODE_RELEASE_BUFFERS
212   SSL_CTX_set_mode(ctx,
213                    SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
214                    SSL_MODE_ENABLE_PARTIAL_WRITE
215                    | SSL_MODE_RELEASE_BUFFERS
216                    );
217 #else
218   SSL_CTX_set_mode(ctx,
219                    SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
220                    SSL_MODE_ENABLE_PARTIAL_WRITE
221                    );
222 #endif
223 }
224
225 BIO_METHOD eorAwareBioMethod;
226
227 void* initEorBioMethod(void) {
228   memcpy(&eorAwareBioMethod, BIO_s_socket(), sizeof(eorAwareBioMethod));
229   // override the bwrite method for MSG_EOR support
230   eorAwareBioMethod.bwrite = AsyncSSLSocket::eorAwareBioWrite;
231
232   // Note that the eorAwareBioMethod.type and eorAwareBioMethod.name are not
233   // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
234   // then have specific handlings. The eorAwareBioWrite should be compatible
235   // with the one in openssl.
236
237   // Return something here to enable AsyncSSLSocket to call this method using
238   // a function-scoped static.
239   return nullptr;
240 }
241
242 } // anonymous namespace
243
244 namespace folly {
245
246 SSLException::SSLException(int sslError, int errno_copy):
247     AsyncSocketException(
248       AsyncSocketException::SSL_ERROR,
249       ERR_error_string(sslError, msg_),
250       sslError == SSL_ERROR_SYSCALL ? errno_copy : 0), error_(sslError) {}
251
252 /**
253  * Create a client AsyncSSLSocket
254  */
255 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
256                                EventBase* evb, bool deferSecurityNegotiation) :
257     AsyncSocket(evb),
258     ctx_(ctx),
259     handshakeTimeout_(this, evb) {
260   init();
261   if (deferSecurityNegotiation) {
262     sslState_ = STATE_UNENCRYPTED;
263   }
264 }
265
266 /**
267  * Create a server/client AsyncSSLSocket
268  */
269 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
270                                EventBase* evb, int fd, bool server,
271                                bool deferSecurityNegotiation) :
272     AsyncSocket(evb, fd),
273     server_(server),
274     ctx_(ctx),
275     handshakeTimeout_(this, evb) {
276   init();
277   if (server) {
278     SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
279                               AsyncSSLSocket::sslInfoCallback);
280   }
281   if (deferSecurityNegotiation) {
282     sslState_ = STATE_UNENCRYPTED;
283   }
284 }
285
286 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
287 /**
288  * Create a client AsyncSSLSocket and allow tlsext_hostname
289  * to be sent in Client Hello.
290  */
291 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
292                                  EventBase* evb,
293                                const std::string& serverName,
294                                bool deferSecurityNegotiation) :
295     AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
296   tlsextHostname_ = serverName;
297 }
298
299 /**
300  * Create a client AsyncSSLSocket from an already connected fd
301  * and allow tlsext_hostname to be sent in Client Hello.
302  */
303 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
304                                  EventBase* evb, int fd,
305                                const std::string& serverName,
306                                bool deferSecurityNegotiation) :
307     AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
308   tlsextHostname_ = serverName;
309 }
310 #endif
311
312 AsyncSSLSocket::~AsyncSSLSocket() {
313   VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
314           << ", evb=" << eventBase_ << ", fd=" << fd_
315           << ", state=" << int(state_) << ", sslState="
316           << sslState_ << ", events=" << eventFlags_ << ")";
317 }
318
319 void AsyncSSLSocket::init() {
320   // Do this here to ensure we initialize this once before any use of
321   // AsyncSSLSocket instances and not as part of library load.
322   static const auto eorAwareBioMethodInitializer = initEorBioMethod();
323   setup_SSL_CTX(ctx_->getSSLCtx());
324 }
325
326 void AsyncSSLSocket::closeNow() {
327   // Close the SSL connection.
328   if (ssl_ != nullptr && fd_ != -1) {
329     int rc = SSL_shutdown(ssl_);
330     if (rc == 0) {
331       rc = SSL_shutdown(ssl_);
332     }
333     if (rc < 0) {
334       ERR_clear_error();
335     }
336   }
337
338   if (sslSession_ != nullptr) {
339     SSL_SESSION_free(sslSession_);
340     sslSession_ = nullptr;
341   }
342
343   sslState_ = STATE_CLOSED;
344
345   if (handshakeTimeout_.isScheduled()) {
346     handshakeTimeout_.cancelTimeout();
347   }
348
349   DestructorGuard dg(this);
350
351   if (handshakeCallback_) {
352     AsyncSocketException ex(AsyncSocketException::END_OF_FILE,
353                            "SSL connection closed locally");
354     HandshakeCB* callback = handshakeCallback_;
355     handshakeCallback_ = nullptr;
356     callback->handshakeErr(this, ex);
357   }
358
359   if (ssl_ != nullptr) {
360     SSL_free(ssl_);
361     ssl_ = nullptr;
362   }
363
364   // Close the socket.
365   AsyncSocket::closeNow();
366 }
367
368 void AsyncSSLSocket::shutdownWrite() {
369   // SSL sockets do not support half-shutdown, so just perform a full shutdown.
370   //
371   // (Performing a full shutdown here is more desirable than doing nothing at
372   // all.  The purpose of shutdownWrite() is normally to notify the other end
373   // of the connection that no more data will be sent.  If we do nothing, the
374   // other end will never know that no more data is coming, and this may result
375   // in protocol deadlock.)
376   close();
377 }
378
379 void AsyncSSLSocket::shutdownWriteNow() {
380   closeNow();
381 }
382
383 bool AsyncSSLSocket::good() const {
384   return (AsyncSocket::good() &&
385           (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
386            sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
387 }
388
389 // The TAsyncTransport definition of 'good' states that the transport is
390 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
391 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
392 // is connected but we haven't initiated the call to SSL_connect.
393 bool AsyncSSLSocket::connecting() const {
394   return (!server_ &&
395           (AsyncSocket::connecting() ||
396            (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
397                                      sslState_ == STATE_CONNECTING))));
398 }
399
400 bool AsyncSSLSocket::isEorTrackingEnabled() const {
401   const BIO *wb = SSL_get_wbio(ssl_);
402   return wb && wb->method == &eorAwareBioMethod;
403 }
404
405 void AsyncSSLSocket::setEorTracking(bool track) {
406   BIO *wb = SSL_get_wbio(ssl_);
407   if (!wb) {
408     throw AsyncSocketException(AsyncSocketException::INVALID_STATE,
409                               "setting EOR tracking without an initialized "
410                               "BIO");
411   }
412
413   if (track) {
414     if (wb->method != &eorAwareBioMethod) {
415       // only do this if we didn't
416       wb->method = &eorAwareBioMethod;
417       BIO_set_app_data(wb, this);
418       appEorByteNo_ = 0;
419       minEorRawByteNo_ = 0;
420     }
421   } else if (wb->method == &eorAwareBioMethod) {
422     wb->method = BIO_s_socket();
423     BIO_set_app_data(wb, nullptr);
424     appEorByteNo_ = 0;
425     minEorRawByteNo_ = 0;
426   } else {
427     CHECK(wb->method == BIO_s_socket());
428   }
429 }
430
431 size_t AsyncSSLSocket::getRawBytesWritten() const {
432   BIO *b;
433   if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
434     return 0;
435   }
436
437   return BIO_number_written(b);
438 }
439
440 size_t AsyncSSLSocket::getRawBytesReceived() const {
441   BIO *b;
442   if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
443     return 0;
444   }
445
446   return BIO_number_read(b);
447 }
448
449
450 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
451   LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
452              << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
453              << "events=" << eventFlags_ << ", server=" << short(server_) << "): "
454              << "sslAccept/Connect() called in invalid "
455              << "state, handshake callback " << handshakeCallback_ << ", new callback "
456              << callback;
457   assert(!handshakeTimeout_.isScheduled());
458   sslState_ = STATE_ERROR;
459
460   AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
461                          "sslAccept() called with socket in invalid state");
462
463   if (callback) {
464     callback->handshakeErr(this, ex);
465   }
466
467   // Check the socket state not the ssl state here.
468   if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
469     failHandshake(__func__, ex);
470   }
471 }
472
473 void AsyncSSLSocket::sslAccept(HandshakeCB* callback, uint32_t timeout,
474       const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
475   DestructorGuard dg(this);
476   assert(eventBase_->isInEventBaseThread());
477   verifyPeer_ = verifyPeer;
478
479   // Make sure we're in the uninitialized state
480   if (!server_ || (sslState_ != STATE_UNINIT &&
481                    sslState_ != STATE_UNENCRYPTED) ||
482       handshakeCallback_ != nullptr) {
483     return invalidState(callback);
484   }
485
486   sslState_ = STATE_ACCEPTING;
487   handshakeCallback_ = callback;
488
489   if (timeout > 0) {
490     handshakeTimeout_.scheduleTimeout(timeout);
491   }
492
493   /* register for a read operation (waiting for CLIENT HELLO) */
494   updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
495 }
496
497 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
498 void AsyncSSLSocket::attachSSLContext(
499   const std::shared_ptr<SSLContext>& ctx) {
500
501   // Check to ensure we are in client mode. Changing a server's ssl
502   // context doesn't make sense since clients of that server would likely
503   // become confused when the server's context changes.
504   DCHECK(!server_);
505   DCHECK(!ctx_);
506   DCHECK(ctx);
507   DCHECK(ctx->getSSLCtx());
508   ctx_ = ctx;
509
510   // In order to call attachSSLContext, detachSSLContext must have been
511   // previously called which sets the socket's context to the dummy
512   // context. Thus we must acquire this lock.
513   SpinLockGuard guard(dummyCtxLock);
514   SSL_set_SSL_CTX(ssl_, ctx->getSSLCtx());
515 }
516
517 void AsyncSSLSocket::detachSSLContext() {
518   DCHECK(ctx_);
519   ctx_.reset();
520   // We aren't using the initial_ctx for now, and it can introduce race
521   // conditions in the destructor of the SSL object.
522 #ifndef OPENSSL_NO_TLSEXT
523   if (ssl_->initial_ctx) {
524     SSL_CTX_free(ssl_->initial_ctx);
525     ssl_->initial_ctx = nullptr;
526   }
527 #endif
528   SpinLockGuard guard(dummyCtxLock);
529   if (nullptr == dummyCtx) {
530     // We need to lazily initialize the dummy context so we don't
531     // accidentally override any programmatic settings to openssl
532     dummyCtx = new SSLContext;
533   }
534   // We must remove this socket's references to its context right now
535   // since this socket could get passed to any thread. If the context has
536   // had its locking disabled, just doing a set in attachSSLContext()
537   // would not be thread safe.
538   SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
539 }
540 #endif
541
542 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
543 void AsyncSSLSocket::switchServerSSLContext(
544   const std::shared_ptr<SSLContext>& handshakeCtx) {
545   CHECK(server_);
546   if (sslState_ != STATE_ACCEPTING) {
547     // We log it here and allow the switch.
548     // It should not affect our re-negotiation support (which
549     // is not supported now).
550     VLOG(6) << "fd=" << getFd()
551             << " renegotation detected when switching SSL_CTX";
552   }
553
554   setup_SSL_CTX(handshakeCtx->getSSLCtx());
555   SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
556                             AsyncSSLSocket::sslInfoCallback);
557   handshakeCtx_ = handshakeCtx;
558   SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
559 }
560
561 bool AsyncSSLSocket::isServerNameMatch() const {
562   CHECK(!server_);
563
564   if (!ssl_) {
565     return false;
566   }
567
568   SSL_SESSION *ss = SSL_get_session(ssl_);
569   if (!ss) {
570     return false;
571   }
572
573   if(!ss->tlsext_hostname) {
574     return false;
575   }
576   return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
577 }
578
579 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
580   tlsextHostname_ = std::move(serverName);
581 }
582
583 #endif
584
585 void AsyncSSLSocket::timeoutExpired() noexcept {
586   if (state_ == StateEnum::ESTABLISHED &&
587       (sslState_ == STATE_CACHE_LOOKUP ||
588        sslState_ == STATE_RSA_ASYNC_PENDING)) {
589     sslState_ = STATE_ERROR;
590     // We are expecting a callback in restartSSLAccept.  The cache lookup
591     // and rsa-call necessarily have pointers to this ssl socket, so delay
592     // the cleanup until he calls us back.
593   } else {
594     assert(state_ == StateEnum::ESTABLISHED &&
595            (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
596     DestructorGuard dg(this);
597     AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
598                            (sslState_ == STATE_CONNECTING) ?
599                            "SSL connect timed out" : "SSL accept timed out");
600     failHandshake(__func__, ex);
601   }
602 }
603
604 int AsyncSSLSocket::sslExDataIndex_ = -1;
605 std::mutex AsyncSSLSocket::mutex_;
606
607 int AsyncSSLSocket::getSSLExDataIndex() {
608   if (sslExDataIndex_ < 0) {
609     std::lock_guard<std::mutex> g(mutex_);
610     if (sslExDataIndex_ < 0) {
611       sslExDataIndex_ = SSL_get_ex_new_index(0,
612           (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
613     }
614   }
615   return sslExDataIndex_;
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
1068 AsyncSSLSocket::handleRead() noexcept {
1069   VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1070           << ", state=" << int(state_) << ", "
1071           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1072   if (state_ < StateEnum::ESTABLISHED) {
1073     return AsyncSocket::handleRead();
1074   }
1075
1076
1077   if (sslState_ == STATE_ACCEPTING) {
1078     assert(server_);
1079     handleAccept();
1080     return;
1081   }
1082   else if (sslState_ == STATE_CONNECTING) {
1083     assert(!server_);
1084     handleConnect();
1085     return;
1086   }
1087
1088   // Normal read
1089   AsyncSocket::handleRead();
1090 }
1091
1092 ssize_t
1093 AsyncSSLSocket::performRead(void* buf, size_t buflen) {
1094   if (sslState_ == STATE_UNENCRYPTED) {
1095     return AsyncSocket::performRead(buf, buflen);
1096   }
1097
1098   errno = 0;
1099   ssize_t bytes = SSL_read(ssl_, buf, buflen);
1100   if (server_ && renegotiateAttempted_) {
1101     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1102                << ", sslstate=" << sslState_ << ", events=" << eventFlags_ << "): "
1103                << "client intitiated SSL renegotiation not permitted";
1104     // We pack our own SSLerr here with a dummy function
1105     errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1106                      SSL_CLIENT_RENEGOTIATION_ATTEMPT);
1107     ERR_clear_error();
1108     return READ_ERROR;
1109   }
1110   if (bytes <= 0) {
1111     int error = SSL_get_error(ssl_, bytes);
1112     if (error == SSL_ERROR_WANT_READ) {
1113       // The caller will register for read event if not already.
1114       return READ_BLOCKING;
1115     } else if (error == SSL_ERROR_WANT_WRITE) {
1116       // TODO: Even though we are attempting to read data, SSL_read() may
1117       // need to write data if renegotiation is being performed.  We currently
1118       // don't support this and just fail the read.
1119       LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1120                  << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1121                  << "unsupported SSL renegotiation during read",
1122       errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1123                        SSL_INVALID_RENEGOTIATION);
1124       ERR_clear_error();
1125       return READ_ERROR;
1126     } else {
1127       // TODO: Fix this code so that it can return a proper error message
1128       // to the callback, rather than relying on AsyncSocket code which
1129       // can't handle SSL errors.
1130       long lastError = ERR_get_error();
1131
1132       VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1133               << "state=" << state_ << ", "
1134               << "sslState=" << sslState_ << ", "
1135               << "events=" << std::hex << eventFlags_ << "): "
1136               << "bytes: " << bytes << ", "
1137               << "error: " << error << ", "
1138               << "errno: " << errno << ", "
1139               << "func: " << ERR_func_error_string(lastError) << ", "
1140               << "reason: " << ERR_reason_error_string(lastError);
1141       ERR_clear_error();
1142       if (zero_return(error, bytes)) {
1143         return bytes;
1144       }
1145       if (error != SSL_ERROR_SYSCALL) {
1146         if ((unsigned long)lastError < 0x8000) {
1147           errno = ENOSYS;
1148         } else {
1149           errno = lastError;
1150         }
1151       }
1152       return READ_ERROR;
1153     }
1154   } else {
1155     appBytesReceived_ += bytes;
1156     return bytes;
1157   }
1158 }
1159
1160 void AsyncSSLSocket::handleWrite() noexcept {
1161   VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1162           << ", state=" << int(state_) << ", "
1163           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1164   if (state_ < StateEnum::ESTABLISHED) {
1165     return AsyncSocket::handleWrite();
1166   }
1167
1168   if (sslState_ == STATE_ACCEPTING) {
1169     assert(server_);
1170     handleAccept();
1171     return;
1172   }
1173
1174   if (sslState_ == STATE_CONNECTING) {
1175     assert(!server_);
1176     handleConnect();
1177     return;
1178   }
1179
1180   // Normal write
1181   AsyncSocket::handleWrite();
1182 }
1183
1184 ssize_t AsyncSSLSocket::performWrite(const iovec* vec,
1185                                       uint32_t count,
1186                                       WriteFlags flags,
1187                                       uint32_t* countWritten,
1188                                       uint32_t* partialWritten) {
1189   if (sslState_ == STATE_UNENCRYPTED) {
1190     return AsyncSocket::performWrite(
1191       vec, count, flags, countWritten, partialWritten);
1192   }
1193   if (sslState_ != STATE_ESTABLISHED) {
1194     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1195                << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1196                << "TODO: AsyncSSLSocket currently does not support calling "
1197                << "write() before the handshake has fully completed";
1198       errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1199                        SSL_EARLY_WRITE);
1200       return -1;
1201   }
1202
1203   bool cork = isSet(flags, WriteFlags::CORK);
1204   CorkGuard guard(fd_, count > 1, cork, &corked_);
1205
1206   // Declare a buffer used to hold small write requests.  It could point to a
1207   // memory block either on stack or on heap. If it is on heap, we release it
1208   // manually when scope exits
1209   char* combinedBuf{nullptr};
1210   SCOPE_EXIT {
1211     // Note, always keep this check consistent with what we do below
1212     if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1213       delete[] combinedBuf;
1214     }
1215   };
1216
1217   *countWritten = 0;
1218   *partialWritten = 0;
1219   ssize_t totalWritten = 0;
1220   size_t bytesStolenFromNextBuffer = 0;
1221   for (uint32_t i = 0; i < count; i++) {
1222     const iovec* v = vec + i;
1223     size_t offset = bytesStolenFromNextBuffer;
1224     bytesStolenFromNextBuffer = 0;
1225     size_t len = v->iov_len - offset;
1226     const void* buf;
1227     if (len == 0) {
1228       (*countWritten)++;
1229       continue;
1230     }
1231     buf = ((const char*)v->iov_base) + offset;
1232
1233     ssize_t bytes;
1234     errno = 0;
1235     uint32_t buffersStolen = 0;
1236     if ((len < minWriteSize_) && ((i + 1) < count)) {
1237       // Combine this buffer with part or all of the next buffers in
1238       // order to avoid really small-grained calls to SSL_write().
1239       // Each call to SSL_write() produces a separate record in
1240       // the egress SSL stream, and we've found that some low-end
1241       // mobile clients can't handle receiving an HTTP response
1242       // header and the first part of the response body in two
1243       // separate SSL records (even if those two records are in
1244       // the same TCP packet).
1245
1246       if (combinedBuf == nullptr) {
1247         if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1248           // Allocate the buffer on heap
1249           combinedBuf = new char[minWriteSize_];
1250         } else {
1251           // Allocate the buffer on stack
1252           combinedBuf = (char*)alloca(minWriteSize_);
1253         }
1254       }
1255       assert(combinedBuf != nullptr);
1256
1257       memcpy(combinedBuf, buf, len);
1258       do {
1259         // INVARIANT: i + buffersStolen == complete chunks serialized
1260         uint32_t nextIndex = i + buffersStolen + 1;
1261         bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1262                                              minWriteSize_ - len);
1263         memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1264                bytesStolenFromNextBuffer);
1265         len += bytesStolenFromNextBuffer;
1266         if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1267           // couldn't steal the whole buffer
1268           break;
1269         } else {
1270           bytesStolenFromNextBuffer = 0;
1271           buffersStolen++;
1272         }
1273       } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1274       bytes = eorAwareSSLWrite(
1275         ssl_, combinedBuf, len,
1276         (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1277
1278     } else {
1279       bytes = eorAwareSSLWrite(ssl_, buf, len,
1280                            (isSet(flags, WriteFlags::EOR) && i + 1 == count));
1281     }
1282
1283     if (bytes <= 0) {
1284       int error = SSL_get_error(ssl_, bytes);
1285       if (error == SSL_ERROR_WANT_WRITE) {
1286         // The caller will register for write event if not already.
1287         *partialWritten = offset;
1288         return totalWritten;
1289       } else if (error == SSL_ERROR_WANT_READ) {
1290         // TODO: Even though we are attempting to write data, SSL_write() may
1291         // need to read data if renegotiation is being performed.  We currently
1292         // don't support this and just fail the write.
1293         LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1294                    << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1295                    << "unsupported SSL renegotiation during write",
1296         errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1297                          SSL_INVALID_RENEGOTIATION);
1298         ERR_clear_error();
1299         return -1;
1300       } else {
1301         // TODO: Fix this code so that it can return a proper error message
1302         // to the callback, rather than relying on AsyncSocket code which
1303         // can't handle SSL errors.
1304         long lastError = ERR_get_error();
1305         VLOG(3) <<
1306           "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1307                 << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1308                 << "SSL error: " << error << ", errno: " << errno
1309                 << ", func: " << ERR_func_error_string(lastError)
1310                 << ", reason: " << ERR_reason_error_string(lastError);
1311         if (error != SSL_ERROR_SYSCALL) {
1312           if ((unsigned long)lastError < 0x8000) {
1313             errno = ENOSYS;
1314           } else {
1315             errno = lastError;
1316           }
1317         }
1318         ERR_clear_error();
1319         if (!zero_return(error, bytes)) {
1320           return -1;
1321         } // else fall through to below to correctly record totalWritten
1322       }
1323     }
1324
1325     totalWritten += bytes;
1326
1327     if (bytes == (ssize_t)len) {
1328       // The full iovec is written.
1329       (*countWritten) += 1 + buffersStolen;
1330       i += buffersStolen;
1331       // continue
1332     } else {
1333       bytes += offset; // adjust bytes to account for all of v
1334       while (bytes >= (ssize_t)v->iov_len) {
1335         // We combined this buf with part or all of the next one, and
1336         // we managed to write all of this buf but not all of the bytes
1337         // from the next one that we'd hoped to write.
1338         bytes -= v->iov_len;
1339         (*countWritten)++;
1340         v = &(vec[++i]);
1341       }
1342       *partialWritten = bytes;
1343       return totalWritten;
1344     }
1345   }
1346
1347   return totalWritten;
1348 }
1349
1350 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1351                                       bool eor) {
1352   if (eor && SSL_get_wbio(ssl)->method == &eorAwareBioMethod) {
1353     if (appEorByteNo_) {
1354       // cannot track for more than one app byte EOR
1355       CHECK(appEorByteNo_ == appBytesWritten_ + n);
1356     } else {
1357       appEorByteNo_ = appBytesWritten_ + n;
1358     }
1359
1360     // 1. It is fine to keep updating minEorRawByteNo_.
1361     // 2. It is _min_ in the sense that SSL record will add some overhead.
1362     minEorRawByteNo_ = getRawBytesWritten() + n;
1363   }
1364
1365   n = sslWriteImpl(ssl, buf, n);
1366   if (n > 0) {
1367     appBytesWritten_ += n;
1368     if (appEorByteNo_) {
1369       if (getRawBytesWritten() >= minEorRawByteNo_) {
1370         minEorRawByteNo_ = 0;
1371       }
1372       if(appBytesWritten_ == appEorByteNo_) {
1373         appEorByteNo_ = 0;
1374       } else {
1375         CHECK(appBytesWritten_ < appEorByteNo_);
1376       }
1377     }
1378   }
1379   return n;
1380 }
1381
1382 void
1383 AsyncSSLSocket::sslInfoCallback(const SSL *ssl, int where, int ret) {
1384   AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1385   if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1386     sslSocket->renegotiateAttempted_ = true;
1387   }
1388 }
1389
1390 int AsyncSSLSocket::eorAwareBioWrite(BIO *b, const char *in, int inl) {
1391   int ret;
1392   struct msghdr msg;
1393   struct iovec iov;
1394   int flags = 0;
1395   AsyncSSLSocket *tsslSock;
1396
1397   iov.iov_base = const_cast<char *>(in);
1398   iov.iov_len = inl;
1399   memset(&msg, 0, sizeof(msg));
1400   msg.msg_iov = &iov;
1401   msg.msg_iovlen = 1;
1402
1403   tsslSock =
1404     reinterpret_cast<AsyncSSLSocket*>(BIO_get_app_data(b));
1405   if (tsslSock &&
1406       tsslSock->minEorRawByteNo_ &&
1407       tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1408     flags = MSG_EOR;
1409   }
1410
1411   errno = 0;
1412   ret = sendmsg(b->num, &msg, flags);
1413   BIO_clear_retry_flags(b);
1414   if (ret <= 0) {
1415     if (BIO_sock_should_retry(ret))
1416       BIO_set_retry_write(b);
1417   }
1418   return(ret);
1419 }
1420
1421 int AsyncSSLSocket::sslVerifyCallback(int preverifyOk,
1422                                        X509_STORE_CTX* x509Ctx) {
1423   SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1424     x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1425   AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1426
1427   VLOG(3) <<  "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1428           << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1429   return (self->handshakeCallback_) ?
1430     self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1431     preverifyOk;
1432 }
1433
1434 void AsyncSSLSocket::enableClientHelloParsing()  {
1435     parseClientHello_ = true;
1436     clientHelloInfo_.reset(new ClientHelloInfo());
1437 }
1438
1439 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl)  {
1440   SSL_set_msg_callback(ssl, nullptr);
1441   SSL_set_msg_callback_arg(ssl, nullptr);
1442   clientHelloInfo_->clientHelloBuf_.clear();
1443 }
1444
1445 void
1446 AsyncSSLSocket::clientHelloParsingCallback(int written, int version,
1447     int contentType, const void *buf, size_t len, SSL *ssl, void *arg)
1448 {
1449   AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1450   if (written != 0) {
1451     sock->resetClientHelloParsing(ssl);
1452     return;
1453   }
1454   if (contentType != SSL3_RT_HANDSHAKE) {
1455     sock->resetClientHelloParsing(ssl);
1456     return;
1457   }
1458   if (len == 0) {
1459     return;
1460   }
1461
1462   auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1463   clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1464   try {
1465     Cursor cursor(clientHelloBuf.front());
1466     if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1467       sock->resetClientHelloParsing(ssl);
1468       return;
1469     }
1470
1471     if (cursor.totalLength() < 3) {
1472       clientHelloBuf.trimEnd(len);
1473       clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1474       return;
1475     }
1476
1477     uint32_t messageLength = cursor.read<uint8_t>();
1478     messageLength <<= 8;
1479     messageLength |= cursor.read<uint8_t>();
1480     messageLength <<= 8;
1481     messageLength |= cursor.read<uint8_t>();
1482     if (cursor.totalLength() < messageLength) {
1483       clientHelloBuf.trimEnd(len);
1484       clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1485       return;
1486     }
1487
1488     sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1489     sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1490
1491     cursor.skip(4); // gmt_unix_time
1492     cursor.skip(28); // random_bytes
1493
1494     cursor.skip(cursor.read<uint8_t>()); // session_id
1495
1496     uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1497     for (int i = 0; i < cipherSuitesLength; i += 2) {
1498       sock->clientHelloInfo_->
1499         clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1500     }
1501
1502     uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1503     for (int i = 0; i < compressionMethodsLength; ++i) {
1504       sock->clientHelloInfo_->
1505         clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1506     }
1507
1508     if (cursor.totalLength() > 0) {
1509       uint16_t extensionsLength = cursor.readBE<uint16_t>();
1510       while (extensionsLength) {
1511         sock->clientHelloInfo_->
1512           clientHelloExtensions_.push_back(cursor.readBE<uint16_t>());
1513         extensionsLength -= 2;
1514         uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1515         extensionsLength -= 2;
1516         cursor.skip(extensionDataLength);
1517         extensionsLength -= extensionDataLength;
1518       }
1519     }
1520   } catch (std::out_of_range& e) {
1521     // we'll use what we found and cleanup below.
1522     VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1523       << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1524   }
1525
1526   sock->resetClientHelloParsing(ssl);
1527 }
1528
1529 } // namespace