Add pre received data API to AsyncSSLSocket.
[folly.git] / folly / io / async / AsyncSSLSocket.h
1 /*
2  * Copyright 2017 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 #pragma once
18
19 #include <iomanip>
20
21 #include <folly/Optional.h>
22 #include <folly/String.h>
23 #include <folly/io/async/AsyncSocket.h>
24 #include <folly/io/async/AsyncTimeout.h>
25 #include <folly/io/async/SSLContext.h>
26 #include <folly/io/async/TimeoutManager.h>
27 #include <folly/io/async/ssl/OpenSSLPtrTypes.h>
28 #include <folly/io/async/ssl/OpenSSLUtils.h>
29 #include <folly/io/async/ssl/SSLErrors.h>
30 #include <folly/io/async/ssl/TLSDefinitions.h>
31
32 #include <folly/Bits.h>
33 #include <folly/io/IOBuf.h>
34 #include <folly/io/Cursor.h>
35 #include <folly/portability/OpenSSL.h>
36 #include <folly/portability/Sockets.h>
37
38 namespace folly {
39
40 /**
41  * A class for performing asynchronous I/O on an SSL connection.
42  *
43  * AsyncSSLSocket allows users to asynchronously wait for data on an
44  * SSL connection, and to asynchronously send data.
45  *
46  * The APIs for reading and writing are intentionally asymmetric.
47  * Waiting for data to read is a persistent API: a callback is
48  * installed, and is notified whenever new data is available.  It
49  * continues to be notified of new events until it is uninstalled.
50  *
51  * AsyncSSLSocket does not provide read timeout functionality,
52  * because it typically cannot determine when the timeout should be
53  * active.  Generally, a timeout should only be enabled when
54  * processing is blocked waiting on data from the remote endpoint.
55  * For server connections, the timeout should not be active if the
56  * server is currently processing one or more outstanding requests for
57  * this connection.  For client connections, the timeout should not be
58  * active if there are no requests pending on the connection.
59  * Additionally, if a client has multiple pending requests, it will
60  * ususally want a separate timeout for each request, rather than a
61  * single read timeout.
62  *
63  * The write API is fairly intuitive: a user can request to send a
64  * block of data, and a callback will be informed once the entire
65  * block has been transferred to the kernel, or on error.
66  * AsyncSSLSocket does provide a send timeout, since most callers
67  * want to give up if the remote end stops responding and no further
68  * progress can be made sending the data.
69  */
70 class AsyncSSLSocket : public virtual AsyncSocket {
71  public:
72   typedef std::unique_ptr<AsyncSSLSocket, Destructor> UniquePtr;
73   using X509_deleter = folly::static_function_deleter<X509, &X509_free>;
74
75   class HandshakeCB {
76    public:
77     virtual ~HandshakeCB() = default;
78
79     /**
80      * handshakeVer() is invoked during handshaking to give the
81      * application chance to validate it's peer's certificate.
82      *
83      * Note that OpenSSL performs only rudimentary internal
84      * consistency verification checks by itself. Any other validation
85      * like whether or not the certificate was issued by a trusted CA.
86      * The default implementation of this callback mimics what what
87      * OpenSSL does internally if SSL_VERIFY_PEER is set with no
88      * verification callback.
89      *
90      * See the passages on verify_callback in SSL_CTX_set_verify(3)
91      * for more details.
92      */
93     virtual bool handshakeVer(AsyncSSLSocket* /*sock*/,
94                                  bool preverifyOk,
95                                  X509_STORE_CTX* /*ctx*/) noexcept {
96       return preverifyOk;
97     }
98
99     /**
100      * handshakeSuc() is called when a new SSL connection is
101      * established, i.e., after SSL_accept/connect() returns successfully.
102      *
103      * The HandshakeCB will be uninstalled before handshakeSuc()
104      * is called.
105      *
106      * @param sock  SSL socket on which the handshake was initiated
107      */
108     virtual void handshakeSuc(AsyncSSLSocket *sock) noexcept = 0;
109
110     /**
111      * handshakeErr() is called if an error occurs while
112      * establishing the SSL connection.
113      *
114      * The HandshakeCB will be uninstalled before handshakeErr()
115      * is called.
116      *
117      * @param sock  SSL socket on which the handshake was initiated
118      * @param ex  An exception representing the error.
119      */
120     virtual void handshakeErr(
121       AsyncSSLSocket *sock,
122       const AsyncSocketException& ex)
123       noexcept = 0;
124   };
125
126   class HandshakeTimeout : public AsyncTimeout {
127    public:
128     HandshakeTimeout(AsyncSSLSocket* sslSocket, EventBase* eventBase)
129       : AsyncTimeout(eventBase)
130       , sslSocket_(sslSocket) {}
131
132     virtual void timeoutExpired() noexcept {
133       sslSocket_->timeoutExpired();
134     }
135
136    private:
137     AsyncSSLSocket* sslSocket_;
138   };
139
140   // Timer for if we fallback from SSL connects to TCP connects
141   class ConnectionTimeout : public AsyncTimeout {
142    public:
143     ConnectionTimeout(AsyncSSLSocket* sslSocket, EventBase* eventBase)
144         : AsyncTimeout(eventBase), sslSocket_(sslSocket) {}
145
146     virtual void timeoutExpired() noexcept override {
147       sslSocket_->timeoutExpired();
148     }
149
150    private:
151     AsyncSSLSocket* sslSocket_;
152   };
153
154   /**
155    * Create a client AsyncSSLSocket
156    */
157   AsyncSSLSocket(const std::shared_ptr<folly::SSLContext> &ctx,
158                  EventBase* evb, bool deferSecurityNegotiation = false);
159
160   /**
161    * Create a server/client AsyncSSLSocket from an already connected
162    * socket file descriptor.
163    *
164    * Note that while AsyncSSLSocket enables TCP_NODELAY for sockets it creates
165    * when connecting, it does not change the socket options when given an
166    * existing file descriptor.  If callers want TCP_NODELAY enabled when using
167    * this version of the constructor, they need to explicitly call
168    * setNoDelay(true) after the constructor returns.
169    *
170    * @param ctx             SSL context for this connection.
171    * @param evb EventBase that will manage this socket.
172    * @param fd  File descriptor to take over (should be a connected socket).
173    * @param server Is socket in server mode?
174    * @param deferSecurityNegotiation
175    *          unencrypted data can be sent before sslConn/Accept
176    */
177   AsyncSSLSocket(const std::shared_ptr<folly::SSLContext>& ctx,
178                  EventBase* evb, int fd,
179                  bool server = true, bool deferSecurityNegotiation = false);
180
181
182   /**
183    * Helper function to create a server/client shared_ptr<AsyncSSLSocket>.
184    */
185   static std::shared_ptr<AsyncSSLSocket> newSocket(
186     const std::shared_ptr<folly::SSLContext>& ctx,
187     EventBase* evb, int fd, bool server=true,
188     bool deferSecurityNegotiation = false) {
189     return std::shared_ptr<AsyncSSLSocket>(
190       new AsyncSSLSocket(ctx, evb, fd, server, deferSecurityNegotiation),
191       Destructor());
192   }
193
194   /**
195    * Helper function to create a client shared_ptr<AsyncSSLSocket>.
196    */
197   static std::shared_ptr<AsyncSSLSocket> newSocket(
198     const std::shared_ptr<folly::SSLContext>& ctx,
199     EventBase* evb, bool deferSecurityNegotiation = false) {
200     return std::shared_ptr<AsyncSSLSocket>(
201       new AsyncSSLSocket(ctx, evb, deferSecurityNegotiation),
202       Destructor());
203   }
204
205
206 #if FOLLY_OPENSSL_HAS_SNI
207   /**
208    * Create a client AsyncSSLSocket with tlsext_servername in
209    * the Client Hello message.
210    */
211   AsyncSSLSocket(const std::shared_ptr<folly::SSLContext> &ctx,
212                   EventBase* evb,
213                  const std::string& serverName,
214                 bool deferSecurityNegotiation = false);
215
216   /**
217    * Create a client AsyncSSLSocket from an already connected
218    * socket file descriptor.
219    *
220    * Note that while AsyncSSLSocket enables TCP_NODELAY for sockets it creates
221    * when connecting, it does not change the socket options when given an
222    * existing file descriptor.  If callers want TCP_NODELAY enabled when using
223    * this version of the constructor, they need to explicitly call
224    * setNoDelay(true) after the constructor returns.
225    *
226    * @param ctx  SSL context for this connection.
227    * @param evb  EventBase that will manage this socket.
228    * @param fd   File descriptor to take over (should be a connected socket).
229    * @param serverName tlsext_hostname that will be sent in ClientHello.
230    */
231   AsyncSSLSocket(const std::shared_ptr<folly::SSLContext>& ctx,
232                   EventBase* evb,
233                   int fd,
234                  const std::string& serverName,
235                 bool deferSecurityNegotiation = false);
236
237   static std::shared_ptr<AsyncSSLSocket> newSocket(
238     const std::shared_ptr<folly::SSLContext>& ctx,
239     EventBase* evb,
240     const std::string& serverName,
241     bool deferSecurityNegotiation = false) {
242     return std::shared_ptr<AsyncSSLSocket>(
243       new AsyncSSLSocket(ctx, evb, serverName, deferSecurityNegotiation),
244       Destructor());
245   }
246 #endif // FOLLY_OPENSSL_HAS_SNI
247
248   /**
249    * TODO: implement support for SSL renegotiation.
250    *
251    * This involves proper handling of the SSL_ERROR_WANT_READ/WRITE
252    * code as a result of SSL_write/read(), instead of returning an
253    * error. In that case, the READ/WRITE event should be registered,
254    * and a flag (e.g., writeBlockedOnRead) should be set to indiciate
255    * the condition. In the next invocation of read/write callback, if
256    * the flag is on, performWrite()/performRead() should be called in
257    * addition to the normal call to performRead()/performWrite(), and
258    * the flag should be reset.
259    */
260
261   // Inherit TAsyncTransport methods from AsyncSocket except the
262   // following.
263   // See the documentation in TAsyncTransport.h
264   // TODO: implement graceful shutdown in close()
265   // TODO: implement detachSSL() that returns the SSL connection
266   virtual void closeNow() override;
267   virtual void shutdownWrite() override;
268   virtual void shutdownWriteNow() override;
269   virtual bool good() const override;
270   virtual bool connecting() const override;
271   virtual std::string getApplicationProtocol() noexcept override;
272
273   virtual std::string getSecurityProtocol() const override { return "TLS"; }
274
275   bool isEorTrackingEnabled() const override;
276   virtual void setEorTracking(bool track) override;
277   virtual size_t getRawBytesWritten() const override;
278   virtual size_t getRawBytesReceived() const override;
279   void enableClientHelloParsing();
280
281   void setPreReceivedData(std::unique_ptr<IOBuf> data);
282
283   /**
284    * Accept an SSL connection on the socket.
285    *
286    * The callback will be invoked and uninstalled when an SSL
287    * connection has been established on the underlying socket.
288    * The value of verifyPeer determines the client verification method.
289    * By default, its set to use the value in the underlying context
290    *
291    * @param callback callback object to invoke on success/failure
292    * @param timeout timeout for this function in milliseconds, or 0 for no
293    *                timeout
294    * @param verifyPeer  SSLVerifyPeerEnum uses the options specified in the
295    *                context by default, can be set explcitly to override the
296    *                method in the context
297    */
298   virtual void sslAccept(
299       HandshakeCB* callback,
300       std::chrono::milliseconds timeout = std::chrono::milliseconds::zero(),
301       const folly::SSLContext::SSLVerifyPeerEnum& verifyPeer =
302           folly::SSLContext::SSLVerifyPeerEnum::USE_CTX);
303
304   /**
305    * Invoke SSL accept following an asynchronous session cache lookup
306    */
307   void restartSSLAccept();
308
309   /**
310    * Connect to the given address, invoking callback when complete or on error
311    *
312    * Note timeout applies to TCP + SSL connection time
313    */
314   void connect(ConnectCallback* callback,
315                const folly::SocketAddress& address,
316                int timeout = 0,
317                const OptionMap &options = emptyOptionMap,
318                const folly::SocketAddress& bindAddr = anyAddress())
319                noexcept override;
320
321   using AsyncSocket::connect;
322
323   /**
324    * Initiate an SSL connection on the socket
325    * The callback will be invoked and uninstalled when an SSL connection
326    * has been establshed on the underlying socket.
327    * The verification option verifyPeer is applied if it's passed explicitly.
328    * If it's not, the options in SSLContext set on the underlying SSLContext
329    * are applied.
330    *
331    * @param callback callback object to invoke on success/failure
332    * @param timeout timeout for this function in milliseconds, or 0 for no
333    *                timeout
334    * @param verifyPeer  SSLVerifyPeerEnum uses the options specified in the
335    *                context by default, can be set explcitly to override the
336    *                method in the context. If verification is turned on sets
337    *                SSL_VERIFY_PEER and invokes
338    *                HandshakeCB::handshakeVer().
339    */
340   virtual void sslConn(
341       HandshakeCB* callback,
342       std::chrono::milliseconds timeout = std::chrono::milliseconds::zero(),
343       const folly::SSLContext::SSLVerifyPeerEnum& verifyPeer =
344           folly::SSLContext::SSLVerifyPeerEnum::USE_CTX);
345
346   enum SSLStateEnum {
347     STATE_UNINIT,
348     STATE_UNENCRYPTED,
349     STATE_ACCEPTING,
350     STATE_CACHE_LOOKUP,
351     STATE_ASYNC_PENDING,
352     STATE_CONNECTING,
353     STATE_ESTABLISHED,
354     STATE_REMOTE_CLOSED, /// remote end closed; we can still write
355     STATE_CLOSING,       ///< close() called, but waiting on writes to complete
356     /// close() called with pending writes, before connect() has completed
357     STATE_CONNECTING_CLOSING,
358     STATE_CLOSED,
359     STATE_ERROR
360   };
361
362   SSLStateEnum getSSLState() const { return sslState_;}
363
364   /**
365    * Get a handle to the negotiated SSL session.  This increments the session
366    * refcount and must be deallocated by the caller.
367    */
368   SSL_SESSION *getSSLSession();
369
370   /**
371    * Get a handle to the SSL struct.
372    */
373   const SSL* getSSL() const;
374
375   /**
376    * Set the SSL session to be used during sslConn.  AsyncSSLSocket will
377    * hold a reference to the session until it is destroyed or released by the
378    * underlying SSL structure.
379    *
380    * @param takeOwnership if true, AsyncSSLSocket will assume the caller's
381    *                      reference count to session.
382    */
383   void setSSLSession(SSL_SESSION *session, bool takeOwnership = false);
384
385   /**
386    * Get the name of the protocol selected by the client during
387    * Next Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
388    * (ALPN)
389    *
390    * Throw an exception if openssl does not support NPN
391    *
392    * @param protoName      Name of the protocol (not guaranteed to be
393    *                       null terminated); will be set to nullptr if
394    *                       the client did not negotiate a protocol.
395    *                       Note: the AsyncSSLSocket retains ownership
396    *                       of this string.
397    * @param protoNameLen   Length of the name.
398    * @param protoType      Whether this was an NPN or ALPN negotiation
399    */
400   virtual void getSelectedNextProtocol(
401       const unsigned char** protoName,
402       unsigned* protoLen,
403       SSLContext::NextProtocolType* protoType = nullptr) const;
404
405   /**
406    * Get the name of the protocol selected by the client during
407    * Next Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
408    * (ALPN)
409    *
410    * @param protoName      Name of the protocol (not guaranteed to be
411    *                       null terminated); will be set to nullptr if
412    *                       the client did not negotiate a protocol.
413    *                       Note: the AsyncSSLSocket retains ownership
414    *                       of this string.
415    * @param protoNameLen   Length of the name.
416    * @param protoType      Whether this was an NPN or ALPN negotiation
417    * @return false if openssl does not support NPN
418    */
419   virtual bool getSelectedNextProtocolNoThrow(
420       const unsigned char** protoName,
421       unsigned* protoLen,
422       SSLContext::NextProtocolType* protoType = nullptr) const;
423
424   /**
425    * Determine if the session specified during setSSLSession was reused
426    * or if the server rejected it and issued a new session.
427    */
428   virtual bool getSSLSessionReused() const;
429
430   /**
431    * true if the session was resumed using session ID
432    */
433   bool sessionIDResumed() const { return sessionIDResumed_; }
434
435   void setSessionIDResumed(bool resumed) {
436     sessionIDResumed_ = resumed;
437   }
438
439   /**
440    * Get the negociated cipher name for this SSL connection.
441    * Returns the cipher used or the constant value "NONE" when no SSL session
442    * has been established.
443    */
444   virtual const char* getNegotiatedCipherName() const;
445
446   /**
447    * Get the server name for this SSL connection.
448    * Returns the server name used or the constant value "NONE" when no SSL
449    * session has been established.
450    * If openssl has no SNI support, throw TTransportException.
451    */
452   const char *getSSLServerName() const;
453
454   /**
455    * Get the server name for this SSL connection.
456    * Returns the server name used or the constant value "NONE" when no SSL
457    * session has been established.
458    * If openssl has no SNI support, return "NONE"
459    */
460   const char *getSSLServerNameNoThrow() const;
461
462   /**
463    * Get the SSL version for this connection.
464    * Possible return values are SSL2_VERSION, SSL3_VERSION, TLS1_VERSION,
465    * with hexa representations 0x200, 0x300, 0x301,
466    * or 0 if no SSL session has been established.
467    */
468   int getSSLVersion() const;
469
470   /**
471    * Get the signature algorithm used in the cert that is used for this
472    * connection.
473    */
474   const char *getSSLCertSigAlgName() const;
475
476   /**
477    * Get the certificate size used for this SSL connection.
478    */
479   int getSSLCertSize() const;
480
481   /**
482    * Get the certificate used for this SSL connection. May be null
483    */
484   virtual const X509* getSelfCert() const override;
485
486   virtual void attachEventBase(EventBase* eventBase) override {
487     AsyncSocket::attachEventBase(eventBase);
488     handshakeTimeout_.attachEventBase(eventBase);
489     connectionTimeout_.attachEventBase(eventBase);
490   }
491
492   virtual void detachEventBase() override {
493     AsyncSocket::detachEventBase();
494     handshakeTimeout_.detachEventBase();
495     connectionTimeout_.detachEventBase();
496   }
497
498   virtual bool isDetachable() const override {
499     return AsyncSocket::isDetachable() && !handshakeTimeout_.isScheduled();
500   }
501
502   virtual void attachTimeoutManager(TimeoutManager* manager) {
503     handshakeTimeout_.attachTimeoutManager(manager);
504   }
505
506   virtual void detachTimeoutManager() {
507     handshakeTimeout_.detachTimeoutManager();
508   }
509
510 #if OPENSSL_VERSION_NUMBER >= 0x009080bfL
511   /**
512    * This function will set the SSL context for this socket to the
513    * argument. This should only be used on client SSL Sockets that have
514    * already called detachSSLContext();
515    */
516   void attachSSLContext(const std::shared_ptr<folly::SSLContext>& ctx);
517
518   /**
519    * Detaches the SSL context for this socket.
520    */
521   void detachSSLContext();
522 #endif
523
524 #if FOLLY_OPENSSL_HAS_SNI
525   /**
526    * Switch the SSLContext to continue the SSL handshake.
527    * It can only be used in server mode.
528    */
529   void switchServerSSLContext(
530     const std::shared_ptr<folly::SSLContext>& handshakeCtx);
531
532   /**
533    * Did server recognize/support the tlsext_hostname in Client Hello?
534    * It can only be used in client mode.
535    *
536    * @return true - tlsext_hostname is matched by the server
537    *         false - tlsext_hostname is not matched or
538    *                 is not supported by server
539    */
540   bool isServerNameMatch() const;
541
542   /**
543    * Set the SNI hostname that we'll advertise to the server in the
544    * ClientHello message.
545    */
546   void setServerName(std::string serverName) noexcept;
547 #endif // FOLLY_OPENSSL_HAS_SNI
548
549   void timeoutExpired() noexcept;
550
551   /**
552    * Get the list of supported ciphers sent by the client in the client's
553    * preference order.
554    */
555   void getSSLClientCiphers(
556       std::string& clientCiphers,
557       bool convertToString = true) const;
558
559   /**
560    * Get the list of compression methods sent by the client in TLS Hello.
561    */
562   std::string getSSLClientComprMethods() const;
563
564   /**
565    * Get the list of TLS extensions sent by the client in the TLS Hello.
566    */
567   std::string getSSLClientExts() const;
568
569   std::string getSSLClientSigAlgs() const;
570
571   /**
572    * Get the list of versions in the supported versions extension (used to
573    * negotiate TLS 1.3).
574    */
575   std::string getSSLClientSupportedVersions() const;
576
577   std::string getSSLAlertsReceived() const;
578
579   /**
580    * Get the list of shared ciphers between the server and the client.
581    * Works well for only SSLv2, not so good for SSLv3 or TLSv1.
582    */
583   void getSSLSharedCiphers(std::string& sharedCiphers) const;
584
585   /**
586    * Get the list of ciphers supported by the server in the server's
587    * preference order.
588    */
589   void getSSLServerCiphers(std::string& serverCiphers) const;
590
591   static int getSSLExDataIndex();
592   static AsyncSSLSocket* getFromSSL(const SSL *ssl);
593   static int bioWrite(BIO* b, const char* in, int inl);
594   static int bioRead(BIO* b, char* out, int outl);
595   void resetClientHelloParsing(SSL *ssl);
596   static void clientHelloParsingCallback(int write_p, int version,
597       int content_type, const void *buf, size_t len, SSL *ssl, void *arg);
598   static const char* getSSLServerNameFromSSL(SSL* ssl);
599
600   // For unit-tests
601   ssl::ClientHelloInfo* getClientHelloInfo() const {
602     return clientHelloInfo_.get();
603   }
604
605   /**
606    * Returns the time taken to complete a handshake.
607    */
608   virtual std::chrono::nanoseconds getHandshakeTime() const {
609     return handshakeEndTime_ - handshakeStartTime_;
610   }
611
612   void setMinWriteSize(size_t minWriteSize) {
613     minWriteSize_ = minWriteSize;
614   }
615
616   size_t getMinWriteSize() const {
617     return minWriteSize_;
618   }
619
620   void setReadCB(ReadCallback* callback) override;
621
622   /**
623    * Tries to enable the buffer movable experimental feature in openssl.
624    * This is not guaranteed to succeed in case openssl does not have
625    * the experimental feature built in.
626    */
627   void setBufferMovableEnabled(bool enabled);
628
629   /**
630    * Returns the peer certificate, or nullptr if no peer certificate received.
631    */
632   virtual ssl::X509UniquePtr getPeerCert() const override {
633     if (!ssl_) {
634       return nullptr;
635     }
636
637     X509* cert = SSL_get_peer_certificate(ssl_);
638     return ssl::X509UniquePtr(cert);
639   }
640
641   /**
642    * Force AsyncSSLSocket object to cache local and peer socket addresses.
643    * If called with "true" before connect() this function forces full local
644    * and remote socket addresses to be cached in the socket object and available
645    * through getLocalAddress()/getPeerAddress() methods even after the socket is
646    * closed.
647    */
648   void forceCacheAddrOnFailure(bool force) { cacheAddrOnFailure_ = force; }
649
650   const std::string& getServiceIdentity() const { return serviceIdentity_; }
651
652   void setServiceIdentity(std::string serviceIdentity) {
653     serviceIdentity_ = std::move(serviceIdentity);
654   }
655
656   void setCertCacheHit(bool hit) {
657     certCacheHit_ = hit;
658   }
659
660   bool getCertCacheHit() const {
661     return certCacheHit_;
662   }
663
664   bool sessionResumptionAttempted() const {
665     return sessionResumptionAttempted_;
666   }
667
668  private:
669
670   void init();
671
672  protected:
673
674   /**
675    * Protected destructor.
676    *
677    * Users of AsyncSSLSocket must never delete it directly.  Instead, invoke
678    * destroy() instead.  (See the documentation in DelayedDestruction.h for
679    * more details.)
680    */
681   ~AsyncSSLSocket();
682
683   // Inherit event notification methods from AsyncSocket except
684   // the following.
685   void prepareReadBuffer(void** buf, size_t* buflen) override;
686   void handleRead() noexcept override;
687   void handleWrite() noexcept override;
688   void handleAccept() noexcept;
689   void handleConnect() noexcept override;
690
691   void invalidState(HandshakeCB* callback);
692   bool willBlock(int ret,
693                  int* sslErrorOut,
694                  unsigned long* errErrorOut) noexcept;
695
696   virtual void checkForImmediateRead() noexcept override;
697   // AsyncSocket calls this at the wrong time for SSL
698   void handleInitialReadWrite() noexcept override {}
699
700   WriteResult interpretSSLError(int rc, int error);
701   ReadResult performRead(void** buf, size_t* buflen, size_t* offset) override;
702   WriteResult performWrite(
703       const iovec* vec,
704       uint32_t count,
705       WriteFlags flags,
706       uint32_t* countWritten,
707       uint32_t* partialWritten) override;
708
709   ssize_t performWriteIovec(const iovec* vec, uint32_t count,
710                             WriteFlags flags, uint32_t* countWritten,
711                             uint32_t* partialWritten);
712
713   // This virtual wrapper around SSL_write exists solely for testing/mockability
714   virtual int sslWriteImpl(SSL *ssl, const void *buf, int n) {
715     return SSL_write(ssl, buf, n);
716   }
717
718   /**
719    * Apply verification options passed to sslConn/sslAccept or those set
720    * in the underlying SSLContext object.
721    *
722    * @param ssl pointer to the SSL object on which verification options will be
723    * applied. If verifyPeer_ was explicitly set either via sslConn/sslAccept,
724    * those options override the settings in the underlying SSLContext.
725    */
726   void applyVerificationOptions(SSL * ssl);
727
728   /**
729    * Sets up SSL with a custom write bio which intercepts all writes.
730    *
731    * @return true, if succeeds and false if there is an error creating the bio.
732    */
733   bool setupSSLBio();
734
735   /**
736    * A SSL_write wrapper that understand EOR
737    *
738    * @param ssl: SSL* object
739    * @param buf: Buffer to be written
740    * @param n:   Number of bytes to be written
741    * @param eor: Does the last byte (buf[n-1]) have the app-last-byte?
742    * @return:    The number of app bytes successfully written to the socket
743    */
744   int eorAwareSSLWrite(SSL *ssl, const void *buf, int n, bool eor);
745
746   // Inherit error handling methods from AsyncSocket, plus the following.
747   void failHandshake(const char* fn, const AsyncSocketException& ex);
748
749   void invokeHandshakeErr(const AsyncSocketException& ex);
750   void invokeHandshakeCB();
751
752   void invokeConnectErr(const AsyncSocketException& ex) override;
753   void invokeConnectSuccess() override;
754   void scheduleConnectTimeout() override;
755
756   void cacheLocalPeerAddr();
757
758   void startSSLConnect();
759
760   static void sslInfoCallback(const SSL *ssl, int type, int val);
761
762   // Whether the current write to the socket should use MSG_MORE.
763   bool corkCurrentWrite_{false};
764   // SSL related members.
765   bool server_{false};
766   // Used to prevent client-initiated renegotiation.  Note that AsyncSSLSocket
767   // doesn't fully support renegotiation, so we could just fail all attempts
768   // to enforce this.  Once it is supported, we should make it an option
769   // to disable client-initiated renegotiation.
770   bool handshakeComplete_{false};
771   bool renegotiateAttempted_{false};
772   SSLStateEnum sslState_{STATE_UNINIT};
773   std::shared_ptr<folly::SSLContext> ctx_;
774   // Callback for SSL_accept() or SSL_connect()
775   HandshakeCB* handshakeCallback_{nullptr};
776   SSL* ssl_{nullptr};
777   SSL_SESSION *sslSession_{nullptr};
778   HandshakeTimeout handshakeTimeout_;
779   ConnectionTimeout connectionTimeout_;
780   // whether the SSL session was resumed using session ID or not
781   bool sessionIDResumed_{false};
782
783   // Whether to track EOR or not.
784   bool trackEor_{false};
785
786   // The app byte num that we are tracking for the MSG_EOR
787   // Only one app EOR byte can be tracked.
788   size_t appEorByteNo_{0};
789
790   // Try to avoid calling SSL_write() for buffers smaller than this.
791   // It doesn't take effect when it is 0.
792   size_t minWriteSize_{1500};
793
794   // When openssl is about to sendmsg() across the minEorRawBytesNo_,
795   // it will pass MSG_EOR to sendmsg().
796   size_t minEorRawByteNo_{0};
797 #if FOLLY_OPENSSL_HAS_SNI
798   std::shared_ptr<folly::SSLContext> handshakeCtx_;
799   std::string tlsextHostname_;
800 #endif
801
802   // a service identity that this socket/connection is associated with
803   std::string serviceIdentity_;
804
805   folly::SSLContext::SSLVerifyPeerEnum
806     verifyPeer_{folly::SSLContext::SSLVerifyPeerEnum::USE_CTX};
807
808   // Callback for SSL_CTX_set_verify()
809   static int sslVerifyCallback(int preverifyOk, X509_STORE_CTX* ctx);
810
811   bool parseClientHello_{false};
812   bool cacheAddrOnFailure_{false};
813   bool bufferMovableEnabled_{false};
814   bool certCacheHit_{false};
815   std::unique_ptr<ssl::ClientHelloInfo> clientHelloInfo_;
816   std::vector<std::pair<char, StringPiece>> alertsReceived_;
817
818   // Time taken to complete the ssl handshake.
819   std::chrono::steady_clock::time_point handshakeStartTime_;
820   std::chrono::steady_clock::time_point handshakeEndTime_;
821   std::chrono::milliseconds handshakeConnectTimeout_{0};
822   bool sessionResumptionAttempted_{false};
823
824   std::unique_ptr<IOBuf> preReceivedData_;
825 };
826
827 } // namespace