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