refactor the interpretation of SSL errors into a function
[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 int AsyncSSLSocket::interpretSSLError(int rc, int error) {
1185   if (error == SSL_ERROR_WANT_READ) {
1186     // TODO: Even though we are attempting to write data, SSL_write() may
1187     // need to read data if renegotiation is being performed.  We currently
1188     // don't support this and just fail the write.
1189     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1190                << ", sslState=" << sslState_ << ", events=" << eventFlags_
1191                << "): " << "unsupported SSL renegotiation during write",
1192       errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1193                        SSL_INVALID_RENEGOTIATION);
1194     ERR_clear_error();
1195     return -1;
1196   } else {
1197     // TODO: Fix this code so that it can return a proper error message
1198     // to the callback, rather than relying on AsyncSocket code which
1199     // can't handle SSL errors.
1200     long lastError = ERR_get_error();
1201     VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1202             << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1203             << "SSL error: " << error << ", errno: " << errno
1204             << ", func: " << ERR_func_error_string(lastError)
1205             << ", reason: " << ERR_reason_error_string(lastError);
1206     if (error != SSL_ERROR_SYSCALL) {
1207       if ((unsigned long)lastError < 0x8000) {
1208         errno = ENOSYS;
1209       } else {
1210         errno = lastError;
1211       }
1212     }
1213     ERR_clear_error();
1214     if (!zero_return(error, rc)) {
1215       return -1;
1216     } else {
1217       return 0;
1218     }
1219   }
1220 }
1221
1222 ssize_t AsyncSSLSocket::performWrite(const iovec* vec,
1223                                       uint32_t count,
1224                                       WriteFlags flags,
1225                                       uint32_t* countWritten,
1226                                       uint32_t* partialWritten) {
1227   if (sslState_ == STATE_UNENCRYPTED) {
1228     return AsyncSocket::performWrite(
1229       vec, count, flags, countWritten, partialWritten);
1230   }
1231   if (sslState_ != STATE_ESTABLISHED) {
1232     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1233                << ", sslState=" << sslState_
1234                << ", events=" << eventFlags_ << "): "
1235                << "TODO: AsyncSSLSocket currently does not support calling "
1236                << "write() before the handshake has fully completed";
1237       errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1238                        SSL_EARLY_WRITE);
1239       return -1;
1240   }
1241
1242   bool cork = isSet(flags, WriteFlags::CORK);
1243   CorkGuard guard(fd_, count > 1, cork, &corked_);
1244
1245   // Declare a buffer used to hold small write requests.  It could point to a
1246   // memory block either on stack or on heap. If it is on heap, we release it
1247   // manually when scope exits
1248   char* combinedBuf{nullptr};
1249   SCOPE_EXIT {
1250     // Note, always keep this check consistent with what we do below
1251     if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1252       delete[] combinedBuf;
1253     }
1254   };
1255
1256   *countWritten = 0;
1257   *partialWritten = 0;
1258   ssize_t totalWritten = 0;
1259   size_t bytesStolenFromNextBuffer = 0;
1260   for (uint32_t i = 0; i < count; i++) {
1261     const iovec* v = vec + i;
1262     size_t offset = bytesStolenFromNextBuffer;
1263     bytesStolenFromNextBuffer = 0;
1264     size_t len = v->iov_len - offset;
1265     const void* buf;
1266     if (len == 0) {
1267       (*countWritten)++;
1268       continue;
1269     }
1270     buf = ((const char*)v->iov_base) + offset;
1271
1272     ssize_t bytes;
1273     errno = 0;
1274     uint32_t buffersStolen = 0;
1275     if ((len < minWriteSize_) && ((i + 1) < count)) {
1276       // Combine this buffer with part or all of the next buffers in
1277       // order to avoid really small-grained calls to SSL_write().
1278       // Each call to SSL_write() produces a separate record in
1279       // the egress SSL stream, and we've found that some low-end
1280       // mobile clients can't handle receiving an HTTP response
1281       // header and the first part of the response body in two
1282       // separate SSL records (even if those two records are in
1283       // the same TCP packet).
1284
1285       if (combinedBuf == nullptr) {
1286         if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1287           // Allocate the buffer on heap
1288           combinedBuf = new char[minWriteSize_];
1289         } else {
1290           // Allocate the buffer on stack
1291           combinedBuf = (char*)alloca(minWriteSize_);
1292         }
1293       }
1294       assert(combinedBuf != nullptr);
1295
1296       memcpy(combinedBuf, buf, len);
1297       do {
1298         // INVARIANT: i + buffersStolen == complete chunks serialized
1299         uint32_t nextIndex = i + buffersStolen + 1;
1300         bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1301                                              minWriteSize_ - len);
1302         memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1303                bytesStolenFromNextBuffer);
1304         len += bytesStolenFromNextBuffer;
1305         if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1306           // couldn't steal the whole buffer
1307           break;
1308         } else {
1309           bytesStolenFromNextBuffer = 0;
1310           buffersStolen++;
1311         }
1312       } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1313       bytes = eorAwareSSLWrite(
1314         ssl_, combinedBuf, len,
1315         (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1316
1317     } else {
1318       bytes = eorAwareSSLWrite(ssl_, buf, len,
1319                            (isSet(flags, WriteFlags::EOR) && i + 1 == count));
1320     }
1321
1322     if (bytes <= 0) {
1323       int error = SSL_get_error(ssl_, bytes);
1324       if (error == SSL_ERROR_WANT_WRITE) {
1325         // The caller will register for write event if not already.
1326         *partialWritten = offset;
1327         return totalWritten;
1328       }
1329       int rc = interpretSSLError(bytes, error);
1330       if (rc < 0) {
1331         return rc;
1332       } // else fall through to below to correctly record totalWritten
1333     }
1334
1335     totalWritten += bytes;
1336
1337     if (bytes == (ssize_t)len) {
1338       // The full iovec is written.
1339       (*countWritten) += 1 + buffersStolen;
1340       i += buffersStolen;
1341       // continue
1342     } else {
1343       bytes += offset; // adjust bytes to account for all of v
1344       while (bytes >= (ssize_t)v->iov_len) {
1345         // We combined this buf with part or all of the next one, and
1346         // we managed to write all of this buf but not all of the bytes
1347         // from the next one that we'd hoped to write.
1348         bytes -= v->iov_len;
1349         (*countWritten)++;
1350         v = &(vec[++i]);
1351       }
1352       *partialWritten = bytes;
1353       return totalWritten;
1354     }
1355   }
1356
1357   return totalWritten;
1358 }
1359
1360 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1361                                       bool eor) {
1362   if (eor && SSL_get_wbio(ssl)->method == &eorAwareBioMethod) {
1363     if (appEorByteNo_) {
1364       // cannot track for more than one app byte EOR
1365       CHECK(appEorByteNo_ == appBytesWritten_ + n);
1366     } else {
1367       appEorByteNo_ = appBytesWritten_ + n;
1368     }
1369
1370     // 1. It is fine to keep updating minEorRawByteNo_.
1371     // 2. It is _min_ in the sense that SSL record will add some overhead.
1372     minEorRawByteNo_ = getRawBytesWritten() + n;
1373   }
1374
1375   n = sslWriteImpl(ssl, buf, n);
1376   if (n > 0) {
1377     appBytesWritten_ += n;
1378     if (appEorByteNo_) {
1379       if (getRawBytesWritten() >= minEorRawByteNo_) {
1380         minEorRawByteNo_ = 0;
1381       }
1382       if(appBytesWritten_ == appEorByteNo_) {
1383         appEorByteNo_ = 0;
1384       } else {
1385         CHECK(appBytesWritten_ < appEorByteNo_);
1386       }
1387     }
1388   }
1389   return n;
1390 }
1391
1392 void
1393 AsyncSSLSocket::sslInfoCallback(const SSL *ssl, int where, int ret) {
1394   AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1395   if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1396     sslSocket->renegotiateAttempted_ = true;
1397   }
1398 }
1399
1400 int AsyncSSLSocket::eorAwareBioWrite(BIO *b, const char *in, int inl) {
1401   int ret;
1402   struct msghdr msg;
1403   struct iovec iov;
1404   int flags = 0;
1405   AsyncSSLSocket *tsslSock;
1406
1407   iov.iov_base = const_cast<char *>(in);
1408   iov.iov_len = inl;
1409   memset(&msg, 0, sizeof(msg));
1410   msg.msg_iov = &iov;
1411   msg.msg_iovlen = 1;
1412
1413   tsslSock =
1414     reinterpret_cast<AsyncSSLSocket*>(BIO_get_app_data(b));
1415   if (tsslSock &&
1416       tsslSock->minEorRawByteNo_ &&
1417       tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1418     flags = MSG_EOR;
1419   }
1420
1421   errno = 0;
1422   ret = sendmsg(b->num, &msg, flags);
1423   BIO_clear_retry_flags(b);
1424   if (ret <= 0) {
1425     if (BIO_sock_should_retry(ret))
1426       BIO_set_retry_write(b);
1427   }
1428   return(ret);
1429 }
1430
1431 int AsyncSSLSocket::sslVerifyCallback(int preverifyOk,
1432                                        X509_STORE_CTX* x509Ctx) {
1433   SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1434     x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1435   AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1436
1437   VLOG(3) <<  "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1438           << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1439   return (self->handshakeCallback_) ?
1440     self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1441     preverifyOk;
1442 }
1443
1444 void AsyncSSLSocket::enableClientHelloParsing()  {
1445     parseClientHello_ = true;
1446     clientHelloInfo_.reset(new ClientHelloInfo());
1447 }
1448
1449 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl)  {
1450   SSL_set_msg_callback(ssl, nullptr);
1451   SSL_set_msg_callback_arg(ssl, nullptr);
1452   clientHelloInfo_->clientHelloBuf_.clear();
1453 }
1454
1455 void
1456 AsyncSSLSocket::clientHelloParsingCallback(int written, int version,
1457     int contentType, const void *buf, size_t len, SSL *ssl, void *arg)
1458 {
1459   AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1460   if (written != 0) {
1461     sock->resetClientHelloParsing(ssl);
1462     return;
1463   }
1464   if (contentType != SSL3_RT_HANDSHAKE) {
1465     sock->resetClientHelloParsing(ssl);
1466     return;
1467   }
1468   if (len == 0) {
1469     return;
1470   }
1471
1472   auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1473   clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1474   try {
1475     Cursor cursor(clientHelloBuf.front());
1476     if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1477       sock->resetClientHelloParsing(ssl);
1478       return;
1479     }
1480
1481     if (cursor.totalLength() < 3) {
1482       clientHelloBuf.trimEnd(len);
1483       clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1484       return;
1485     }
1486
1487     uint32_t messageLength = cursor.read<uint8_t>();
1488     messageLength <<= 8;
1489     messageLength |= cursor.read<uint8_t>();
1490     messageLength <<= 8;
1491     messageLength |= cursor.read<uint8_t>();
1492     if (cursor.totalLength() < messageLength) {
1493       clientHelloBuf.trimEnd(len);
1494       clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1495       return;
1496     }
1497
1498     sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1499     sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1500
1501     cursor.skip(4); // gmt_unix_time
1502     cursor.skip(28); // random_bytes
1503
1504     cursor.skip(cursor.read<uint8_t>()); // session_id
1505
1506     uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1507     for (int i = 0; i < cipherSuitesLength; i += 2) {
1508       sock->clientHelloInfo_->
1509         clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1510     }
1511
1512     uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1513     for (int i = 0; i < compressionMethodsLength; ++i) {
1514       sock->clientHelloInfo_->
1515         clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1516     }
1517
1518     if (cursor.totalLength() > 0) {
1519       uint16_t extensionsLength = cursor.readBE<uint16_t>();
1520       while (extensionsLength) {
1521         sock->clientHelloInfo_->
1522           clientHelloExtensions_.push_back(cursor.readBE<uint16_t>());
1523         extensionsLength -= 2;
1524         uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1525         extensionsLength -= 2;
1526         cursor.skip(extensionDataLength);
1527         extensionsLength -= extensionDataLength;
1528       }
1529     }
1530   } catch (std::out_of_range& e) {
1531     // we'll use what we found and cleanup below.
1532     VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1533       << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1534   }
1535
1536   sock->resetClientHelloParsing(ssl);
1537 }
1538
1539 } // namespace