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