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