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