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