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