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