Add framework for switching certs based on signature_algorithms TLS extension.
[folly.git] / folly / io / async / AsyncSSLSocket.cpp
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/io/async/AsyncSSLSocket.h>
18
19 #include <folly/io/async/EventBase.h>
20
21 #include <boost/noncopyable.hpp>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <netinet/in.h>
25 #include <netinet/tcp.h>
26 #include <openssl/err.h>
27 #include <openssl/asn1.h>
28 #include <openssl/ssl.h>
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <unistd.h>
32 #include <chrono>
33
34 #include <folly/Bits.h>
35 #include <folly/SocketAddress.h>
36 #include <folly/SpinLock.h>
37 #include <folly/io/IOBuf.h>
38 #include <folly/io/Cursor.h>
39
40 using folly::SocketAddress;
41 using folly::SSLContext;
42 using std::string;
43 using std::shared_ptr;
44
45 using folly::Endian;
46 using folly::IOBuf;
47 using folly::SpinLock;
48 using folly::SpinLockGuard;
49 using folly::io::Cursor;
50 using std::unique_ptr;
51 using std::bind;
52
53 namespace {
54 using folly::AsyncSocket;
55 using folly::AsyncSocketException;
56 using folly::AsyncSSLSocket;
57 using folly::Optional;
58
59 // We have one single dummy SSL context so that we can implement attach
60 // and detach methods in a thread safe fashion without modifying opnessl.
61 static SSLContext *dummyCtx = nullptr;
62 static SpinLock dummyCtxLock;
63
64 // Numbers chosen as to not collide with functions in ssl.h
65 const uint8_t TASYNCSSLSOCKET_F_PERFORM_READ = 90;
66 const uint8_t TASYNCSSLSOCKET_F_PERFORM_WRITE = 91;
67
68 // If given min write size is less than this, buffer will be allocated on
69 // stack, otherwise it is allocated on heap
70 const size_t MAX_STACK_BUF_SIZE = 2048;
71
72 // This converts "illegal" shutdowns into ZERO_RETURN
73 inline bool zero_return(int error, int rc) {
74   return (error == SSL_ERROR_ZERO_RETURN || (rc == 0 && errno == 0));
75 }
76
77 class AsyncSSLSocketConnector: public AsyncSocket::ConnectCallback,
78                                 public AsyncSSLSocket::HandshakeCB {
79
80  private:
81   AsyncSSLSocket *sslSocket_;
82   AsyncSSLSocket::ConnectCallback *callback_;
83   int timeout_;
84   int64_t startTime_;
85
86  protected:
87   ~AsyncSSLSocketConnector() override {}
88
89  public:
90   AsyncSSLSocketConnector(AsyncSSLSocket *sslSocket,
91                            AsyncSocket::ConnectCallback *callback,
92                            int timeout) :
93       sslSocket_(sslSocket),
94       callback_(callback),
95       timeout_(timeout),
96       startTime_(std::chrono::duration_cast<std::chrono::milliseconds>(
97                    std::chrono::steady_clock::now().time_since_epoch()).count()) {
98   }
99
100   void connectSuccess() noexcept override {
101     VLOG(7) << "client socket connected";
102
103     int64_t timeoutLeft = 0;
104     if (timeout_ > 0) {
105       auto curTime = std::chrono::duration_cast<std::chrono::milliseconds>(
106         std::chrono::steady_clock::now().time_since_epoch()).count();
107
108       timeoutLeft = timeout_ - (curTime - startTime_);
109       if (timeoutLeft <= 0) {
110         AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
111                                 "SSL connect timed out");
112         fail(ex);
113         delete this;
114         return;
115       }
116     }
117     sslSocket_->sslConn(this, timeoutLeft);
118   }
119
120   void connectErr(const AsyncSocketException& ex) noexcept override {
121     LOG(ERROR) << "TCP connect failed: " <<  ex.what();
122     fail(ex);
123     delete this;
124   }
125
126   void handshakeSuc(AsyncSSLSocket* sock) noexcept override {
127     VLOG(7) << "client handshake success";
128     if (callback_) {
129       callback_->connectSuccess();
130     }
131     delete this;
132   }
133
134   void handshakeErr(AsyncSSLSocket* socket,
135                     const AsyncSocketException& ex) noexcept override {
136     LOG(ERROR) << "client handshakeErr: " << ex.what();
137     fail(ex);
138     delete this;
139   }
140
141   void fail(const AsyncSocketException &ex) {
142     // fail is a noop if called twice
143     if (callback_) {
144       AsyncSSLSocket::ConnectCallback *cb = callback_;
145       callback_ = nullptr;
146
147       cb->connectErr(ex);
148       sslSocket_->closeNow();
149       // closeNow can call handshakeErr if it hasn't been called already.
150       // So this may have been deleted, no member variable access beyond this
151       // point
152       // Note that closeNow may invoke writeError callbacks if the socket had
153       // write data pending connection completion.
154     }
155   }
156 };
157
158 // XXX: implement an equivalent to corking for platforms with TCP_NOPUSH?
159 #ifdef TCP_CORK // Linux-only
160 /**
161  * Utility class that corks a TCP socket upon construction or uncorks
162  * the socket upon destruction
163  */
164 class CorkGuard : private boost::noncopyable {
165  public:
166   CorkGuard(int fd, bool multipleWrites, bool haveMore, bool* corked):
167     fd_(fd), haveMore_(haveMore), corked_(corked) {
168     if (*corked_) {
169       // socket is already corked; nothing to do
170       return;
171     }
172     if (multipleWrites || haveMore) {
173       // We are performing multiple writes in this performWrite() call,
174       // and/or there are more calls to performWrite() that will be invoked
175       // later, so enable corking
176       int flag = 1;
177       setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
178       *corked_ = true;
179     }
180   }
181
182   ~CorkGuard() {
183     if (haveMore_) {
184       // more data to come; don't uncork yet
185       return;
186     }
187     if (!*corked_) {
188       // socket isn't corked; nothing to do
189       return;
190     }
191
192     int flag = 0;
193     setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag));
194     *corked_ = false;
195   }
196
197  private:
198   int fd_;
199   bool haveMore_;
200   bool* corked_;
201 };
202 #else
203 class CorkGuard : private boost::noncopyable {
204  public:
205   CorkGuard(int, bool, bool, bool*) {}
206 };
207 #endif
208
209 void setup_SSL_CTX(SSL_CTX *ctx) {
210 #ifdef SSL_MODE_RELEASE_BUFFERS
211   SSL_CTX_set_mode(ctx,
212                    SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
213                    SSL_MODE_ENABLE_PARTIAL_WRITE
214                    | SSL_MODE_RELEASE_BUFFERS
215                    );
216 #else
217   SSL_CTX_set_mode(ctx,
218                    SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
219                    SSL_MODE_ENABLE_PARTIAL_WRITE
220                    );
221 #endif
222 // SSL_CTX_set_mode is a Macro
223 #ifdef SSL_MODE_WRITE_IOVEC
224   SSL_CTX_set_mode(ctx,
225                    SSL_CTX_get_mode(ctx)
226                    | SSL_MODE_WRITE_IOVEC);
227 #endif
228
229 }
230
231 BIO_METHOD eorAwareBioMethod;
232
233 void* initEorBioMethod(void) {
234   memcpy(&eorAwareBioMethod, BIO_s_socket(), sizeof(eorAwareBioMethod));
235   // override the bwrite method for MSG_EOR support
236   eorAwareBioMethod.bwrite = AsyncSSLSocket::eorAwareBioWrite;
237
238   // Note that the eorAwareBioMethod.type and eorAwareBioMethod.name are not
239   // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and
240   // then have specific handlings. The eorAwareBioWrite should be compatible
241   // with the one in openssl.
242
243   // Return something here to enable AsyncSSLSocket to call this method using
244   // a function-scoped static.
245   return nullptr;
246 }
247
248 } // anonymous namespace
249
250 namespace folly {
251
252 SSLException::SSLException(int sslError, int errno_copy):
253     AsyncSocketException(
254       AsyncSocketException::SSL_ERROR,
255       ERR_error_string(sslError, msg_),
256       sslError == SSL_ERROR_SYSCALL ? errno_copy : 0), error_(sslError) {}
257
258 /**
259  * Create a client AsyncSSLSocket
260  */
261 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
262                                EventBase* evb, bool deferSecurityNegotiation) :
263     AsyncSocket(evb),
264     ctx_(ctx),
265     handshakeTimeout_(this, evb) {
266   init();
267   if (deferSecurityNegotiation) {
268     sslState_ = STATE_UNENCRYPTED;
269   }
270 }
271
272 /**
273  * Create a server/client AsyncSSLSocket
274  */
275 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
276                                EventBase* evb, int fd, bool server,
277                                bool deferSecurityNegotiation) :
278     AsyncSocket(evb, fd),
279     server_(server),
280     ctx_(ctx),
281     handshakeTimeout_(this, evb) {
282   init();
283   if (server) {
284     SSL_CTX_set_info_callback(ctx_->getSSLCtx(),
285                               AsyncSSLSocket::sslInfoCallback);
286   }
287   if (deferSecurityNegotiation) {
288     sslState_ = STATE_UNENCRYPTED;
289   }
290 }
291
292 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
293 /**
294  * Create a client AsyncSSLSocket and allow tlsext_hostname
295  * to be sent in Client Hello.
296  */
297 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext> &ctx,
298                                  EventBase* evb,
299                                const std::string& serverName,
300                                bool deferSecurityNegotiation) :
301     AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) {
302   tlsextHostname_ = serverName;
303 }
304
305 /**
306  * Create a client AsyncSSLSocket from an already connected fd
307  * and allow tlsext_hostname to be sent in Client Hello.
308  */
309 AsyncSSLSocket::AsyncSSLSocket(const shared_ptr<SSLContext>& ctx,
310                                  EventBase* evb, int fd,
311                                const std::string& serverName,
312                                bool deferSecurityNegotiation) :
313     AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) {
314   tlsextHostname_ = serverName;
315 }
316 #endif
317
318 AsyncSSLSocket::~AsyncSSLSocket() {
319   VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this
320           << ", evb=" << eventBase_ << ", fd=" << fd_
321           << ", state=" << int(state_) << ", sslState="
322           << sslState_ << ", events=" << eventFlags_ << ")";
323 }
324
325 void AsyncSSLSocket::init() {
326   // Do this here to ensure we initialize this once before any use of
327   // AsyncSSLSocket instances and not as part of library load.
328   static const auto eorAwareBioMethodInitializer = initEorBioMethod();
329   (void)eorAwareBioMethodInitializer;
330
331   setup_SSL_CTX(ctx_->getSSLCtx());
332 }
333
334 void AsyncSSLSocket::closeNow() {
335   // Close the SSL connection.
336   if (ssl_ != nullptr && fd_ != -1) {
337     int rc = SSL_shutdown(ssl_);
338     if (rc == 0) {
339       rc = SSL_shutdown(ssl_);
340     }
341     if (rc < 0) {
342       ERR_clear_error();
343     }
344   }
345
346   if (sslSession_ != nullptr) {
347     SSL_SESSION_free(sslSession_);
348     sslSession_ = nullptr;
349   }
350
351   sslState_ = STATE_CLOSED;
352
353   if (handshakeTimeout_.isScheduled()) {
354     handshakeTimeout_.cancelTimeout();
355   }
356
357   DestructorGuard dg(this);
358
359   invokeHandshakeErr(
360       AsyncSocketException(
361         AsyncSocketException::END_OF_FILE,
362         "SSL connection closed locally"));
363
364   if (ssl_ != nullptr) {
365     SSL_free(ssl_);
366     ssl_ = nullptr;
367   }
368
369   // Close the socket.
370   AsyncSocket::closeNow();
371 }
372
373 void AsyncSSLSocket::shutdownWrite() {
374   // SSL sockets do not support half-shutdown, so just perform a full shutdown.
375   //
376   // (Performing a full shutdown here is more desirable than doing nothing at
377   // all.  The purpose of shutdownWrite() is normally to notify the other end
378   // of the connection that no more data will be sent.  If we do nothing, the
379   // other end will never know that no more data is coming, and this may result
380   // in protocol deadlock.)
381   close();
382 }
383
384 void AsyncSSLSocket::shutdownWriteNow() {
385   closeNow();
386 }
387
388 bool AsyncSSLSocket::good() const {
389   return (AsyncSocket::good() &&
390           (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING ||
391            sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED));
392 }
393
394 // The TAsyncTransport definition of 'good' states that the transport is
395 // ready to perform reads and writes, so sslState_ == UNINIT must report !good.
396 // connecting can be true when the sslState_ == UNINIT because the AsyncSocket
397 // is connected but we haven't initiated the call to SSL_connect.
398 bool AsyncSSLSocket::connecting() const {
399   return (!server_ &&
400           (AsyncSocket::connecting() ||
401            (AsyncSocket::good() && (sslState_ == STATE_UNINIT ||
402                                      sslState_ == STATE_CONNECTING))));
403 }
404
405 bool AsyncSSLSocket::isEorTrackingEnabled() const {
406   const BIO *wb = SSL_get_wbio(ssl_);
407   return wb && wb->method == &eorAwareBioMethod;
408 }
409
410 void AsyncSSLSocket::setEorTracking(bool track) {
411   BIO *wb = SSL_get_wbio(ssl_);
412   if (!wb) {
413     throw AsyncSocketException(AsyncSocketException::INVALID_STATE,
414                               "setting EOR tracking without an initialized "
415                               "BIO");
416   }
417
418   if (track) {
419     if (wb->method != &eorAwareBioMethod) {
420       // only do this if we didn't
421       wb->method = &eorAwareBioMethod;
422       BIO_set_app_data(wb, this);
423       appEorByteNo_ = 0;
424       minEorRawByteNo_ = 0;
425     }
426   } else if (wb->method == &eorAwareBioMethod) {
427     wb->method = BIO_s_socket();
428     BIO_set_app_data(wb, nullptr);
429     appEorByteNo_ = 0;
430     minEorRawByteNo_ = 0;
431   } else {
432     CHECK(wb->method == BIO_s_socket());
433   }
434 }
435
436 size_t AsyncSSLSocket::getRawBytesWritten() const {
437   BIO *b;
438   if (!ssl_ || !(b = SSL_get_wbio(ssl_))) {
439     return 0;
440   }
441
442   return BIO_number_written(b);
443 }
444
445 size_t AsyncSSLSocket::getRawBytesReceived() const {
446   BIO *b;
447   if (!ssl_ || !(b = SSL_get_rbio(ssl_))) {
448     return 0;
449   }
450
451   return BIO_number_read(b);
452 }
453
454
455 void AsyncSSLSocket::invalidState(HandshakeCB* callback) {
456   LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_
457              << ", state=" << int(state_) << ", sslState=" << sslState_ << ", "
458              << "events=" << eventFlags_ << ", server=" << short(server_) << "): "
459              << "sslAccept/Connect() called in invalid "
460              << "state, handshake callback " << handshakeCallback_ << ", new callback "
461              << callback;
462   assert(!handshakeTimeout_.isScheduled());
463   sslState_ = STATE_ERROR;
464
465   AsyncSocketException ex(AsyncSocketException::INVALID_STATE,
466                          "sslAccept() called with socket in invalid state");
467
468   handshakeEndTime_ = std::chrono::steady_clock::now();
469   if (callback) {
470     callback->handshakeErr(this, ex);
471   }
472
473   // Check the socket state not the ssl state here.
474   if (state_ != StateEnum::CLOSED || state_ != StateEnum::ERROR) {
475     failHandshake(__func__, ex);
476   }
477 }
478
479 void AsyncSSLSocket::sslAccept(HandshakeCB* callback, uint32_t timeout,
480       const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
481   DestructorGuard dg(this);
482   assert(eventBase_->isInEventBaseThread());
483   verifyPeer_ = verifyPeer;
484
485   // Make sure we're in the uninitialized state
486   if (!server_ || (sslState_ != STATE_UNINIT &&
487                    sslState_ != STATE_UNENCRYPTED) ||
488       handshakeCallback_ != nullptr) {
489     return invalidState(callback);
490   }
491   handshakeStartTime_ = std::chrono::steady_clock::now();
492   // Make end time at least >= start time.
493   handshakeEndTime_ = handshakeStartTime_;
494
495   sslState_ = STATE_ACCEPTING;
496   handshakeCallback_ = callback;
497
498   if (timeout > 0) {
499     handshakeTimeout_.scheduleTimeout(timeout);
500   }
501
502   /* register for a read operation (waiting for CLIENT HELLO) */
503   updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
504 }
505
506 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
507 void AsyncSSLSocket::attachSSLContext(
508   const std::shared_ptr<SSLContext>& ctx) {
509
510   // Check to ensure we are in client mode. Changing a server's ssl
511   // context doesn't make sense since clients of that server would likely
512   // become confused when the server's context changes.
513   DCHECK(!server_);
514   DCHECK(!ctx_);
515   DCHECK(ctx);
516   DCHECK(ctx->getSSLCtx());
517   ctx_ = ctx;
518
519   // In order to call attachSSLContext, detachSSLContext must have been
520   // previously called which sets the socket's context to the dummy
521   // context. Thus we must acquire this lock.
522   SpinLockGuard guard(dummyCtxLock);
523   SSL_set_SSL_CTX(ssl_, ctx->getSSLCtx());
524 }
525
526 void AsyncSSLSocket::detachSSLContext() {
527   DCHECK(ctx_);
528   ctx_.reset();
529   // We aren't using the initial_ctx for now, and it can introduce race
530   // conditions in the destructor of the SSL object.
531 #ifndef OPENSSL_NO_TLSEXT
532   if (ssl_->initial_ctx) {
533     SSL_CTX_free(ssl_->initial_ctx);
534     ssl_->initial_ctx = nullptr;
535   }
536 #endif
537   SpinLockGuard guard(dummyCtxLock);
538   if (nullptr == dummyCtx) {
539     // We need to lazily initialize the dummy context so we don't
540     // accidentally override any programmatic settings to openssl
541     dummyCtx = new SSLContext;
542   }
543   // We must remove this socket's references to its context right now
544   // since this socket could get passed to any thread. If the context has
545   // had its locking disabled, just doing a set in attachSSLContext()
546   // would not be thread safe.
547   SSL_set_SSL_CTX(ssl_, dummyCtx->getSSLCtx());
548 }
549 #endif
550
551 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
552 void AsyncSSLSocket::switchServerSSLContext(
553   const std::shared_ptr<SSLContext>& handshakeCtx) {
554   CHECK(server_);
555   if (sslState_ != STATE_ACCEPTING) {
556     // We log it here and allow the switch.
557     // It should not affect our re-negotiation support (which
558     // is not supported now).
559     VLOG(6) << "fd=" << getFd()
560             << " renegotation detected when switching SSL_CTX";
561   }
562
563   setup_SSL_CTX(handshakeCtx->getSSLCtx());
564   SSL_CTX_set_info_callback(handshakeCtx->getSSLCtx(),
565                             AsyncSSLSocket::sslInfoCallback);
566   handshakeCtx_ = handshakeCtx;
567   SSL_set_SSL_CTX(ssl_, handshakeCtx->getSSLCtx());
568 }
569
570 bool AsyncSSLSocket::isServerNameMatch() const {
571   CHECK(!server_);
572
573   if (!ssl_) {
574     return false;
575   }
576
577   SSL_SESSION *ss = SSL_get_session(ssl_);
578   if (!ss) {
579     return false;
580   }
581
582   if(!ss->tlsext_hostname) {
583     return false;
584   }
585   return (tlsextHostname_.compare(ss->tlsext_hostname) ? false : true);
586 }
587
588 void AsyncSSLSocket::setServerName(std::string serverName) noexcept {
589   tlsextHostname_ = std::move(serverName);
590 }
591
592 #endif
593
594 void AsyncSSLSocket::timeoutExpired() noexcept {
595   if (state_ == StateEnum::ESTABLISHED &&
596       (sslState_ == STATE_CACHE_LOOKUP ||
597        sslState_ == STATE_RSA_ASYNC_PENDING)) {
598     sslState_ = STATE_ERROR;
599     // We are expecting a callback in restartSSLAccept.  The cache lookup
600     // and rsa-call necessarily have pointers to this ssl socket, so delay
601     // the cleanup until he calls us back.
602   } else {
603     assert(state_ == StateEnum::ESTABLISHED &&
604            (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING));
605     DestructorGuard dg(this);
606     AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
607                            (sslState_ == STATE_CONNECTING) ?
608                            "SSL connect timed out" : "SSL accept timed out");
609     failHandshake(__func__, ex);
610   }
611 }
612
613 int AsyncSSLSocket::getSSLExDataIndex() {
614   static auto index = SSL_get_ex_new_index(
615       0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr);
616   return index;
617 }
618
619 AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL *ssl) {
620   return static_cast<AsyncSSLSocket *>(SSL_get_ex_data(ssl,
621       getSSLExDataIndex()));
622 }
623
624 void AsyncSSLSocket::failHandshake(const char* fn,
625                                     const AsyncSocketException& ex) {
626   startFail();
627   if (handshakeTimeout_.isScheduled()) {
628     handshakeTimeout_.cancelTimeout();
629   }
630   invokeHandshakeErr(ex);
631   finishFail();
632 }
633
634 void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) {
635   handshakeEndTime_ = std::chrono::steady_clock::now();
636   if (handshakeCallback_ != nullptr) {
637     HandshakeCB* callback = handshakeCallback_;
638     handshakeCallback_ = nullptr;
639     callback->handshakeErr(this, ex);
640   }
641 }
642
643 void AsyncSSLSocket::invokeHandshakeCB() {
644   handshakeEndTime_ = std::chrono::steady_clock::now();
645   if (handshakeTimeout_.isScheduled()) {
646     handshakeTimeout_.cancelTimeout();
647   }
648   if (handshakeCallback_) {
649     HandshakeCB* callback = handshakeCallback_;
650     handshakeCallback_ = nullptr;
651     callback->handshakeSuc(this);
652   }
653 }
654
655 void AsyncSSLSocket::connect(ConnectCallback* callback,
656                               const folly::SocketAddress& address,
657                               int timeout,
658                               const OptionMap &options,
659                               const folly::SocketAddress& bindAddr)
660                               noexcept {
661   assert(!server_);
662   assert(state_ == StateEnum::UNINIT);
663   assert(sslState_ == STATE_UNINIT);
664   AsyncSSLSocketConnector *connector =
665     new AsyncSSLSocketConnector(this, callback, timeout);
666   AsyncSocket::connect(connector, address, timeout, options, bindAddr);
667 }
668
669 void AsyncSSLSocket::applyVerificationOptions(SSL * ssl) {
670   // apply the settings specified in verifyPeer_
671   if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) {
672     if(ctx_->needsPeerVerification()) {
673       SSL_set_verify(ssl, ctx_->getVerificationMode(),
674         AsyncSSLSocket::sslVerifyCallback);
675     }
676   } else {
677     if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY ||
678         verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) {
679       SSL_set_verify(ssl, SSLContext::getVerificationMode(verifyPeer_),
680         AsyncSSLSocket::sslVerifyCallback);
681     }
682   }
683 }
684
685 void AsyncSSLSocket::sslConn(HandshakeCB* callback, uint64_t timeout,
686         const SSLContext::SSLVerifyPeerEnum& verifyPeer) {
687   DestructorGuard dg(this);
688   assert(eventBase_->isInEventBaseThread());
689
690   verifyPeer_ = verifyPeer;
691
692   // Make sure we're in the uninitialized state
693   if (server_ || (sslState_ != STATE_UNINIT && sslState_ !=
694                   STATE_UNENCRYPTED) ||
695       handshakeCallback_ != nullptr) {
696     return invalidState(callback);
697   }
698
699   handshakeStartTime_ = std::chrono::steady_clock::now();
700   // Make end time at least >= start time.
701   handshakeEndTime_ = handshakeStartTime_;
702
703   sslState_ = STATE_CONNECTING;
704   handshakeCallback_ = callback;
705
706   try {
707     ssl_ = ctx_->createSSL();
708   } catch (std::exception &e) {
709     sslState_ = STATE_ERROR;
710     AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
711                            "error calling SSLContext::createSSL()");
712     LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd="
713             << fd_ << "): " << e.what();
714     return failHandshake(__func__, ex);
715   }
716
717   applyVerificationOptions(ssl_);
718
719   SSL_set_fd(ssl_, fd_);
720   if (sslSession_ != nullptr) {
721     SSL_set_session(ssl_, sslSession_);
722     SSL_SESSION_free(sslSession_);
723     sslSession_ = nullptr;
724   }
725 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
726   if (tlsextHostname_.size()) {
727     SSL_set_tlsext_host_name(ssl_, tlsextHostname_.c_str());
728   }
729 #endif
730
731   SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
732
733   if (timeout > 0) {
734     handshakeTimeout_.scheduleTimeout(timeout);
735   }
736
737   handleConnect();
738 }
739
740 SSL_SESSION *AsyncSSLSocket::getSSLSession() {
741   if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
742     return SSL_get1_session(ssl_);
743   }
744
745   return sslSession_;
746 }
747
748 void AsyncSSLSocket::setSSLSession(SSL_SESSION *session, bool takeOwnership) {
749   sslSession_ = session;
750   if (!takeOwnership && session != nullptr) {
751     // Increment the reference count
752     CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
753   }
754 }
755
756 void AsyncSSLSocket::getSelectedNextProtocol(const unsigned char** protoName,
757     unsigned* protoLen) const {
758   if (!getSelectedNextProtocolNoThrow(protoName, protoLen)) {
759     throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
760                               "NPN not supported");
761   }
762 }
763
764 bool AsyncSSLSocket::getSelectedNextProtocolNoThrow(
765   const unsigned char** protoName,
766   unsigned* protoLen) const {
767   *protoName = nullptr;
768   *protoLen = 0;
769 #ifdef OPENSSL_NPN_NEGOTIATED
770   SSL_get0_next_proto_negotiated(ssl_, protoName, protoLen);
771   return true;
772 #else
773   return false;
774 #endif
775 }
776
777 bool AsyncSSLSocket::getSSLSessionReused() const {
778   if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) {
779     return SSL_session_reused(ssl_);
780   }
781   return false;
782 }
783
784 const char *AsyncSSLSocket::getNegotiatedCipherName() const {
785   return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_) : nullptr;
786 }
787
788 const char *AsyncSSLSocket::getSSLServerName() const {
789 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
790   return (ssl_ != nullptr) ? SSL_get_servername(ssl_, TLSEXT_NAMETYPE_host_name)
791         : nullptr;
792 #else
793   throw AsyncSocketException(AsyncSocketException::NOT_SUPPORTED,
794                             "SNI not supported");
795 #endif
796 }
797
798 const char *AsyncSSLSocket::getSSLServerNameNoThrow() const {
799   try {
800     return getSSLServerName();
801   } catch (AsyncSocketException& ex) {
802     return nullptr;
803   }
804 }
805
806 int AsyncSSLSocket::getSSLVersion() const {
807   return (ssl_ != nullptr) ? SSL_version(ssl_) : 0;
808 }
809
810 const char *AsyncSSLSocket::getSSLCertSigAlgName() const {
811   X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
812   if (cert) {
813     int nid = OBJ_obj2nid(cert->sig_alg->algorithm);
814     return OBJ_nid2ln(nid);
815   }
816   return nullptr;
817 }
818
819 int AsyncSSLSocket::getSSLCertSize() const {
820   int certSize = 0;
821   X509 *cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_) : nullptr;
822   if (cert) {
823     EVP_PKEY *key = X509_get_pubkey(cert);
824     certSize = EVP_PKEY_bits(key);
825     EVP_PKEY_free(key);
826   }
827   return certSize;
828 }
829
830 bool AsyncSSLSocket::willBlock(int ret, int *errorOut) noexcept {
831   int error = *errorOut = SSL_get_error(ssl_, ret);
832   if (error == SSL_ERROR_WANT_READ) {
833     // Register for read event if not already.
834     updateEventRegistration(EventHandler::READ, EventHandler::WRITE);
835     return true;
836   } else if (error == SSL_ERROR_WANT_WRITE) {
837     VLOG(3) << "AsyncSSLSocket(fd=" << fd_
838             << ", state=" << int(state_) << ", sslState="
839             << sslState_ << ", events=" << eventFlags_ << "): "
840             << "SSL_ERROR_WANT_WRITE";
841     // Register for write event if not already.
842     updateEventRegistration(EventHandler::WRITE, EventHandler::READ);
843     return true;
844 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
845   } else if (error == SSL_ERROR_WANT_SESS_CACHE_LOOKUP) {
846     // We will block but we can't register our own socket.  The callback that
847     // triggered this code will re-call handleAccept at the appropriate time.
848
849     // We can only get here if the linked libssl.so has support for this feature
850     // as well, otherwise SSL_get_error cannot return our error code.
851     sslState_ = STATE_CACHE_LOOKUP;
852
853     // Unregister for all events while blocked here
854     updateEventRegistration(EventHandler::NONE,
855                             EventHandler::READ | EventHandler::WRITE);
856
857     // The timeout (if set) keeps running here
858     return true;
859 #endif
860 #ifdef SSL_ERROR_WANT_RSA_ASYNC_PENDING
861   } else if (error == SSL_ERROR_WANT_RSA_ASYNC_PENDING) {
862     // Our custom openssl function has kicked off an async request to do
863     // modular exponentiation.  When that call returns, a callback will
864     // be invoked that will re-call handleAccept.
865     sslState_ = STATE_RSA_ASYNC_PENDING;
866
867     // Unregister for all events while blocked here
868     updateEventRegistration(
869       EventHandler::NONE,
870       EventHandler::READ | EventHandler::WRITE
871     );
872
873     // The timeout (if set) keeps running here
874     return true;
875 #endif
876   } else {
877     // SSL_ERROR_ZERO_RETURN is processed here so we can get some detail
878     // in the log
879     long lastError = ERR_get_error();
880     VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
881             << "state=" << state_ << ", "
882             << "sslState=" << sslState_ << ", "
883             << "events=" << std::hex << eventFlags_ << "): "
884             << "SSL error: " << error << ", "
885             << "errno: " << errno << ", "
886             << "ret: " << ret << ", "
887             << "read: " << BIO_number_read(SSL_get_rbio(ssl_)) << ", "
888             << "written: " << BIO_number_written(SSL_get_wbio(ssl_)) << ", "
889             << "func: " << ERR_func_error_string(lastError) << ", "
890             << "reason: " << ERR_reason_error_string(lastError);
891     if (error != SSL_ERROR_SYSCALL) {
892       if (error == SSL_ERROR_SSL) {
893         *errorOut = lastError;
894       }
895       if ((unsigned long)lastError < 0x8000) {
896         errno = ENOSYS;
897       } else {
898         errno = lastError;
899       }
900     }
901     ERR_clear_error();
902     return false;
903   }
904 }
905
906 void AsyncSSLSocket::checkForImmediateRead() noexcept {
907   // openssl may have buffered data that it read from the socket already.
908   // In this case we have to process it immediately, rather than waiting for
909   // the socket to become readable again.
910   if (ssl_ != nullptr && SSL_pending(ssl_) > 0) {
911     AsyncSocket::handleRead();
912   }
913 }
914
915 void
916 AsyncSSLSocket::restartSSLAccept()
917 {
918   VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this << ", fd=" << fd_
919           << ", state=" << int(state_) << ", "
920           << "sslState=" << sslState_ << ", events=" << eventFlags_;
921   DestructorGuard dg(this);
922   assert(
923     sslState_ == STATE_CACHE_LOOKUP ||
924     sslState_ == STATE_RSA_ASYNC_PENDING ||
925     sslState_ == STATE_ERROR ||
926     sslState_ == STATE_CLOSED
927   );
928   if (sslState_ == STATE_CLOSED) {
929     // I sure hope whoever closed this socket didn't delete it already,
930     // but this is not strictly speaking an error
931     return;
932   }
933   if (sslState_ == STATE_ERROR) {
934     // go straight to fail if timeout expired during lookup
935     AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
936                            "SSL accept timed out");
937     failHandshake(__func__, ex);
938     return;
939   }
940   sslState_ = STATE_ACCEPTING;
941   this->handleAccept();
942 }
943
944 void
945 AsyncSSLSocket::handleAccept() noexcept {
946   VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this
947           << ", fd=" << fd_ << ", state=" << int(state_) << ", "
948           << "sslState=" << sslState_ << ", events=" << eventFlags_;
949   assert(server_);
950   assert(state_ == StateEnum::ESTABLISHED &&
951          sslState_ == STATE_ACCEPTING);
952   if (!ssl_) {
953     /* lazily create the SSL structure */
954     try {
955       ssl_ = ctx_->createSSL();
956     } catch (std::exception &e) {
957       sslState_ = STATE_ERROR;
958       AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
959                              "error calling SSLContext::createSSL()");
960       LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this
961                  << ", fd=" << fd_ << "): " << e.what();
962       return failHandshake(__func__, ex);
963     }
964     SSL_set_fd(ssl_, fd_);
965     SSL_set_ex_data(ssl_, getSSLExDataIndex(), this);
966
967     applyVerificationOptions(ssl_);
968   }
969
970   if (server_ && parseClientHello_) {
971     SSL_set_msg_callback_arg(ssl_, this);
972     SSL_set_msg_callback(ssl_, &AsyncSSLSocket::clientHelloParsingCallback);
973   }
974
975   errno = 0;
976   int ret = SSL_accept(ssl_);
977   if (ret <= 0) {
978     int error;
979     if (willBlock(ret, &error)) {
980       return;
981     } else {
982       sslState_ = STATE_ERROR;
983       SSLException ex(error, errno);
984       return failHandshake(__func__, ex);
985     }
986   }
987
988   handshakeComplete_ = true;
989   updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
990
991   // Move into STATE_ESTABLISHED in the normal case that we are in
992   // STATE_ACCEPTING.
993   sslState_ = STATE_ESTABLISHED;
994
995   VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_
996           << " successfully accepted; state=" << int(state_)
997           << ", sslState=" << sslState_ << ", events=" << eventFlags_;
998
999   // Remember the EventBase we are attached to, before we start invoking any
1000   // callbacks (since the callbacks may call detachEventBase()).
1001   EventBase* originalEventBase = eventBase_;
1002
1003   // Call the accept callback.
1004   invokeHandshakeCB();
1005
1006   // Note that the accept callback may have changed our state.
1007   // (set or unset the read callback, called write(), closed the socket, etc.)
1008   // The following code needs to handle these situations correctly.
1009   //
1010   // If the socket has been closed, readCallback_ and writeReqHead_ will
1011   // always be nullptr, so that will prevent us from trying to read or write.
1012   //
1013   // The main thing to check for is if eventBase_ is still originalEventBase.
1014   // If not, we have been detached from this event base, so we shouldn't
1015   // perform any more operations.
1016   if (eventBase_ != originalEventBase) {
1017     return;
1018   }
1019
1020   AsyncSocket::handleInitialReadWrite();
1021 }
1022
1023 void
1024 AsyncSSLSocket::handleConnect() noexcept {
1025   VLOG(3) <<  "AsyncSSLSocket::handleConnect() this=" << this
1026           << ", fd=" << fd_ << ", state=" << int(state_) << ", "
1027           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1028   assert(!server_);
1029   if (state_ < StateEnum::ESTABLISHED) {
1030     return AsyncSocket::handleConnect();
1031   }
1032
1033   assert(state_ == StateEnum::ESTABLISHED &&
1034          sslState_ == STATE_CONNECTING);
1035   assert(ssl_);
1036
1037   errno = 0;
1038   int ret = SSL_connect(ssl_);
1039   if (ret <= 0) {
1040     int error;
1041     if (willBlock(ret, &error)) {
1042       return;
1043     } else {
1044       sslState_ = STATE_ERROR;
1045       SSLException ex(error, errno);
1046       return failHandshake(__func__, ex);
1047     }
1048   }
1049
1050   handshakeComplete_ = true;
1051   updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE);
1052
1053   // Move into STATE_ESTABLISHED in the normal case that we are in
1054   // STATE_CONNECTING.
1055   sslState_ = STATE_ESTABLISHED;
1056
1057   VLOG(3) << "AsyncSSLSocket %p: fd %d successfully connected; "
1058           << "state=" << int(state_) << ", sslState=" << sslState_
1059           << ", events=" << eventFlags_;
1060
1061   // Remember the EventBase we are attached to, before we start invoking any
1062   // callbacks (since the callbacks may call detachEventBase()).
1063   EventBase* originalEventBase = eventBase_;
1064
1065   // Call the handshake callback.
1066   invokeHandshakeCB();
1067
1068   // Note that the connect callback may have changed our state.
1069   // (set or unset the read callback, called write(), closed the socket, etc.)
1070   // The following code needs to handle these situations correctly.
1071   //
1072   // If the socket has been closed, readCallback_ and writeReqHead_ will
1073   // always be nullptr, so that will prevent us from trying to read or write.
1074   //
1075   // The main thing to check for is if eventBase_ is still originalEventBase.
1076   // If not, we have been detached from this event base, so we shouldn't
1077   // perform any more operations.
1078   if (eventBase_ != originalEventBase) {
1079     return;
1080   }
1081
1082   AsyncSocket::handleInitialReadWrite();
1083 }
1084
1085 void AsyncSSLSocket::setReadCB(ReadCallback *callback) {
1086 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1087   // turn on the buffer movable in openssl
1088   if (!isBufferMovable_ && callback != nullptr && callback->isBufferMovable()) {
1089     SSL_set_mode(ssl_, SSL_get_mode(ssl_) | SSL_MODE_MOVE_BUFFER_OWNERSHIP);
1090     isBufferMovable_ = true;
1091   }
1092 #endif
1093
1094   AsyncSocket::setReadCB(callback);
1095 }
1096
1097 void AsyncSSLSocket::prepareReadBuffer(void** buf, size_t* buflen) noexcept {
1098   CHECK(readCallback_);
1099   if (isBufferMovable_) {
1100     *buf = nullptr;
1101     *buflen = 0;
1102   } else {
1103     // buf is necessary for SSLSocket without SSL_MODE_MOVE_BUFFER_OWNERSHIP
1104     readCallback_->getReadBuffer(buf, buflen);
1105   }
1106 }
1107
1108 void
1109 AsyncSSLSocket::handleRead() noexcept {
1110   VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_
1111           << ", state=" << int(state_) << ", "
1112           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1113   if (state_ < StateEnum::ESTABLISHED) {
1114     return AsyncSocket::handleRead();
1115   }
1116
1117
1118   if (sslState_ == STATE_ACCEPTING) {
1119     assert(server_);
1120     handleAccept();
1121     return;
1122   }
1123   else if (sslState_ == STATE_CONNECTING) {
1124     assert(!server_);
1125     handleConnect();
1126     return;
1127   }
1128
1129   // Normal read
1130   AsyncSocket::handleRead();
1131 }
1132
1133 ssize_t
1134 AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1135   VLOG(4) << "AsyncSSLSocket::performRead() this=" << this
1136           << ", buf=" << *buf << ", buflen=" << *buflen;
1137
1138   if (sslState_ == STATE_UNENCRYPTED) {
1139     return AsyncSocket::performRead(buf, buflen, offset);
1140   }
1141
1142   errno = 0;
1143   ssize_t bytes = 0;
1144   if (!isBufferMovable_) {
1145     bytes = SSL_read(ssl_, *buf, *buflen);
1146   }
1147 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
1148   else {
1149     bytes = SSL_read_buf(ssl_, buf, (int *) offset, (int *) buflen);
1150   }
1151 #endif
1152
1153   if (server_ && renegotiateAttempted_) {
1154     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1155                << ", sslstate=" << sslState_ << ", events=" << eventFlags_
1156                << "): client intitiated SSL renegotiation not permitted";
1157     // We pack our own SSLerr here with a dummy function
1158     errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1159                      SSL_CLIENT_RENEGOTIATION_ATTEMPT);
1160     ERR_clear_error();
1161     return READ_ERROR;
1162   }
1163   if (bytes <= 0) {
1164     int error = SSL_get_error(ssl_, bytes);
1165     if (error == SSL_ERROR_WANT_READ) {
1166       // The caller will register for read event if not already.
1167       return READ_BLOCKING;
1168     } else if (error == SSL_ERROR_WANT_WRITE) {
1169       // TODO: Even though we are attempting to read data, SSL_read() may
1170       // need to write data if renegotiation is being performed.  We currently
1171       // don't support this and just fail the read.
1172       LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1173                  << ", sslState=" << sslState_ << ", events=" << eventFlags_
1174                  << "): unsupported SSL renegotiation during read",
1175       errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_READ,
1176                        SSL_INVALID_RENEGOTIATION);
1177       ERR_clear_error();
1178       return READ_ERROR;
1179     } else {
1180       // TODO: Fix this code so that it can return a proper error message
1181       // to the callback, rather than relying on AsyncSocket code which
1182       // can't handle SSL errors.
1183       long lastError = ERR_get_error();
1184
1185       VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", "
1186               << "state=" << state_ << ", "
1187               << "sslState=" << sslState_ << ", "
1188               << "events=" << std::hex << eventFlags_ << "): "
1189               << "bytes: " << bytes << ", "
1190               << "error: " << error << ", "
1191               << "errno: " << errno << ", "
1192               << "func: " << ERR_func_error_string(lastError) << ", "
1193               << "reason: " << ERR_reason_error_string(lastError);
1194       ERR_clear_error();
1195       if (zero_return(error, bytes)) {
1196         return bytes;
1197       }
1198       if (error != SSL_ERROR_SYSCALL) {
1199         if ((unsigned long)lastError < 0x8000) {
1200           errno = ENOSYS;
1201         } else {
1202           errno = lastError;
1203         }
1204       }
1205       return READ_ERROR;
1206     }
1207   } else {
1208     appBytesReceived_ += bytes;
1209     return bytes;
1210   }
1211 }
1212
1213 void AsyncSSLSocket::handleWrite() noexcept {
1214   VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_
1215           << ", state=" << int(state_) << ", "
1216           << "sslState=" << sslState_ << ", events=" << eventFlags_;
1217   if (state_ < StateEnum::ESTABLISHED) {
1218     return AsyncSocket::handleWrite();
1219   }
1220
1221   if (sslState_ == STATE_ACCEPTING) {
1222     assert(server_);
1223     handleAccept();
1224     return;
1225   }
1226
1227   if (sslState_ == STATE_CONNECTING) {
1228     assert(!server_);
1229     handleConnect();
1230     return;
1231   }
1232
1233   // Normal write
1234   AsyncSocket::handleWrite();
1235 }
1236
1237 int AsyncSSLSocket::interpretSSLError(int rc, int error) {
1238   if (error == SSL_ERROR_WANT_READ) {
1239     // TODO: Even though we are attempting to write data, SSL_write() may
1240     // need to read data if renegotiation is being performed.  We currently
1241     // don't support this and just fail the write.
1242     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1243                << ", sslState=" << sslState_ << ", events=" << eventFlags_
1244                << "): " << "unsupported SSL renegotiation during write",
1245       errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1246                        SSL_INVALID_RENEGOTIATION);
1247     ERR_clear_error();
1248     return -1;
1249   } else {
1250     // TODO: Fix this code so that it can return a proper error message
1251     // to the callback, rather than relying on AsyncSocket code which
1252     // can't handle SSL errors.
1253     long lastError = ERR_get_error();
1254     VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1255             << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): "
1256             << "SSL error: " << error << ", errno: " << errno
1257             << ", func: " << ERR_func_error_string(lastError)
1258             << ", reason: " << ERR_reason_error_string(lastError);
1259     if (error != SSL_ERROR_SYSCALL) {
1260       if ((unsigned long)lastError < 0x8000) {
1261         errno = ENOSYS;
1262       } else {
1263         errno = lastError;
1264       }
1265     }
1266     ERR_clear_error();
1267     if (!zero_return(error, rc)) {
1268       return -1;
1269     } else {
1270       return 0;
1271     }
1272   }
1273 }
1274
1275 ssize_t AsyncSSLSocket::performWrite(const iovec* vec,
1276                                       uint32_t count,
1277                                       WriteFlags flags,
1278                                       uint32_t* countWritten,
1279                                       uint32_t* partialWritten) {
1280   if (sslState_ == STATE_UNENCRYPTED) {
1281     return AsyncSocket::performWrite(
1282       vec, count, flags, countWritten, partialWritten);
1283   }
1284   if (sslState_ != STATE_ESTABLISHED) {
1285     LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_)
1286                << ", sslState=" << sslState_
1287                << ", events=" << eventFlags_ << "): "
1288                << "TODO: AsyncSSLSocket currently does not support calling "
1289                << "write() before the handshake has fully completed";
1290       errno = ERR_PACK(ERR_LIB_USER, TASYNCSSLSOCKET_F_PERFORM_WRITE,
1291                        SSL_EARLY_WRITE);
1292       return -1;
1293   }
1294
1295   bool cork = isSet(flags, WriteFlags::CORK);
1296   CorkGuard guard(fd_, count > 1, cork, &corked_);
1297
1298 #if 0
1299 //#ifdef SSL_MODE_WRITE_IOVEC
1300   if (ssl_->expand == nullptr &&
1301       ssl_->compress == nullptr &&
1302       (ssl_->mode & SSL_MODE_WRITE_IOVEC)) {
1303     return performWriteIovec(vec, count, flags, countWritten, partialWritten);
1304   }
1305 #endif
1306
1307   // Declare a buffer used to hold small write requests.  It could point to a
1308   // memory block either on stack or on heap. If it is on heap, we release it
1309   // manually when scope exits
1310   char* combinedBuf{nullptr};
1311   SCOPE_EXIT {
1312     // Note, always keep this check consistent with what we do below
1313     if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) {
1314       delete[] combinedBuf;
1315     }
1316   };
1317
1318   *countWritten = 0;
1319   *partialWritten = 0;
1320   ssize_t totalWritten = 0;
1321   size_t bytesStolenFromNextBuffer = 0;
1322   for (uint32_t i = 0; i < count; i++) {
1323     const iovec* v = vec + i;
1324     size_t offset = bytesStolenFromNextBuffer;
1325     bytesStolenFromNextBuffer = 0;
1326     size_t len = v->iov_len - offset;
1327     const void* buf;
1328     if (len == 0) {
1329       (*countWritten)++;
1330       continue;
1331     }
1332     buf = ((const char*)v->iov_base) + offset;
1333
1334     ssize_t bytes;
1335     errno = 0;
1336     uint32_t buffersStolen = 0;
1337     if ((len < minWriteSize_) && ((i + 1) < count)) {
1338       // Combine this buffer with part or all of the next buffers in
1339       // order to avoid really small-grained calls to SSL_write().
1340       // Each call to SSL_write() produces a separate record in
1341       // the egress SSL stream, and we've found that some low-end
1342       // mobile clients can't handle receiving an HTTP response
1343       // header and the first part of the response body in two
1344       // separate SSL records (even if those two records are in
1345       // the same TCP packet).
1346
1347       if (combinedBuf == nullptr) {
1348         if (minWriteSize_ > MAX_STACK_BUF_SIZE) {
1349           // Allocate the buffer on heap
1350           combinedBuf = new char[minWriteSize_];
1351         } else {
1352           // Allocate the buffer on stack
1353           combinedBuf = (char*)alloca(minWriteSize_);
1354         }
1355       }
1356       assert(combinedBuf != nullptr);
1357
1358       memcpy(combinedBuf, buf, len);
1359       do {
1360         // INVARIANT: i + buffersStolen == complete chunks serialized
1361         uint32_t nextIndex = i + buffersStolen + 1;
1362         bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len,
1363                                              minWriteSize_ - len);
1364         memcpy(combinedBuf + len, vec[nextIndex].iov_base,
1365                bytesStolenFromNextBuffer);
1366         len += bytesStolenFromNextBuffer;
1367         if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) {
1368           // couldn't steal the whole buffer
1369           break;
1370         } else {
1371           bytesStolenFromNextBuffer = 0;
1372           buffersStolen++;
1373         }
1374       } while ((i + buffersStolen + 1) < count && (len < minWriteSize_));
1375       bytes = eorAwareSSLWrite(
1376         ssl_, combinedBuf, len,
1377         (isSet(flags, WriteFlags::EOR) && i + buffersStolen + 1 == count));
1378
1379     } else {
1380       bytes = eorAwareSSLWrite(ssl_, buf, len,
1381                            (isSet(flags, WriteFlags::EOR) && i + 1 == count));
1382     }
1383
1384     if (bytes <= 0) {
1385       int error = SSL_get_error(ssl_, bytes);
1386       if (error == SSL_ERROR_WANT_WRITE) {
1387         // The caller will register for write event if not already.
1388         *partialWritten = offset;
1389         return totalWritten;
1390       }
1391       int rc = interpretSSLError(bytes, error);
1392       if (rc < 0) {
1393         return rc;
1394       } // else fall through to below to correctly record totalWritten
1395     }
1396
1397     totalWritten += bytes;
1398
1399     if (bytes == (ssize_t)len) {
1400       // The full iovec is written.
1401       (*countWritten) += 1 + buffersStolen;
1402       i += buffersStolen;
1403       // continue
1404     } else {
1405       bytes += offset; // adjust bytes to account for all of v
1406       while (bytes >= (ssize_t)v->iov_len) {
1407         // We combined this buf with part or all of the next one, and
1408         // we managed to write all of this buf but not all of the bytes
1409         // from the next one that we'd hoped to write.
1410         bytes -= v->iov_len;
1411         (*countWritten)++;
1412         v = &(vec[++i]);
1413       }
1414       *partialWritten = bytes;
1415       return totalWritten;
1416     }
1417   }
1418
1419   return totalWritten;
1420 }
1421
1422 #if 0
1423 //#ifdef SSL_MODE_WRITE_IOVEC
1424 ssize_t AsyncSSLSocket::performWriteIovec(const iovec* vec,
1425                                           uint32_t count,
1426                                           WriteFlags flags,
1427                                           uint32_t* countWritten,
1428                                           uint32_t* partialWritten) {
1429   size_t tot = 0;
1430   for (uint32_t j = 0; j < count; j++) {
1431     tot += vec[j].iov_len;
1432   }
1433
1434   ssize_t totalWritten = SSL_write_iovec(ssl_, vec, count);
1435
1436   *countWritten = 0;
1437   *partialWritten = 0;
1438   if (totalWritten <= 0) {
1439     return interpretSSLError(totalWritten, SSL_get_error(ssl_, totalWritten));
1440   } else {
1441     ssize_t bytes = totalWritten, i = 0;
1442     while (i < count && bytes >= (ssize_t)vec[i].iov_len) {
1443       // we managed to write all of this buf
1444       bytes -= vec[i].iov_len;
1445       (*countWritten)++;
1446       i++;
1447     }
1448     *partialWritten = bytes;
1449
1450     VLOG(4) << "SSL_write_iovec() writes " << tot
1451             << ", returns " << totalWritten << " bytes"
1452             << ", max_send_fragment=" << ssl_->max_send_fragment
1453             << ", count=" << count << ", countWritten=" << *countWritten;
1454
1455     return totalWritten;
1456   }
1457 }
1458 #endif
1459
1460 int AsyncSSLSocket::eorAwareSSLWrite(SSL *ssl, const void *buf, int n,
1461                                       bool eor) {
1462   if (eor && SSL_get_wbio(ssl)->method == &eorAwareBioMethod) {
1463     if (appEorByteNo_) {
1464       // cannot track for more than one app byte EOR
1465       CHECK(appEorByteNo_ == appBytesWritten_ + n);
1466     } else {
1467       appEorByteNo_ = appBytesWritten_ + n;
1468     }
1469
1470     // 1. It is fine to keep updating minEorRawByteNo_.
1471     // 2. It is _min_ in the sense that SSL record will add some overhead.
1472     minEorRawByteNo_ = getRawBytesWritten() + n;
1473   }
1474
1475   n = sslWriteImpl(ssl, buf, n);
1476   if (n > 0) {
1477     appBytesWritten_ += n;
1478     if (appEorByteNo_) {
1479       if (getRawBytesWritten() >= minEorRawByteNo_) {
1480         minEorRawByteNo_ = 0;
1481       }
1482       if(appBytesWritten_ == appEorByteNo_) {
1483         appEorByteNo_ = 0;
1484       } else {
1485         CHECK(appBytesWritten_ < appEorByteNo_);
1486       }
1487     }
1488   }
1489   return n;
1490 }
1491
1492 void
1493 AsyncSSLSocket::sslInfoCallback(const SSL *ssl, int where, int ret) {
1494   AsyncSSLSocket *sslSocket = AsyncSSLSocket::getFromSSL(ssl);
1495   if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) {
1496     sslSocket->renegotiateAttempted_ = true;
1497   }
1498 }
1499
1500 int AsyncSSLSocket::eorAwareBioWrite(BIO *b, const char *in, int inl) {
1501   int ret;
1502   struct msghdr msg;
1503   struct iovec iov;
1504   int flags = 0;
1505   AsyncSSLSocket *tsslSock;
1506
1507   iov.iov_base = const_cast<char *>(in);
1508   iov.iov_len = inl;
1509   memset(&msg, 0, sizeof(msg));
1510   msg.msg_iov = &iov;
1511   msg.msg_iovlen = 1;
1512
1513   tsslSock =
1514     reinterpret_cast<AsyncSSLSocket*>(BIO_get_app_data(b));
1515   if (tsslSock &&
1516       tsslSock->minEorRawByteNo_ &&
1517       tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) {
1518     flags = MSG_EOR;
1519   }
1520
1521   errno = 0;
1522   ret = sendmsg(b->num, &msg, flags);
1523   BIO_clear_retry_flags(b);
1524   if (ret <= 0) {
1525     if (BIO_sock_should_retry(ret))
1526       BIO_set_retry_write(b);
1527   }
1528   return(ret);
1529 }
1530
1531 int AsyncSSLSocket::sslVerifyCallback(int preverifyOk,
1532                                        X509_STORE_CTX* x509Ctx) {
1533   SSL* ssl = (SSL*) X509_STORE_CTX_get_ex_data(
1534     x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1535   AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl);
1536
1537   VLOG(3) <<  "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", "
1538           << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk;
1539   return (self->handshakeCallback_) ?
1540     self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) :
1541     preverifyOk;
1542 }
1543
1544 void AsyncSSLSocket::enableClientHelloParsing()  {
1545     parseClientHello_ = true;
1546     clientHelloInfo_.reset(new ClientHelloInfo());
1547 }
1548
1549 void AsyncSSLSocket::resetClientHelloParsing(SSL *ssl)  {
1550   SSL_set_msg_callback(ssl, nullptr);
1551   SSL_set_msg_callback_arg(ssl, nullptr);
1552   clientHelloInfo_->clientHelloBuf_.clear();
1553 }
1554
1555 void
1556 AsyncSSLSocket::clientHelloParsingCallback(int written, int version,
1557     int contentType, const void *buf, size_t len, SSL *ssl, void *arg)
1558 {
1559   AsyncSSLSocket *sock = static_cast<AsyncSSLSocket*>(arg);
1560   if (written != 0) {
1561     sock->resetClientHelloParsing(ssl);
1562     return;
1563   }
1564   if (contentType != SSL3_RT_HANDSHAKE) {
1565     sock->resetClientHelloParsing(ssl);
1566     return;
1567   }
1568   if (len == 0) {
1569     return;
1570   }
1571
1572   auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_;
1573   clientHelloBuf.append(IOBuf::wrapBuffer(buf, len));
1574   try {
1575     Cursor cursor(clientHelloBuf.front());
1576     if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) {
1577       sock->resetClientHelloParsing(ssl);
1578       return;
1579     }
1580
1581     if (cursor.totalLength() < 3) {
1582       clientHelloBuf.trimEnd(len);
1583       clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1584       return;
1585     }
1586
1587     uint32_t messageLength = cursor.read<uint8_t>();
1588     messageLength <<= 8;
1589     messageLength |= cursor.read<uint8_t>();
1590     messageLength <<= 8;
1591     messageLength |= cursor.read<uint8_t>();
1592     if (cursor.totalLength() < messageLength) {
1593       clientHelloBuf.trimEnd(len);
1594       clientHelloBuf.append(IOBuf::copyBuffer(buf, len));
1595       return;
1596     }
1597
1598     sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>();
1599     sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>();
1600
1601     cursor.skip(4); // gmt_unix_time
1602     cursor.skip(28); // random_bytes
1603
1604     cursor.skip(cursor.read<uint8_t>()); // session_id
1605
1606     uint16_t cipherSuitesLength = cursor.readBE<uint16_t>();
1607     for (int i = 0; i < cipherSuitesLength; i += 2) {
1608       sock->clientHelloInfo_->
1609         clientHelloCipherSuites_.push_back(cursor.readBE<uint16_t>());
1610     }
1611
1612     uint8_t compressionMethodsLength = cursor.read<uint8_t>();
1613     for (int i = 0; i < compressionMethodsLength; ++i) {
1614       sock->clientHelloInfo_->
1615         clientHelloCompressionMethods_.push_back(cursor.readBE<uint8_t>());
1616     }
1617
1618     if (cursor.totalLength() > 0) {
1619       uint16_t extensionsLength = cursor.readBE<uint16_t>();
1620       while (extensionsLength) {
1621         TLSExtension extensionType = static_cast<TLSExtension>(
1622             cursor.readBE<uint16_t>());
1623         sock->clientHelloInfo_->
1624           clientHelloExtensions_.push_back(extensionType);
1625         extensionsLength -= 2;
1626         uint16_t extensionDataLength = cursor.readBE<uint16_t>();
1627         extensionsLength -= 2;
1628
1629         if (extensionType == TLSExtension::SIGNATURE_ALGORITHMS) {
1630           cursor.skip(2);
1631           extensionDataLength -= 2;
1632           while (extensionDataLength) {
1633             HashAlgorithm hashAlg = static_cast<HashAlgorithm>(
1634                 cursor.readBE<uint8_t>());
1635             SignatureAlgorithm sigAlg = static_cast<SignatureAlgorithm>(
1636                 cursor.readBE<uint8_t>());
1637             extensionDataLength -= 2;
1638             sock->clientHelloInfo_->
1639               clientHelloSigAlgs_.emplace_back(hashAlg, sigAlg);
1640           }
1641         } else {
1642           cursor.skip(extensionDataLength);
1643           extensionsLength -= extensionDataLength;
1644         }
1645       }
1646     }
1647   } catch (std::out_of_range& e) {
1648     // we'll use what we found and cleanup below.
1649     VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): "
1650       << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock;
1651   }
1652
1653   sock->resetClientHelloParsing(ssl);
1654 }
1655
1656 } // namespace