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