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