Modernise and clang-format existing formatting benchmark
[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 { return false; }
396
397   void setEorTracking(bool /*track*/) override {}
398
399   bool connecting() const override {
400     return (state_ == StateEnum::CONNECTING);
401   }
402
403   virtual bool isClosedByPeer() const {
404     return (state_ == StateEnum::CLOSED &&
405             (readErr_ == READ_EOF || readErr_ == READ_ERROR));
406   }
407
408   virtual bool isClosedBySelf() const {
409     return (state_ == StateEnum::CLOSED &&
410             (readErr_ != READ_EOF && readErr_ != READ_ERROR));
411   }
412
413   size_t getAppBytesWritten() const override {
414     return appBytesWritten_;
415   }
416
417   size_t getRawBytesWritten() const override {
418     return getAppBytesWritten();
419   }
420
421   size_t getAppBytesReceived() const override {
422     return appBytesReceived_;
423   }
424
425   size_t getRawBytesReceived() const override {
426     return getAppBytesReceived();
427   }
428
429   std::chrono::nanoseconds getConnectTime() const {
430     return connectEndTime_ - connectStartTime_;
431   }
432
433   std::chrono::milliseconds getConnectTimeout() const {
434     return connectTimeout_;
435   }
436
437   bool getTFOAttempted() const {
438     return tfoAttempted_;
439   }
440
441   /**
442    * Returns whether or not the attempt to use TFO
443    * finished successfully. This does not necessarily
444    * mean TFO worked, just that trying to use TFO
445    * succeeded.
446    */
447   bool getTFOFinished() const {
448     return tfoFinished_;
449   }
450
451   /**
452    * Returns whether or not TFO attempt succeded on this
453    * connection.
454    * For servers this is pretty straightforward API and can
455    * be invoked right after the connection is accepted. This API
456    * will perform one syscall.
457    * This API is a bit tricky to use for clients, since clients
458    * only know this for sure after the SYN-ACK is returned. So it's
459    * appropriate to call this only after the first application
460    * data is read from the socket when the caller knows that
461    * the SYN has been ACKed by the server.
462    */
463   bool getTFOSucceded() const;
464
465   // Methods controlling socket options
466
467   /**
468    * Force writes to be transmitted immediately.
469    *
470    * This controls the TCP_NODELAY socket option.  When enabled, TCP segments
471    * are sent as soon as possible, even if it is not a full frame of data.
472    * When disabled, the data may be buffered briefly to try and wait for a full
473    * frame of data.
474    *
475    * By default, TCP_NODELAY is enabled for AsyncSocket objects.
476    *
477    * This method will fail if the socket is not currently open.
478    *
479    * @return Returns 0 if the TCP_NODELAY flag was successfully updated,
480    *         or a non-zero errno value on error.
481    */
482   int setNoDelay(bool noDelay);
483
484
485   /**
486    * Set the FD_CLOEXEC flag so that the socket will be closed if the program
487    * later forks and execs.
488    */
489   void setCloseOnExec();
490
491   /*
492    * Set the Flavor of Congestion Control to be used for this Socket
493    * Please check '/lib/modules/<kernel>/kernel/net/ipv4' for tcp_*.ko
494    * first to make sure the module is available for plugging in
495    * Alternatively you can choose from net.ipv4.tcp_allowed_congestion_control
496    */
497   int setCongestionFlavor(const std::string &cname);
498
499   /*
500    * Forces ACKs to be sent immediately
501    *
502    * @return Returns 0 if the TCP_QUICKACK flag was successfully updated,
503    *         or a non-zero errno value on error.
504    */
505   int setQuickAck(bool quickack);
506
507   /**
508    * Set the send bufsize
509    */
510   int setSendBufSize(size_t bufsize);
511
512   /**
513    * Set the recv bufsize
514    */
515   int setRecvBufSize(size_t bufsize);
516
517   /**
518    * Sets a specific tcp personality
519    * Available only on kernels 3.2 and greater
520    */
521   #define SO_SET_NAMESPACE        41
522   int setTCPProfile(int profd);
523
524   /**
525    * Generic API for reading a socket option.
526    *
527    * @param level     same as the "level" parameter in getsockopt().
528    * @param optname   same as the "optname" parameter in getsockopt().
529    * @param optval    pointer to the variable in which the option value should
530    *                  be returned.
531    * @param optlen    value-result argument, initially containing the size of
532    *                  the buffer pointed to by optval, and modified on return
533    *                  to indicate the actual size of the value returned.
534    * @return          same as the return value of getsockopt().
535    */
536   template <typename T>
537   int getSockOpt(int level, int optname, T* optval, socklen_t* optlen) {
538     return getsockopt(fd_, level, optname, (void*) optval, optlen);
539   }
540
541   /**
542    * Generic API for setting a socket option.
543    *
544    * @param level     same as the "level" parameter in getsockopt().
545    * @param optname   same as the "optname" parameter in getsockopt().
546    * @param optval    the option value to set.
547    * @return          same as the return value of setsockopt().
548    */
549   template <typename T>
550   int setSockOpt(int  level,  int  optname,  const T *optval) {
551     return setsockopt(fd_, level, optname, optval, sizeof(T));
552   }
553
554   virtual void setPeek(bool peek) {
555     peek_ = peek;
556   }
557
558   /**
559    * Enables TFO behavior on the AsyncSocket if FOLLY_ALLOW_TFO
560    * is set.
561    */
562   void enableTFO() {
563     // No-op if folly does not allow tfo
564 #if FOLLY_ALLOW_TFO
565     tfoEnabled_ = true;
566 #endif
567   }
568
569   void disableTransparentTls() {
570     noTransparentTls_ = true;
571   }
572
573   enum class StateEnum : uint8_t {
574     UNINIT,
575     CONNECTING,
576     ESTABLISHED,
577     CLOSED,
578     ERROR,
579     FAST_OPEN,
580   };
581
582   void setBufferCallback(BufferCallback* cb);
583
584   // Callers should set this prior to connecting the socket for the safest
585   // behavior.
586   void setEvbChangedCallback(std::unique_ptr<EvbChangeCallback> cb) {
587     evbChangeCb_ = std::move(cb);
588   }
589
590   /**
591    * writeReturn is the total number of bytes written, or WRITE_ERROR on error.
592    * If no data has been written, 0 is returned.
593    * exception is a more specific exception that cause a write error.
594    * Not all writes have exceptions associated with them thus writeReturn
595    * should be checked to determine whether the operation resulted in an error.
596    */
597   struct WriteResult {
598     explicit WriteResult(ssize_t ret) : writeReturn(ret) {}
599
600     WriteResult(ssize_t ret, std::unique_ptr<const AsyncSocketException> e)
601         : writeReturn(ret), exception(std::move(e)) {}
602
603     ssize_t writeReturn;
604     std::unique_ptr<const AsyncSocketException> exception;
605   };
606
607   /**
608    * readReturn is the number of bytes read, or READ_EOF on EOF, or
609    * READ_ERROR on error, or READ_BLOCKING if the operation will
610    * block.
611    * exception is a more specific exception that may have caused a read error.
612    * Not all read errors have exceptions associated with them thus readReturn
613    * should be checked to determine whether the operation resulted in an error.
614    */
615   struct ReadResult {
616     explicit ReadResult(ssize_t ret) : readReturn(ret) {}
617
618     ReadResult(ssize_t ret, std::unique_ptr<const AsyncSocketException> e)
619         : readReturn(ret), exception(std::move(e)) {}
620
621     ssize_t readReturn;
622     std::unique_ptr<const AsyncSocketException> exception;
623   };
624
625   /**
626    * A WriteRequest object tracks information about a pending write operation.
627    */
628   class WriteRequest {
629    public:
630     WriteRequest(AsyncSocket* socket, WriteCallback* callback) :
631       socket_(socket), callback_(callback) {}
632
633     virtual void start() {}
634
635     virtual void destroy() = 0;
636
637     virtual WriteResult performWrite() = 0;
638
639     virtual void consume() = 0;
640
641     virtual bool isComplete() = 0;
642
643     WriteRequest* getNext() const {
644       return next_;
645     }
646
647     WriteCallback* getCallback() const {
648       return callback_;
649     }
650
651     uint32_t getTotalBytesWritten() const {
652       return totalBytesWritten_;
653     }
654
655     void append(WriteRequest* next) {
656       assert(next_ == nullptr);
657       next_ = next;
658     }
659
660     void fail(const char* fn, const AsyncSocketException& ex) {
661       socket_->failWrite(fn, ex);
662     }
663
664     void bytesWritten(size_t count) {
665       totalBytesWritten_ += uint32_t(count);
666       socket_->appBytesWritten_ += count;
667     }
668
669    protected:
670     // protected destructor, to ensure callers use destroy()
671     virtual ~WriteRequest() {}
672
673     AsyncSocket* socket_;         ///< parent socket
674     WriteRequest* next_{nullptr};          ///< pointer to next WriteRequest
675     WriteCallback* callback_;     ///< completion callback
676     uint32_t totalBytesWritten_{0};  ///< total bytes written
677   };
678
679  protected:
680   enum ReadResultEnum {
681     READ_EOF = 0,
682     READ_ERROR = -1,
683     READ_BLOCKING = -2,
684     READ_NO_ERROR = -3,
685   };
686
687   enum WriteResultEnum {
688     WRITE_ERROR = -1,
689   };
690
691   /**
692    * Protected destructor.
693    *
694    * Users of AsyncSocket must never delete it directly.  Instead, invoke
695    * destroy() instead.  (See the documentation in DelayedDestruction.h for
696    * more details.)
697    */
698   ~AsyncSocket();
699
700   friend std::ostream& operator << (std::ostream& os, const StateEnum& state);
701
702   enum ShutdownFlags {
703     /// shutdownWrite() called, but we are still waiting on writes to drain
704     SHUT_WRITE_PENDING = 0x01,
705     /// writes have been completely shut down
706     SHUT_WRITE = 0x02,
707     /**
708      * Reads have been shutdown.
709      *
710      * At the moment we don't distinguish between remote read shutdown
711      * (received EOF from the remote end) and local read shutdown.  We can
712      * only receive EOF when a read callback is set, and we immediately inform
713      * it of the EOF.  Therefore there doesn't seem to be any reason to have a
714      * separate state of "received EOF but the local side may still want to
715      * read".
716      *
717      * We also don't currently provide any API for only shutting down the read
718      * side of a socket.  (This is a no-op as far as TCP is concerned, anyway.)
719      */
720     SHUT_READ = 0x04,
721   };
722
723   class BytesWriteRequest;
724
725   class WriteTimeout : public AsyncTimeout {
726    public:
727     WriteTimeout(AsyncSocket* socket, EventBase* eventBase)
728       : AsyncTimeout(eventBase)
729       , socket_(socket) {}
730
731     virtual void timeoutExpired() noexcept {
732       socket_->timeoutExpired();
733     }
734
735    private:
736     AsyncSocket* socket_;
737   };
738
739   class IoHandler : public EventHandler {
740    public:
741     IoHandler(AsyncSocket* socket, EventBase* eventBase)
742       : EventHandler(eventBase, -1)
743       , socket_(socket) {}
744     IoHandler(AsyncSocket* socket, EventBase* eventBase, int fd)
745       : EventHandler(eventBase, fd)
746       , socket_(socket) {}
747
748     virtual void handlerReady(uint16_t events) noexcept {
749       socket_->ioReady(events);
750     }
751
752    private:
753     AsyncSocket* socket_;
754   };
755
756   void init();
757
758   class ImmediateReadCB : public folly::EventBase::LoopCallback {
759    public:
760     explicit ImmediateReadCB(AsyncSocket* socket) : socket_(socket) {}
761     void runLoopCallback() noexcept override {
762       DestructorGuard dg(socket_);
763       socket_->checkForImmediateRead();
764     }
765    private:
766     AsyncSocket* socket_;
767   };
768
769   /**
770    * Schedule checkForImmediateRead to be executed in the next loop
771    * iteration.
772    */
773   void scheduleImmediateRead() noexcept {
774     if (good()) {
775       eventBase_->runInLoop(&immediateReadHandler_);
776     }
777   }
778
779   /**
780    * Schedule handleInitalReadWrite to run in the next iteration.
781    */
782   void scheduleInitialReadWrite() noexcept {
783     if (good()) {
784       DestructorGuard dg(this);
785       eventBase_->runInLoop([this, dg] {
786         if (good()) {
787           handleInitialReadWrite();
788         }
789       });
790     }
791   }
792
793   // event notification methods
794   void ioReady(uint16_t events) noexcept;
795   virtual void checkForImmediateRead() noexcept;
796   virtual void handleInitialReadWrite() noexcept;
797   virtual void prepareReadBuffer(void** buf, size_t* buflen);
798   virtual void handleRead() noexcept;
799   virtual void handleWrite() noexcept;
800   virtual void handleConnect() noexcept;
801   void timeoutExpired() noexcept;
802
803   /**
804    * Attempt to read from the socket.
805    *
806    * @param buf      The buffer to read data into.
807    * @param buflen   The length of the buffer.
808    *
809    * @return Returns a read result. See read result for details.
810    */
811   virtual ReadResult performRead(void** buf, size_t* buflen, size_t* offset);
812
813   /**
814    * Populate an iovec array from an IOBuf and attempt to write it.
815    *
816    * @param callback Write completion/error callback.
817    * @param vec      Target iovec array; caller retains ownership.
818    * @param count    Number of IOBufs to write, beginning at start of buf.
819    * @param buf      Chain of iovecs.
820    * @param flags    set of flags for the underlying write calls, like cork
821    */
822   void writeChainImpl(WriteCallback* callback, iovec* vec,
823                       size_t count, std::unique_ptr<folly::IOBuf>&& buf,
824                       WriteFlags flags);
825
826   /**
827    * Write as much data as possible to the socket without blocking,
828    * and queue up any leftover data to send when the socket can
829    * handle writes again.
830    *
831    * @param callback The callback to invoke when the write is completed.
832    * @param vec      Array of buffers to write; this method will make a
833    *                 copy of the vector (but not the buffers themselves)
834    *                 if the write has to be completed asynchronously.
835    * @param count    Number of elements in vec.
836    * @param buf      The IOBuf that manages the buffers referenced by
837    *                 vec, or a pointer to nullptr if the buffers are not
838    *                 associated with an IOBuf.  Note that ownership of
839    *                 the IOBuf is transferred here; upon completion of
840    *                 the write, the AsyncSocket deletes the IOBuf.
841    * @param flags    Set of write flags.
842    */
843   void writeImpl(WriteCallback* callback, const iovec* vec, size_t count,
844                  std::unique_ptr<folly::IOBuf>&& buf,
845                  WriteFlags flags = WriteFlags::NONE);
846
847   /**
848    * Attempt to write to the socket.
849    *
850    * @param vec             The iovec array pointing to the buffers to write.
851    * @param count           The length of the iovec array.
852    * @param flags           Set of write flags.
853    * @param countWritten    On return, the value pointed to by this parameter
854    *                          will contain the number of iovec entries that were
855    *                          fully written.
856    * @param partialWritten  On return, the value pointed to by this parameter
857    *                          will contain the number of bytes written in the
858    *                          partially written iovec entry.
859    *
860    * @return Returns a WriteResult. See WriteResult for more details.
861    */
862   virtual WriteResult performWrite(
863       const iovec* vec,
864       uint32_t count,
865       WriteFlags flags,
866       uint32_t* countWritten,
867       uint32_t* partialWritten);
868
869   /**
870    * Sends the message over the socket using sendmsg
871    *
872    * @param msg       Message to send
873    * @param msg_flags Flags to pass to sendmsg
874    */
875   AsyncSocket::WriteResult
876   sendSocketMessage(int fd, struct msghdr* msg, int msg_flags);
877
878   virtual ssize_t tfoSendMsg(int fd, struct msghdr* msg, int msg_flags);
879
880   int socketConnect(const struct sockaddr* addr, socklen_t len);
881
882   virtual void scheduleConnectTimeout();
883   void registerForConnectEvents();
884
885   bool updateEventRegistration();
886
887   /**
888    * Update event registration.
889    *
890    * @param enable Flags of events to enable. Set it to 0 if no events
891    * need to be enabled in this call.
892    * @param disable Flags of events
893    * to disable. Set it to 0 if no events need to be disabled in this
894    * call.
895    *
896    * @return true iff the update is successful.
897    */
898   bool updateEventRegistration(uint16_t enable, uint16_t disable);
899
900   // Actually close the file descriptor and set it to -1 so we don't
901   // accidentally close it again.
902   void doClose();
903
904   // error handling methods
905   void startFail();
906   void finishFail();
907   void finishFail(const AsyncSocketException& ex);
908   void invokeAllErrors(const AsyncSocketException& ex);
909   void fail(const char* fn, const AsyncSocketException& ex);
910   void failConnect(const char* fn, const AsyncSocketException& ex);
911   void failRead(const char* fn, const AsyncSocketException& ex);
912   void failWrite(const char* fn, WriteCallback* callback, size_t bytesWritten,
913                  const AsyncSocketException& ex);
914   void failWrite(const char* fn, const AsyncSocketException& ex);
915   void failAllWrites(const AsyncSocketException& ex);
916   virtual void invokeConnectErr(const AsyncSocketException& ex);
917   virtual void invokeConnectSuccess();
918   void invalidState(ConnectCallback* callback);
919   void invalidState(ReadCallback* callback);
920   void invalidState(WriteCallback* callback);
921
922   std::string withAddr(const std::string& s);
923
924   StateEnum state_;                     ///< StateEnum describing current state
925   uint8_t shutdownFlags_;               ///< Shutdown state (ShutdownFlags)
926   uint16_t eventFlags_;                 ///< EventBase::HandlerFlags settings
927   int fd_;                              ///< The socket file descriptor
928   mutable folly::SocketAddress addr_;    ///< The address we tried to connect to
929   mutable folly::SocketAddress localAddr_;
930                                         ///< The address we are connecting from
931   uint32_t sendTimeout_;                ///< The send timeout, in milliseconds
932   uint16_t maxReadsPerEvent_;           ///< Max reads per event loop iteration
933   EventBase* eventBase_;                ///< The EventBase
934   WriteTimeout writeTimeout_;           ///< A timeout for connect and write
935   IoHandler ioHandler_;                 ///< A EventHandler to monitor the fd
936   ImmediateReadCB immediateReadHandler_; ///< LoopCallback for checking read
937
938   ConnectCallback* connectCallback_;    ///< ConnectCallback
939   ReadCallback* readCallback_;          ///< ReadCallback
940   WriteRequest* writeReqHead_;          ///< Chain of WriteRequests
941   WriteRequest* writeReqTail_;          ///< End of WriteRequest chain
942   ShutdownSocketSet* shutdownSocketSet_;
943   size_t appBytesReceived_;             ///< Num of bytes received from socket
944   size_t appBytesWritten_;              ///< Num of bytes written to socket
945   bool isBufferMovable_{false};
946
947   bool peek_{false}; // Peek bytes.
948
949   int8_t readErr_{READ_NO_ERROR};      ///< The read error encountered, if any.
950
951   std::chrono::steady_clock::time_point connectStartTime_;
952   std::chrono::steady_clock::time_point connectEndTime_;
953
954   std::chrono::milliseconds connectTimeout_{0};
955
956   BufferCallback* bufferCallback_{nullptr};
957   bool tfoEnabled_{false};
958   bool tfoAttempted_{false};
959   bool tfoFinished_{false};
960   bool noTransparentTls_{false};
961
962   std::unique_ptr<EvbChangeCallback> evbChangeCb_{nullptr};
963 };
964 #ifdef _MSC_VER
965 #pragma vtordisp(pop)
966 #endif
967
968 } // folly