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