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