5aeb159c65fb635b8bc872688560ed6712348832
[folly.git] / folly / io / async / AsyncSocket.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 <folly/Optional.h>
20 #include <folly/SocketAddress.h>
21 #include <folly/detail/SocketFastOpen.h>
22 #include <folly/io/IOBuf.h>
23 #include <folly/io/ShutdownSocketSet.h>
24 #include <folly/io/async/AsyncSocketException.h>
25 #include <folly/io/async/AsyncTimeout.h>
26 #include <folly/io/async/AsyncTransport.h>
27 #include <folly/io/async/DelayedDestruction.h>
28 #include <folly/io/async/EventHandler.h>
29 #include <folly/portability/Sockets.h>
30
31 #include <sys/types.h>
32
33 #include <chrono>
34 #include <memory>
35 #include <map>
36
37 namespace folly {
38
39 /**
40  * A class for performing asynchronous I/O on a socket.
41  *
42  * AsyncSocket allows users to asynchronously wait for data on a socket, and
43  * to asynchronously send data.
44  *
45  * The APIs for reading and writing are intentionally asymmetric.  Waiting for
46  * data to read is a persistent API: a callback is installed, and is notified
47  * whenever new data is available.  It continues to be notified of new events
48  * until it is uninstalled.
49  *
50  * AsyncSocket does not provide read timeout functionality, because it
51  * typically cannot determine when the timeout should be active.  Generally, a
52  * timeout should only be enabled when processing is blocked waiting on data
53  * from the remote endpoint.  For server sockets, the timeout should not be
54  * active if the server is currently processing one or more outstanding
55  * requests for this socket.  For client sockets, the timeout should not be
56  * active if there are no requests pending on the socket.  Additionally, if a
57  * client has multiple pending requests, it will ususally want a separate
58  * timeout for each request, rather than a single read timeout.
59  *
60  * The write API is fairly intuitive: a user can request to send a block of
61  * data, and a callback will be informed once the entire block has been
62  * transferred to the kernel, or on error.  AsyncSocket does provide a send
63  * timeout, since most callers want to give up if the remote end stops
64  * responding and no further progress can be made sending the data.
65  */
66
67 #if defined __linux__ && !defined SO_NO_TRANSPARENT_TLS
68 #define SO_NO_TRANSPARENT_TLS 200
69 #endif
70
71 #ifdef _MSC_VER
72 // We do a dynamic_cast on this, in
73 // AsyncTransportWrapper::getUnderlyingTransport so be safe and
74 // force displacements for it. See:
75 // https://msdn.microsoft.com/en-us/library/7sf3txa8.aspx
76 #pragma vtordisp(push, 2)
77 #endif
78 class AsyncSocket : virtual public AsyncTransportWrapper {
79  public:
80   typedef std::unique_ptr<AsyncSocket, Destructor> UniquePtr;
81
82   class ConnectCallback {
83    public:
84     virtual ~ConnectCallback() = default;
85
86     /**
87      * connectSuccess() will be invoked when the connection has been
88      * successfully established.
89      */
90     virtual void connectSuccess() noexcept = 0;
91
92     /**
93      * connectErr() will be invoked if the connection attempt fails.
94      *
95      * @param ex        An exception describing the error that occurred.
96      */
97     virtual void connectErr(const AsyncSocketException& ex)
98       noexcept = 0;
99   };
100
101   class EvbChangeCallback {
102    public:
103     virtual ~EvbChangeCallback() = default;
104
105     // Called when the socket has been attached to a new EVB
106     // and is called from within that EVB thread
107     virtual void evbAttached(AsyncSocket* socket) = 0;
108
109     // Called when the socket is detached from an EVB and
110     // is called from the EVB thread being detached
111     virtual void evbDetached(AsyncSocket* socket) = 0;
112   };
113
114   explicit AsyncSocket();
115   /**
116    * Create a new unconnected AsyncSocket.
117    *
118    * connect() must later be called on this socket to establish a connection.
119    */
120   explicit AsyncSocket(EventBase* evb);
121
122   void setShutdownSocketSet(ShutdownSocketSet* ss);
123
124   /**
125    * Create a new AsyncSocket and begin the connection process.
126    *
127    * @param evb             EventBase that will manage this socket.
128    * @param address         The address to connect to.
129    * @param connectTimeout  Optional timeout in milliseconds for the connection
130    *                        attempt.
131    */
132   AsyncSocket(EventBase* evb,
133                const folly::SocketAddress& address,
134                uint32_t connectTimeout = 0);
135
136   /**
137    * Create a new AsyncSocket and begin the connection process.
138    *
139    * @param evb             EventBase that will manage this socket.
140    * @param ip              IP address to connect to (dotted-quad).
141    * @param port            Destination port in host byte order.
142    * @param connectTimeout  Optional timeout in milliseconds for the connection
143    *                        attempt.
144    */
145   AsyncSocket(EventBase* evb,
146                const std::string& ip,
147                uint16_t port,
148                uint32_t connectTimeout = 0);
149
150   /**
151    * Create a AsyncSocket from an already connected socket file descriptor.
152    *
153    * Note that while AsyncSocket enables TCP_NODELAY for sockets it creates
154    * when connecting, it does not change the socket options when given an
155    * existing file descriptor.  If callers want TCP_NODELAY enabled when using
156    * this version of the constructor, they need to explicitly call
157    * setNoDelay(true) after the constructor returns.
158    *
159    * @param evb EventBase that will manage this socket.
160    * @param fd  File descriptor to take over (should be a connected socket).
161    */
162   AsyncSocket(EventBase* evb, int fd);
163
164   /**
165    * Helper function to create a shared_ptr<AsyncSocket>.
166    *
167    * This passes in the correct destructor object, since AsyncSocket's
168    * destructor is protected and cannot be invoked directly.
169    */
170   static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb) {
171     return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb),
172                                            Destructor());
173   }
174
175   /**
176    * Helper function to create a shared_ptr<AsyncSocket>.
177    */
178   static std::shared_ptr<AsyncSocket> newSocket(
179       EventBase* evb,
180       const folly::SocketAddress& address,
181       uint32_t connectTimeout = 0) {
182     return std::shared_ptr<AsyncSocket>(
183         new AsyncSocket(evb, address, connectTimeout),
184         Destructor());
185   }
186
187   /**
188    * Helper function to create a shared_ptr<AsyncSocket>.
189    */
190   static std::shared_ptr<AsyncSocket> newSocket(
191       EventBase* evb,
192       const std::string& ip,
193       uint16_t port,
194       uint32_t connectTimeout = 0) {
195     return std::shared_ptr<AsyncSocket>(
196         new AsyncSocket(evb, ip, port, connectTimeout),
197         Destructor());
198   }
199
200   /**
201    * Helper function to create a shared_ptr<AsyncSocket>.
202    */
203   static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb, int fd) {
204     return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb, fd),
205                                            Destructor());
206   }
207
208   /**
209    * Destroy the socket.
210    *
211    * AsyncSocket::destroy() must be called to destroy the socket.
212    * The normal destructor is private, and should not be invoked directly.
213    * This prevents callers from deleting a AsyncSocket while it is invoking a
214    * callback.
215    */
216   virtual void destroy() override;
217
218   /**
219    * Get the EventBase used by this socket.
220    */
221   EventBase* getEventBase() const override {
222     return eventBase_;
223   }
224
225   /**
226    * Get the file descriptor used by the AsyncSocket.
227    */
228   virtual int getFd() const {
229     return fd_;
230   }
231
232   /**
233    * Extract the file descriptor from the AsyncSocket.
234    *
235    * This will immediately cause any installed callbacks to be invoked with an
236    * error.  The AsyncSocket may no longer be used after the file descriptor
237    * has been extracted.
238    *
239    * Returns the file descriptor.  The caller assumes ownership of the
240    * descriptor, and it will not be closed when the AsyncSocket is destroyed.
241    */
242   virtual int detachFd();
243
244   /**
245    * Uniquely identifies a handle to a socket option value. Each
246    * combination of level and option name corresponds to one socket
247    * option value.
248    */
249   class OptionKey {
250    public:
251     bool operator<(const OptionKey& other) const {
252       if (level == other.level) {
253         return optname < other.optname;
254       }
255       return level < other.level;
256     }
257     int apply(int fd, int val) const {
258       return setsockopt(fd, level, optname, &val, sizeof(val));
259     }
260     int level;
261     int optname;
262   };
263
264   // Maps from a socket option key to its value
265   typedef std::map<OptionKey, int> OptionMap;
266
267   static const OptionMap emptyOptionMap;
268   static const folly::SocketAddress& anyAddress();
269
270   /**
271    * Initiate a connection.
272    *
273    * @param callback  The callback to inform when the connection attempt
274    *                  completes.
275    * @param address   The address to connect to.
276    * @param timeout   A timeout value, in milliseconds.  If the connection
277    *                  does not succeed within this period,
278    *                  callback->connectError() will be invoked.
279    */
280   virtual void connect(
281       ConnectCallback* callback,
282       const folly::SocketAddress& address,
283       int timeout = 0,
284       const OptionMap& options = emptyOptionMap,
285       const folly::SocketAddress& bindAddr = anyAddress()) noexcept;
286
287   void connect(
288       ConnectCallback* callback,
289       const std::string& ip,
290       uint16_t port,
291       int timeout = 0,
292       const OptionMap& options = emptyOptionMap) noexcept;
293
294   /**
295    * If a connect request is in-flight, cancels it and closes the socket
296    * immediately. Otherwise, this is a no-op.
297    *
298    * This does not invoke any connection related callbacks. Call this to
299    * prevent any connect callback while cleaning up, etc.
300    */
301   void cancelConnect();
302
303   /**
304    * Set the send timeout.
305    *
306    * If write requests do not make any progress for more than the specified
307    * number of milliseconds, fail all pending writes and close the socket.
308    *
309    * If write requests are currently pending when setSendTimeout() is called,
310    * the timeout interval is immediately restarted using the new value.
311    *
312    * (See the comments for AsyncSocket for an explanation of why AsyncSocket
313    * provides setSendTimeout() but not setRecvTimeout().)
314    *
315    * @param milliseconds  The timeout duration, in milliseconds.  If 0, no
316    *                      timeout will be used.
317    */
318   void setSendTimeout(uint32_t milliseconds) override;
319
320   /**
321    * Get the send timeout.
322    *
323    * @return Returns the current send timeout, in milliseconds.  A return value
324    *         of 0 indicates that no timeout is set.
325    */
326   uint32_t getSendTimeout() const override {
327     return sendTimeout_;
328   }
329
330   /**
331    * Set the maximum number of reads to execute from the underlying
332    * socket each time the EventBase detects that new ingress data is
333    * available. The default is unlimited, but callers can use this method
334    * to limit the amount of data read from the socket per event loop
335    * iteration.
336    *
337    * @param maxReads  Maximum number of reads per data-available event;
338    *                  a value of zero means unlimited.
339    */
340   void setMaxReadsPerEvent(uint16_t maxReads) {
341     maxReadsPerEvent_ = maxReads;
342   }
343
344   /**
345    * Get the maximum number of reads this object will execute from
346    * the underlying socket each time the EventBase detects that new
347    * ingress data is available.
348    *
349    * @returns Maximum number of reads per data-available event; a value
350    *          of zero means unlimited.
351    */
352   uint16_t getMaxReadsPerEvent() const {
353     return maxReadsPerEvent_;
354   }
355
356   // Read and write methods
357   void setReadCB(ReadCallback* callback) override;
358   ReadCallback* getReadCallback() const override;
359
360   void write(WriteCallback* callback, const void* buf, size_t bytes,
361              WriteFlags flags = WriteFlags::NONE) override;
362   void writev(WriteCallback* callback, const iovec* vec, size_t count,
363               WriteFlags flags = WriteFlags::NONE) override;
364   void writeChain(WriteCallback* callback,
365                   std::unique_ptr<folly::IOBuf>&& buf,
366                   WriteFlags flags = WriteFlags::NONE) override;
367
368   class WriteRequest;
369   virtual void writeRequest(WriteRequest* req);
370   void writeRequestReady() {
371     handleWrite();
372   }
373
374   // Methods inherited from AsyncTransport
375   void close() override;
376   void closeNow() override;
377   void closeWithReset() override;
378   void shutdownWrite() override;
379   void shutdownWriteNow() override;
380
381   bool readable() const override;
382   bool isPending() const override;
383   virtual bool hangup() const;
384   bool good() const override;
385   bool error() const override;
386   void attachEventBase(EventBase* eventBase) override;
387   void detachEventBase() override;
388   bool isDetachable() const override;
389
390   void getLocalAddress(
391     folly::SocketAddress* address) const override;
392   void getPeerAddress(
393     folly::SocketAddress* address) const override;
394
395   bool isEorTrackingEnabled() const override {
396     return trackEor_;
397   }
398
399   void setEorTracking(bool track) override {
400     trackEor_ = track;
401   }
402
403   bool connecting() const override {
404     return (state_ == StateEnum::CONNECTING);
405   }
406
407   virtual bool isClosedByPeer() const {
408     return (state_ == StateEnum::CLOSED &&
409             (readErr_ == READ_EOF || readErr_ == READ_ERROR));
410   }
411
412   virtual bool isClosedBySelf() const {
413     return (state_ == StateEnum::CLOSED &&
414             (readErr_ != READ_EOF && readErr_ != READ_ERROR));
415   }
416
417   size_t getAppBytesWritten() const override {
418     return appBytesWritten_;
419   }
420
421   size_t getRawBytesWritten() const override {
422     return getAppBytesWritten();
423   }
424
425   size_t getAppBytesReceived() const override {
426     return appBytesReceived_;
427   }
428
429   size_t getRawBytesReceived() const override {
430     return getAppBytesReceived();
431   }
432
433   std::chrono::nanoseconds getConnectTime() const {
434     return connectEndTime_ - connectStartTime_;
435   }
436
437   std::chrono::milliseconds getConnectTimeout() const {
438     return connectTimeout_;
439   }
440
441   bool getTFOAttempted() const {
442     return tfoAttempted_;
443   }
444
445   /**
446    * Returns whether or not the attempt to use TFO
447    * finished successfully. This does not necessarily
448    * mean TFO worked, just that trying to use TFO
449    * succeeded.
450    */
451   bool getTFOFinished() const {
452     return tfoFinished_;
453   }
454
455   /**
456    * Returns whether or not TFO attempt succeded on this
457    * connection.
458    * For servers this is pretty straightforward API and can
459    * be invoked right after the connection is accepted. This API
460    * will perform one syscall.
461    * This API is a bit tricky to use for clients, since clients
462    * only know this for sure after the SYN-ACK is returned. So it's
463    * appropriate to call this only after the first application
464    * data is read from the socket when the caller knows that
465    * the SYN has been ACKed by the server.
466    */
467   bool getTFOSucceded() const;
468
469   // Methods controlling socket options
470
471   /**
472    * Force writes to be transmitted immediately.
473    *
474    * This controls the TCP_NODELAY socket option.  When enabled, TCP segments
475    * are sent as soon as possible, even if it is not a full frame of data.
476    * When disabled, the data may be buffered briefly to try and wait for a full
477    * frame of data.
478    *
479    * By default, TCP_NODELAY is enabled for AsyncSocket objects.
480    *
481    * This method will fail if the socket is not currently open.
482    *
483    * @return Returns 0 if the TCP_NODELAY flag was successfully updated,
484    *         or a non-zero errno value on error.
485    */
486   int setNoDelay(bool noDelay);
487
488
489   /**
490    * Set the FD_CLOEXEC flag so that the socket will be closed if the program
491    * later forks and execs.
492    */
493   void setCloseOnExec();
494
495   /*
496    * Set the Flavor of Congestion Control to be used for this Socket
497    * Please check '/lib/modules/<kernel>/kernel/net/ipv4' for tcp_*.ko
498    * first to make sure the module is available for plugging in
499    * Alternatively you can choose from net.ipv4.tcp_allowed_congestion_control
500    */
501   int setCongestionFlavor(const std::string &cname);
502
503   /*
504    * Forces ACKs to be sent immediately
505    *
506    * @return Returns 0 if the TCP_QUICKACK flag was successfully updated,
507    *         or a non-zero errno value on error.
508    */
509   int setQuickAck(bool quickack);
510
511   /**
512    * Set the send bufsize
513    */
514   int setSendBufSize(size_t bufsize);
515
516   /**
517    * Set the recv bufsize
518    */
519   int setRecvBufSize(size_t bufsize);
520
521   /**
522    * Sets a specific tcp personality
523    * Available only on kernels 3.2 and greater
524    */
525   #define SO_SET_NAMESPACE        41
526   int setTCPProfile(int profd);
527
528   /**
529    * Generic API for reading a socket option.
530    *
531    * @param level     same as the "level" parameter in getsockopt().
532    * @param optname   same as the "optname" parameter in getsockopt().
533    * @param optval    pointer to the variable in which the option value should
534    *                  be returned.
535    * @param optlen    value-result argument, initially containing the size of
536    *                  the buffer pointed to by optval, and modified on return
537    *                  to indicate the actual size of the value returned.
538    * @return          same as the return value of getsockopt().
539    */
540   template <typename T>
541   int getSockOpt(int level, int optname, T* optval, socklen_t* optlen) {
542     return getsockopt(fd_, level, optname, (void*) optval, optlen);
543   }
544
545   /**
546    * Generic API for setting a socket option.
547    *
548    * @param level     same as the "level" parameter in getsockopt().
549    * @param optname   same as the "optname" parameter in getsockopt().
550    * @param optval    the option value to set.
551    * @return          same as the return value of setsockopt().
552    */
553   template <typename T>
554   int setSockOpt(int  level,  int  optname,  const T *optval) {
555     return setsockopt(fd_, level, optname, optval, sizeof(T));
556   }
557
558   virtual void setPeek(bool peek) {
559     peek_ = peek;
560   }
561
562   /**
563    * Enables TFO behavior on the AsyncSocket if FOLLY_ALLOW_TFO
564    * is set.
565    */
566   void enableTFO() {
567     // No-op if folly does not allow tfo
568 #if FOLLY_ALLOW_TFO
569     tfoEnabled_ = true;
570 #endif
571   }
572
573   void disableTransparentTls() {
574     noTransparentTls_ = true;
575   }
576
577   enum class StateEnum : uint8_t {
578     UNINIT,
579     CONNECTING,
580     ESTABLISHED,
581     CLOSED,
582     ERROR,
583     FAST_OPEN,
584   };
585
586   void setBufferCallback(BufferCallback* cb);
587
588   // Callers should set this prior to connecting the socket for the safest
589   // behavior.
590   void setEvbChangedCallback(std::unique_ptr<EvbChangeCallback> cb) {
591     evbChangeCb_ = std::move(cb);
592   }
593
594   /**
595    * writeReturn is the total number of bytes written, or WRITE_ERROR on error.
596    * If no data has been written, 0 is returned.
597    * exception is a more specific exception that cause a write error.
598    * Not all writes have exceptions associated with them thus writeReturn
599    * should be checked to determine whether the operation resulted in an error.
600    */
601   struct WriteResult {
602     explicit WriteResult(ssize_t ret) : writeReturn(ret) {}
603
604     WriteResult(ssize_t ret, std::unique_ptr<const AsyncSocketException> e)
605         : writeReturn(ret), exception(std::move(e)) {}
606
607     ssize_t writeReturn;
608     std::unique_ptr<const AsyncSocketException> exception;
609   };
610
611   /**
612    * readReturn is the number of bytes read, or READ_EOF on EOF, or
613    * READ_ERROR on error, or READ_BLOCKING if the operation will
614    * block.
615    * exception is a more specific exception that may have caused a read error.
616    * Not all read errors have exceptions associated with them thus readReturn
617    * should be checked to determine whether the operation resulted in an error.
618    */
619   struct ReadResult {
620     explicit ReadResult(ssize_t ret) : readReturn(ret) {}
621
622     ReadResult(ssize_t ret, std::unique_ptr<const AsyncSocketException> e)
623         : readReturn(ret), exception(std::move(e)) {}
624
625     ssize_t readReturn;
626     std::unique_ptr<const AsyncSocketException> exception;
627   };
628
629   /**
630    * A WriteRequest object tracks information about a pending write operation.
631    */
632   class WriteRequest {
633    public:
634     WriteRequest(AsyncSocket* socket, WriteCallback* callback) :
635       socket_(socket), callback_(callback) {}
636
637     virtual void start() {}
638
639     virtual void destroy() = 0;
640
641     virtual WriteResult performWrite() = 0;
642
643     virtual void consume() = 0;
644
645     virtual bool isComplete() = 0;
646
647     WriteRequest* getNext() const {
648       return next_;
649     }
650
651     WriteCallback* getCallback() const {
652       return callback_;
653     }
654
655     uint32_t getTotalBytesWritten() const {
656       return totalBytesWritten_;
657     }
658
659     void append(WriteRequest* next) {
660       assert(next_ == nullptr);
661       next_ = next;
662     }
663
664     void fail(const char* fn, const AsyncSocketException& ex) {
665       socket_->failWrite(fn, ex);
666     }
667
668     void bytesWritten(size_t count) {
669       totalBytesWritten_ += uint32_t(count);
670       socket_->appBytesWritten_ += count;
671     }
672
673    protected:
674     // protected destructor, to ensure callers use destroy()
675     virtual ~WriteRequest() {}
676
677     AsyncSocket* socket_;         ///< parent socket
678     WriteRequest* next_{nullptr};          ///< pointer to next WriteRequest
679     WriteCallback* callback_;     ///< completion callback
680     uint32_t totalBytesWritten_{0};  ///< total bytes written
681   };
682
683  protected:
684   enum ReadResultEnum {
685     READ_EOF = 0,
686     READ_ERROR = -1,
687     READ_BLOCKING = -2,
688     READ_NO_ERROR = -3,
689   };
690
691   enum WriteResultEnum {
692     WRITE_ERROR = -1,
693   };
694
695   /**
696    * Protected destructor.
697    *
698    * Users of AsyncSocket must never delete it directly.  Instead, invoke
699    * destroy() instead.  (See the documentation in DelayedDestruction.h for
700    * more details.)
701    */
702   ~AsyncSocket();
703
704   friend std::ostream& operator << (std::ostream& os, const StateEnum& state);
705
706   enum ShutdownFlags {
707     /// shutdownWrite() called, but we are still waiting on writes to drain
708     SHUT_WRITE_PENDING = 0x01,
709     /// writes have been completely shut down
710     SHUT_WRITE = 0x02,
711     /**
712      * Reads have been shutdown.
713      *
714      * At the moment we don't distinguish between remote read shutdown
715      * (received EOF from the remote end) and local read shutdown.  We can
716      * only receive EOF when a read callback is set, and we immediately inform
717      * it of the EOF.  Therefore there doesn't seem to be any reason to have a
718      * separate state of "received EOF but the local side may still want to
719      * read".
720      *
721      * We also don't currently provide any API for only shutting down the read
722      * side of a socket.  (This is a no-op as far as TCP is concerned, anyway.)
723      */
724     SHUT_READ = 0x04,
725   };
726
727   class BytesWriteRequest;
728
729   class WriteTimeout : public AsyncTimeout {
730    public:
731     WriteTimeout(AsyncSocket* socket, EventBase* eventBase)
732       : AsyncTimeout(eventBase)
733       , socket_(socket) {}
734
735     virtual void timeoutExpired() noexcept {
736       socket_->timeoutExpired();
737     }
738
739    private:
740     AsyncSocket* socket_;
741   };
742
743   class IoHandler : public EventHandler {
744    public:
745     IoHandler(AsyncSocket* socket, EventBase* eventBase)
746       : EventHandler(eventBase, -1)
747       , socket_(socket) {}
748     IoHandler(AsyncSocket* socket, EventBase* eventBase, int fd)
749       : EventHandler(eventBase, fd)
750       , socket_(socket) {}
751
752     virtual void handlerReady(uint16_t events) noexcept {
753       socket_->ioReady(events);
754     }
755
756    private:
757     AsyncSocket* socket_;
758   };
759
760   void init();
761
762   class ImmediateReadCB : public folly::EventBase::LoopCallback {
763    public:
764     explicit ImmediateReadCB(AsyncSocket* socket) : socket_(socket) {}
765     void runLoopCallback() noexcept override {
766       DestructorGuard dg(socket_);
767       socket_->checkForImmediateRead();
768     }
769    private:
770     AsyncSocket* socket_;
771   };
772
773   /**
774    * Schedule checkForImmediateRead to be executed in the next loop
775    * iteration.
776    */
777   void scheduleImmediateRead() noexcept {
778     if (good()) {
779       eventBase_->runInLoop(&immediateReadHandler_);
780     }
781   }
782
783   /**
784    * Schedule handleInitalReadWrite to run in the next iteration.
785    */
786   void scheduleInitialReadWrite() noexcept {
787     if (good()) {
788       DestructorGuard dg(this);
789       eventBase_->runInLoop([this, dg] {
790         if (good()) {
791           handleInitialReadWrite();
792         }
793       });
794     }
795   }
796
797   // event notification methods
798   void ioReady(uint16_t events) noexcept;
799   virtual void checkForImmediateRead() noexcept;
800   virtual void handleInitialReadWrite() noexcept;
801   virtual void prepareReadBuffer(void** buf, size_t* buflen);
802   virtual void handleRead() noexcept;
803   virtual void handleWrite() noexcept;
804   virtual void handleConnect() noexcept;
805   void timeoutExpired() noexcept;
806
807   /**
808    * Attempt to read from the socket.
809    *
810    * @param buf      The buffer to read data into.
811    * @param buflen   The length of the buffer.
812    *
813    * @return Returns a read result. See read result for details.
814    */
815   virtual ReadResult performRead(void** buf, size_t* buflen, size_t* offset);
816
817   /**
818    * Populate an iovec array from an IOBuf and attempt to write it.
819    *
820    * @param callback Write completion/error callback.
821    * @param vec      Target iovec array; caller retains ownership.
822    * @param count    Number of IOBufs to write, beginning at start of buf.
823    * @param buf      Chain of iovecs.
824    * @param flags    set of flags for the underlying write calls, like cork
825    */
826   void writeChainImpl(WriteCallback* callback, iovec* vec,
827                       size_t count, std::unique_ptr<folly::IOBuf>&& buf,
828                       WriteFlags flags);
829
830   /**
831    * Write as much data as possible to the socket without blocking,
832    * and queue up any leftover data to send when the socket can
833    * handle writes again.
834    *
835    * @param callback The callback to invoke when the write is completed.
836    * @param vec      Array of buffers to write; this method will make a
837    *                 copy of the vector (but not the buffers themselves)
838    *                 if the write has to be completed asynchronously.
839    * @param count    Number of elements in vec.
840    * @param buf      The IOBuf that manages the buffers referenced by
841    *                 vec, or a pointer to nullptr if the buffers are not
842    *                 associated with an IOBuf.  Note that ownership of
843    *                 the IOBuf is transferred here; upon completion of
844    *                 the write, the AsyncSocket deletes the IOBuf.
845    * @param flags    Set of write flags.
846    */
847   void writeImpl(WriteCallback* callback, const iovec* vec, size_t count,
848                  std::unique_ptr<folly::IOBuf>&& buf,
849                  WriteFlags flags = WriteFlags::NONE);
850
851   /**
852    * Attempt to write to the socket.
853    *
854    * @param vec             The iovec array pointing to the buffers to write.
855    * @param count           The length of the iovec array.
856    * @param flags           Set of write flags.
857    * @param countWritten    On return, the value pointed to by this parameter
858    *                          will contain the number of iovec entries that were
859    *                          fully written.
860    * @param partialWritten  On return, the value pointed to by this parameter
861    *                          will contain the number of bytes written in the
862    *                          partially written iovec entry.
863    *
864    * @return Returns a WriteResult. See WriteResult for more details.
865    */
866   virtual WriteResult performWrite(
867       const iovec* vec,
868       uint32_t count,
869       WriteFlags flags,
870       uint32_t* countWritten,
871       uint32_t* partialWritten);
872
873   /**
874    * Sends the message over the socket using sendmsg
875    *
876    * @param msg       Message to send
877    * @param msg_flags Flags to pass to sendmsg
878    */
879   AsyncSocket::WriteResult
880   sendSocketMessage(int fd, struct msghdr* msg, int msg_flags);
881
882   virtual ssize_t tfoSendMsg(int fd, struct msghdr* msg, int msg_flags);
883
884   int socketConnect(const struct sockaddr* addr, socklen_t len);
885
886   virtual void scheduleConnectTimeout();
887   void registerForConnectEvents();
888
889   bool updateEventRegistration();
890
891   /**
892    * Update event registration.
893    *
894    * @param enable Flags of events to enable. Set it to 0 if no events
895    * need to be enabled in this call.
896    * @param disable Flags of events
897    * to disable. Set it to 0 if no events need to be disabled in this
898    * call.
899    *
900    * @return true iff the update is successful.
901    */
902   bool updateEventRegistration(uint16_t enable, uint16_t disable);
903
904   // Actually close the file descriptor and set it to -1 so we don't
905   // accidentally close it again.
906   void doClose();
907
908   // error handling methods
909   void startFail();
910   void finishFail();
911   void finishFail(const AsyncSocketException& ex);
912   void invokeAllErrors(const AsyncSocketException& ex);
913   void fail(const char* fn, const AsyncSocketException& ex);
914   void failConnect(const char* fn, const AsyncSocketException& ex);
915   void failRead(const char* fn, const AsyncSocketException& ex);
916   void failWrite(const char* fn, WriteCallback* callback, size_t bytesWritten,
917                  const AsyncSocketException& ex);
918   void failWrite(const char* fn, const AsyncSocketException& ex);
919   void failAllWrites(const AsyncSocketException& ex);
920   virtual void invokeConnectErr(const AsyncSocketException& ex);
921   virtual void invokeConnectSuccess();
922   void invalidState(ConnectCallback* callback);
923   void invalidState(ReadCallback* callback);
924   void invalidState(WriteCallback* callback);
925
926   std::string withAddr(const std::string& s);
927
928   StateEnum state_;                     ///< StateEnum describing current state
929   uint8_t shutdownFlags_;               ///< Shutdown state (ShutdownFlags)
930   uint16_t eventFlags_;                 ///< EventBase::HandlerFlags settings
931   int fd_;                              ///< The socket file descriptor
932   mutable folly::SocketAddress addr_;    ///< The address we tried to connect to
933   mutable folly::SocketAddress localAddr_;
934                                         ///< The address we are connecting from
935   uint32_t sendTimeout_;                ///< The send timeout, in milliseconds
936   uint16_t maxReadsPerEvent_;           ///< Max reads per event loop iteration
937   EventBase* eventBase_;                ///< The EventBase
938   WriteTimeout writeTimeout_;           ///< A timeout for connect and write
939   IoHandler ioHandler_;                 ///< A EventHandler to monitor the fd
940   ImmediateReadCB immediateReadHandler_; ///< LoopCallback for checking read
941
942   ConnectCallback* connectCallback_;    ///< ConnectCallback
943   ReadCallback* readCallback_;          ///< ReadCallback
944   WriteRequest* writeReqHead_;          ///< Chain of WriteRequests
945   WriteRequest* writeReqTail_;          ///< End of WriteRequest chain
946   ShutdownSocketSet* shutdownSocketSet_;
947   size_t appBytesReceived_;             ///< Num of bytes received from socket
948   size_t appBytesWritten_;              ///< Num of bytes written to socket
949   bool isBufferMovable_{false};
950
951   bool peek_{false}; // Peek bytes.
952
953   int8_t readErr_{READ_NO_ERROR};      ///< The read error encountered, if any.
954
955   std::chrono::steady_clock::time_point connectStartTime_;
956   std::chrono::steady_clock::time_point connectEndTime_;
957
958   std::chrono::milliseconds connectTimeout_{0};
959
960   BufferCallback* bufferCallback_{nullptr};
961   bool tfoEnabled_{false};
962   bool tfoAttempted_{false};
963   bool tfoFinished_{false};
964   bool noTransparentTls_{false};
965   // Whether to track EOR or not.
966   bool trackEor_{false};
967
968   std::unique_ptr<EvbChangeCallback> evbChangeCb_{nullptr};
969 };
970 #ifdef _MSC_VER
971 #pragma vtordisp(pop)
972 #endif
973
974 } // folly