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