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