77bd2b0c4db6e50c1333517c35243d7ac9ac1b07
[folly.git] / folly / io / async / AsyncSocket.h
1 /*
2  * Copyright 2014 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 <glog/logging.h>
22 #include <folly/SocketAddress.h>
23 #include <folly/io/ShutdownSocketSet.h>
24 #include <folly/io/IOBuf.h>
25 #include <folly/io/async/AsyncTimeout.h>
26 #include <folly/io/async/AsyncSocketException.h>
27 #include <folly/io/async/AsyncTransport.h>
28 #include <folly/io/async/EventHandler.h>
29 #include <folly/io/async/DelayedDestruction.h>
30
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 class AsyncSocket : virtual public AsyncTransport {
65  public:
66   typedef std::unique_ptr<AsyncSocket, Destructor> UniquePtr;
67
68   class ConnectCallback {
69    public:
70     virtual ~ConnectCallback() {}
71
72     /**
73      * connectSuccess() will be invoked when the connection has been
74      * successfully established.
75      */
76     virtual void connectSuccess() noexcept = 0;
77
78     /**
79      * connectErr() will be invoked if the connection attempt fails.
80      *
81      * @param ex        An exception describing the error that occurred.
82      */
83     virtual void connectErr(const AsyncSocketException& ex)
84       noexcept = 0;
85   };
86
87   class ReadCallback {
88    public:
89     virtual ~ReadCallback() {}
90
91     /**
92      * When data becomes available, getReadBuffer() will be invoked to get the
93      * buffer into which data should be read.
94      *
95      * This method allows the ReadCallback to delay buffer allocation until
96      * data becomes available.  This allows applications to manage large
97      * numbers of idle connections, without having to maintain a separate read
98      * buffer for each idle connection.
99      *
100      * It is possible that in some cases, getReadBuffer() may be called
101      * multiple times before readDataAvailable() is invoked.  In this case, the
102      * data will be written to the buffer returned from the most recent call to
103      * readDataAvailable().  If the previous calls to readDataAvailable()
104      * returned different buffers, the ReadCallback is responsible for ensuring
105      * that they are not leaked.
106      *
107      * If getReadBuffer() throws an exception, returns a nullptr buffer, or
108      * returns a 0 length, the ReadCallback will be uninstalled and its
109      * readError() method will be invoked.
110      *
111      * getReadBuffer() is not allowed to change the transport state before it
112      * returns.  (For example, it should never uninstall the read callback, or
113      * set a different read callback.)
114      *
115      * @param bufReturn getReadBuffer() should update *bufReturn to contain the
116      *                  address of the read buffer.  This parameter will never
117      *                  be nullptr.
118      * @param lenReturn getReadBuffer() should update *lenReturn to contain the
119      *                  maximum number of bytes that may be written to the read
120      *                  buffer.  This parameter will never be nullptr.
121      */
122     virtual void getReadBuffer(void** bufReturn, size_t* lenReturn) = 0;
123
124     /**
125      * readDataAvailable() will be invoked when data has been successfully read
126      * into the buffer returned by the last call to getReadBuffer().
127      *
128      * The read callback remains installed after readDataAvailable() returns.
129      * It must be explicitly uninstalled to stop receiving read events.
130      * getReadBuffer() will be called at least once before each call to
131      * readDataAvailable().  getReadBuffer() will also be called before any
132      * call to readEOF().
133      *
134      * @param len       The number of bytes placed in the buffer.
135      */
136     virtual void readDataAvailable(size_t len) noexcept = 0;
137
138     /**
139      * readEOF() will be invoked when the transport is closed.
140      *
141      * The read callback will be automatically uninstalled immediately before
142      * readEOF() is invoked.
143      */
144     virtual void readEOF() noexcept = 0;
145
146     /**
147      * readError() will be invoked if an error occurs reading from the
148      * transport.
149      *
150      * The read callback will be automatically uninstalled immediately before
151      * readError() is invoked.
152      *
153      * @param ex        An exception describing the error that occurred.
154      */
155     virtual void readErr(const AsyncSocketException& ex)
156       noexcept = 0;
157   };
158
159   class WriteCallback {
160    public:
161     virtual ~WriteCallback() {}
162
163     /**
164      * writeSuccess() will be invoked when all of the data has been
165      * successfully written.
166      *
167      * Note that this mainly signals that the buffer containing the data to
168      * write is no longer needed and may be freed or re-used.  It does not
169      * guarantee that the data has been fully transmitted to the remote
170      * endpoint.  For example, on socket-based transports, writeSuccess() only
171      * indicates that the data has been given to the kernel for eventual
172      * transmission.
173      */
174     virtual void writeSuccess() noexcept = 0;
175
176     /**
177      * writeError() will be invoked if an error occurs writing the data.
178      *
179      * @param bytesWritten      The number of bytes that were successfull
180      * @param ex                An exception describing the error that occurred.
181      */
182     virtual void writeErr(size_t bytesWritten,
183                             const AsyncSocketException& ex)
184       noexcept = 0;
185   };
186
187   /**
188    * Create a new unconnected AsyncSocket.
189    *
190    * connect() must later be called on this socket to establish a connection.
191    */
192   explicit AsyncSocket(EventBase* evb);
193
194   void setShutdownSocketSet(ShutdownSocketSet* ss);
195
196   /**
197    * Create a new AsyncSocket and begin the connection process.
198    *
199    * @param evb             EventBase that will manage this socket.
200    * @param address         The address to connect to.
201    * @param connectTimeout  Optional timeout in milliseconds for the connection
202    *                        attempt.
203    */
204   AsyncSocket(EventBase* evb,
205                const folly::SocketAddress& address,
206                uint32_t connectTimeout = 0);
207
208   /**
209    * Create a new AsyncSocket and begin the connection process.
210    *
211    * @param evb             EventBase that will manage this socket.
212    * @param ip              IP address to connect to (dotted-quad).
213    * @param port            Destination port in host byte order.
214    * @param connectTimeout  Optional timeout in milliseconds for the connection
215    *                        attempt.
216    */
217   AsyncSocket(EventBase* evb,
218                const std::string& ip,
219                uint16_t port,
220                uint32_t connectTimeout = 0);
221
222   /**
223    * Create a AsyncSocket from an already connected socket file descriptor.
224    *
225    * Note that while AsyncSocket enables TCP_NODELAY for sockets it creates
226    * when connecting, it does not change the socket options when given an
227    * existing file descriptor.  If callers want TCP_NODELAY enabled when using
228    * this version of the constructor, they need to explicitly call
229    * setNoDelay(true) after the constructor returns.
230    *
231    * @param evb EventBase that will manage this socket.
232    * @param fd  File descriptor to take over (should be a connected socket).
233    */
234   AsyncSocket(EventBase* evb, int fd);
235
236   /**
237    * Helper function to create a shared_ptr<AsyncSocket>.
238    *
239    * This passes in the correct destructor object, since AsyncSocket's
240    * destructor is protected and cannot be invoked directly.
241    */
242   static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb) {
243     return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb),
244                                            Destructor());
245   }
246
247   /**
248    * Helper function to create a shared_ptr<AsyncSocket>.
249    */
250   static std::shared_ptr<AsyncSocket> newSocket(
251       EventBase* evb,
252       const folly::SocketAddress& address,
253       uint32_t connectTimeout = 0) {
254     return std::shared_ptr<AsyncSocket>(
255         new AsyncSocket(evb, address, connectTimeout),
256         Destructor());
257   }
258
259   /**
260    * Helper function to create a shared_ptr<AsyncSocket>.
261    */
262   static std::shared_ptr<AsyncSocket> newSocket(
263       EventBase* evb,
264       const std::string& ip,
265       uint16_t port,
266       uint32_t connectTimeout = 0) {
267     return std::shared_ptr<AsyncSocket>(
268         new AsyncSocket(evb, ip, port, connectTimeout),
269         Destructor());
270   }
271
272   /**
273    * Helper function to create a shared_ptr<AsyncSocket>.
274    */
275   static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb, int fd) {
276     return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb, fd),
277                                            Destructor());
278   }
279
280   /**
281    * Destroy the socket.
282    *
283    * AsyncSocket::destroy() must be called to destroy the socket.
284    * The normal destructor is private, and should not be invoked directly.
285    * This prevents callers from deleting a AsyncSocket while it is invoking a
286    * callback.
287    */
288   virtual void destroy();
289
290   /**
291    * Get the EventBase used by this socket.
292    */
293   EventBase* getEventBase() const override {
294     return eventBase_;
295   }
296
297   /**
298    * Get the file descriptor used by the AsyncSocket.
299    */
300   virtual int getFd() const {
301     return fd_;
302   }
303
304   /**
305    * Extract the file descriptor from the AsyncSocket.
306    *
307    * This will immediately cause any installed callbacks to be invoked with an
308    * error.  The AsyncSocket may no longer be used after the file descriptor
309    * has been extracted.
310    *
311    * Returns the file descriptor.  The caller assumes ownership of the
312    * descriptor, and it will not be closed when the AsyncSocket is destroyed.
313    */
314   virtual int detachFd();
315
316   /**
317    * Uniquely identifies a handle to a socket option value. Each
318    * combination of level and option name corresponds to one socket
319    * option value.
320    */
321   class OptionKey {
322    public:
323     bool operator<(const OptionKey& other) const {
324       if (level == other.level) {
325         return optname < other.optname;
326       }
327       return level < other.level;
328     }
329     int apply(int fd, int val) const {
330       return setsockopt(fd, level, optname, &val, sizeof(val));
331     }
332     int level;
333     int optname;
334   };
335
336   // Maps from a socket option key to its value
337   typedef std::map<OptionKey, int> OptionMap;
338
339   static const OptionMap emptyOptionMap;
340   static const folly::SocketAddress anyAddress;
341
342   /**
343    * Initiate a connection.
344    *
345    * @param callback  The callback to inform when the connection attempt
346    *                  completes.
347    * @param address   The address to connect to.
348    * @param timeout   A timeout value, in milliseconds.  If the connection
349    *                  does not succeed within this period,
350    *                  callback->connectError() will be invoked.
351    */
352   virtual void connect(ConnectCallback* callback,
353                const folly::SocketAddress& address,
354                int timeout = 0,
355                const OptionMap &options = emptyOptionMap,
356                const folly::SocketAddress& bindAddr = anyAddress
357                ) noexcept;
358   void connect(ConnectCallback* callback, const std::string& ip, uint16_t port,
359                int timeout = 00,
360                const OptionMap &options = emptyOptionMap) noexcept;
361
362   /**
363    * Set the send timeout.
364    *
365    * If write requests do not make any progress for more than the specified
366    * number of milliseconds, fail all pending writes and close the socket.
367    *
368    * If write requests are currently pending when setSendTimeout() is called,
369    * the timeout interval is immediately restarted using the new value.
370    *
371    * (See the comments for AsyncSocket for an explanation of why AsyncSocket
372    * provides setSendTimeout() but not setRecvTimeout().)
373    *
374    * @param milliseconds  The timeout duration, in milliseconds.  If 0, no
375    *                      timeout will be used.
376    */
377   void setSendTimeout(uint32_t milliseconds) override;
378
379   /**
380    * Get the send timeout.
381    *
382    * @return Returns the current send timeout, in milliseconds.  A return value
383    *         of 0 indicates that no timeout is set.
384    */
385   uint32_t getSendTimeout() const override {
386     return sendTimeout_;
387   }
388
389   /**
390    * Set the maximum number of reads to execute from the underlying
391    * socket each time the EventBase detects that new ingress data is
392    * available. The default is unlimited, but callers can use this method
393    * to limit the amount of data read from the socket per event loop
394    * iteration.
395    *
396    * @param maxReads  Maximum number of reads per data-available event;
397    *                  a value of zero means unlimited.
398    */
399   void setMaxReadsPerEvent(uint16_t maxReads) {
400     maxReadsPerEvent_ = maxReads;
401   }
402
403   /**
404    * Get the maximum number of reads this object will execute from
405    * the underlying socket each time the EventBase detects that new
406    * ingress data is available.
407    *
408    * @returns Maximum number of reads per data-available event; a value
409    *          of zero means unlimited.
410    */
411   uint16_t getMaxReadsPerEvent() const {
412     return maxReadsPerEvent_;
413   }
414
415   // Read and write methods
416   void setReadCB(ReadCallback* callback);
417   ReadCallback* getReadCallback() const;
418
419   void write(WriteCallback* callback, const void* buf, size_t bytes,
420              WriteFlags flags = WriteFlags::NONE);
421   void writev(WriteCallback* callback, const iovec* vec, size_t count,
422               WriteFlags flags = WriteFlags::NONE);
423   void writeChain(WriteCallback* callback,
424                   std::unique_ptr<folly::IOBuf>&& buf,
425                   WriteFlags flags = WriteFlags::NONE);
426
427   // Methods inherited from AsyncTransport
428   void close() override;
429   void closeNow() override;
430   void closeWithReset() override;
431   void shutdownWrite() override;
432   void shutdownWriteNow() override;
433
434   bool readable() const override;
435   bool isPending() const override;
436   virtual bool hangup() const;
437   bool good() const override;
438   bool error() const override;
439   void attachEventBase(EventBase* eventBase) override;
440   void detachEventBase() override;
441   bool isDetachable() const override;
442
443   void getLocalAddress(
444     folly::SocketAddress* address) const override;
445   void getPeerAddress(
446     folly::SocketAddress* address) const override;
447
448   bool isEorTrackingEnabled() const override { return false; }
449
450   void setEorTracking(bool track) override {}
451
452   bool connecting() const override {
453     return (state_ == StateEnum::CONNECTING);
454   }
455
456   size_t getAppBytesWritten() const override {
457     return appBytesWritten_;
458   }
459
460   size_t getRawBytesWritten() const override {
461     return getAppBytesWritten();
462   }
463
464   size_t getAppBytesReceived() const override {
465     return appBytesReceived_;
466   }
467
468   size_t getRawBytesReceived() const override {
469     return getAppBytesReceived();
470   }
471
472   // Methods controlling socket options
473
474   /**
475    * Force writes to be transmitted immediately.
476    *
477    * This controls the TCP_NODELAY socket option.  When enabled, TCP segments
478    * are sent as soon as possible, even if it is not a full frame of data.
479    * When disabled, the data may be buffered briefly to try and wait for a full
480    * frame of data.
481    *
482    * By default, TCP_NODELAY is enabled for AsyncSocket objects.
483    *
484    * This method will fail if the socket is not currently open.
485    *
486    * @return Returns 0 if the TCP_NODELAY flag was successfully updated,
487    *         or a non-zero errno value on error.
488    */
489   int setNoDelay(bool noDelay);
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   /**
526    * Generic API for reading a socket option.
527    *
528    * @param level     same as the "level" parameter in getsockopt().
529    * @param optname   same as the "optname" parameter in getsockopt().
530    * @param optval    pointer to the variable in which the option value should
531    *                  be returned.
532    * @return          same as the return value of getsockopt().
533    */
534   template <typename T>
535   int  getSockOpt(int level, int optname, T *optval) {
536     return getsockopt(fd_, level, optname, optval, sizeof(T));
537   }
538
539   /**
540    * Generic API for setting a socket option.
541    *
542    * @param level     same as the "level" parameter in getsockopt().
543    * @param optname   same as the "optname" parameter in getsockopt().
544    * @param optval    the option value to set.
545    * @return          same as the return value of setsockopt().
546    */
547   template <typename T>
548   int setSockOpt(int  level,  int  optname,  const T *optval) {
549     return setsockopt(fd_, level, optname, optval, sizeof(T));
550   }
551
552  protected:
553   enum ReadResultEnum {
554     READ_EOF = 0,
555     READ_ERROR = -1,
556     READ_BLOCKING = -2,
557   };
558
559   /**
560    * Protected destructor.
561    *
562    * Users of AsyncSocket must never delete it directly.  Instead, invoke
563    * destroy() instead.  (See the documentation in DelayedDestruction.h for
564    * more details.)
565    */
566   ~AsyncSocket();
567
568   enum class StateEnum : uint8_t {
569     UNINIT,
570     CONNECTING,
571     ESTABLISHED,
572     CLOSED,
573     ERROR
574   };
575
576   friend std::ostream& operator << (std::ostream& os, const StateEnum& state);
577
578   enum ShutdownFlags {
579     /// shutdownWrite() called, but we are still waiting on writes to drain
580     SHUT_WRITE_PENDING = 0x01,
581     /// writes have been completely shut down
582     SHUT_WRITE = 0x02,
583     /**
584      * Reads have been shutdown.
585      *
586      * At the moment we don't distinguish between remote read shutdown
587      * (received EOF from the remote end) and local read shutdown.  We can
588      * only receive EOF when a read callback is set, and we immediately inform
589      * it of the EOF.  Therefore there doesn't seem to be any reason to have a
590      * separate state of "received EOF but the local side may still want to
591      * read".
592      *
593      * We also don't currently provide any API for only shutting down the read
594      * side of a socket.  (This is a no-op as far as TCP is concerned, anyway.)
595      */
596     SHUT_READ = 0x04,
597   };
598
599   class WriteRequest;
600
601   class WriteTimeout : public AsyncTimeout {
602    public:
603     WriteTimeout(AsyncSocket* socket, EventBase* eventBase)
604       : AsyncTimeout(eventBase)
605       , socket_(socket) {}
606
607     virtual void timeoutExpired() noexcept {
608       socket_->timeoutExpired();
609     }
610
611    private:
612     AsyncSocket* socket_;
613   };
614
615   class IoHandler : public EventHandler {
616    public:
617     IoHandler(AsyncSocket* socket, EventBase* eventBase)
618       : EventHandler(eventBase, -1)
619       , socket_(socket) {}
620     IoHandler(AsyncSocket* socket, EventBase* eventBase, int fd)
621       : EventHandler(eventBase, fd)
622       , socket_(socket) {}
623
624     virtual void handlerReady(uint16_t events) noexcept {
625       socket_->ioReady(events);
626     }
627
628    private:
629     AsyncSocket* socket_;
630   };
631
632   void init();
633
634   // event notification methods
635   void ioReady(uint16_t events) noexcept;
636   virtual void checkForImmediateRead() noexcept;
637   virtual void handleInitialReadWrite() noexcept;
638   virtual void handleRead() noexcept;
639   virtual void handleWrite() noexcept;
640   virtual void handleConnect() noexcept;
641   void timeoutExpired() noexcept;
642
643   /**
644    * Attempt to read from the socket.
645    *
646    * @param buf      The buffer to read data into.
647    * @param buflen   The length of the buffer.
648    *
649    * @return Returns the number of bytes read, or READ_EOF on EOF, or
650    * READ_ERROR on error, or READ_BLOCKING if the operation will
651    * block.
652    */
653   virtual ssize_t performRead(void* buf, size_t buflen);
654
655   /**
656    * Populate an iovec array from an IOBuf and attempt to write it.
657    *
658    * @param callback Write completion/error callback.
659    * @param vec      Target iovec array; caller retains ownership.
660    * @param count    Number of IOBufs to write, beginning at start of buf.
661    * @param buf      Chain of iovecs.
662    * @param flags    set of flags for the underlying write calls, like cork
663    */
664   void writeChainImpl(WriteCallback* callback, iovec* vec,
665                       size_t count, std::unique_ptr<folly::IOBuf>&& buf,
666                       WriteFlags flags);
667
668   /**
669    * Write as much data as possible to the socket without blocking,
670    * and queue up any leftover data to send when the socket can
671    * handle writes again.
672    *
673    * @param callback The callback to invoke when the write is completed.
674    * @param vec      Array of buffers to write; this method will make a
675    *                 copy of the vector (but not the buffers themselves)
676    *                 if the write has to be completed asynchronously.
677    * @param count    Number of elements in vec.
678    * @param buf      The IOBuf that manages the buffers referenced by
679    *                 vec, or a pointer to nullptr if the buffers are not
680    *                 associated with an IOBuf.  Note that ownership of
681    *                 the IOBuf is transferred here; upon completion of
682    *                 the write, the AsyncSocket deletes the IOBuf.
683    * @param flags    Set of write flags.
684    */
685   void writeImpl(WriteCallback* callback, const iovec* vec, size_t count,
686                  std::unique_ptr<folly::IOBuf>&& buf,
687                  WriteFlags flags = WriteFlags::NONE);
688
689   /**
690    * Attempt to write to the socket.
691    *
692    * @param vec             The iovec array pointing to the buffers to write.
693    * @param count           The length of the iovec array.
694    * @param flags           Set of write flags.
695    * @param countWritten    On return, the value pointed to by this parameter
696    *                          will contain the number of iovec entries that were
697    *                          fully written.
698    * @param partialWritten  On return, the value pointed to by this parameter
699    *                          will contain the number of bytes written in the
700    *                          partially written iovec entry.
701    *
702    * @return Returns the total number of bytes written, or -1 on error.  If no
703    *     data can be written immediately, 0 is returned.
704    */
705   virtual ssize_t performWrite(const iovec* vec, uint32_t count,
706                                WriteFlags flags, uint32_t* countWritten,
707                                uint32_t* partialWritten);
708
709   bool updateEventRegistration();
710
711   /**
712    * Update event registration.
713    *
714    * @param enable Flags of events to enable. Set it to 0 if no events
715    * need to be enabled in this call.
716    * @param disable Flags of events
717    * to disable. Set it to 0 if no events need to be disabled in this
718    * call.
719    *
720    * @return true iff the update is successful.
721    */
722   bool updateEventRegistration(uint16_t enable, uint16_t disable);
723
724   // Actually close the file descriptor and set it to -1 so we don't
725   // accidentally close it again.
726   void doClose();
727
728   // error handling methods
729   void startFail();
730   void finishFail();
731   void fail(const char* fn, const AsyncSocketException& ex);
732   void failConnect(const char* fn, const AsyncSocketException& ex);
733   void failRead(const char* fn, const AsyncSocketException& ex);
734   void failWrite(const char* fn, WriteCallback* callback, size_t bytesWritten,
735                  const AsyncSocketException& ex);
736   void failWrite(const char* fn, const AsyncSocketException& ex);
737   void failAllWrites(const AsyncSocketException& ex);
738   void invalidState(ConnectCallback* callback);
739   void invalidState(ReadCallback* callback);
740   void invalidState(WriteCallback* callback);
741
742   std::string withAddr(const std::string& s);
743
744   StateEnum state_;                     ///< StateEnum describing current state
745   uint8_t shutdownFlags_;               ///< Shutdown state (ShutdownFlags)
746   uint16_t eventFlags_;                 ///< EventBase::HandlerFlags settings
747   int fd_;                              ///< The socket file descriptor
748   mutable
749     folly::SocketAddress addr_;    ///< The address we tried to connect to
750   uint32_t sendTimeout_;                ///< The send timeout, in milliseconds
751   uint16_t maxReadsPerEvent_;           ///< Max reads per event loop iteration
752   EventBase* eventBase_;               ///< The EventBase
753   WriteTimeout writeTimeout_;           ///< A timeout for connect and write
754   IoHandler ioHandler_;                 ///< A EventHandler to monitor the fd
755
756   ConnectCallback* connectCallback_;    ///< ConnectCallback
757   ReadCallback* readCallback_;          ///< ReadCallback
758   WriteRequest* writeReqHead_;          ///< Chain of WriteRequests
759   WriteRequest* writeReqTail_;          ///< End of WriteRequest chain
760   ShutdownSocketSet* shutdownSocketSet_;
761   size_t appBytesReceived_;             ///< Num of bytes received from socket
762   size_t appBytesWritten_;              ///< Num of bytes written to socket
763 };
764
765
766 } // folly