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