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