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