2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
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>
31 #include <sys/types.h>
40 * A class for performing asynchronous I/O on a socket.
42 * AsyncSocket allows users to asynchronously wait for data on a socket, and
43 * to asynchronously send data.
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.
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.
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.
67 #if defined __linux__ && !defined SO_NO_TRANSPARENT_TLS
68 #define SO_NO_TRANSPARENT_TLS 200
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)
78 class AsyncSocket : virtual public AsyncTransportWrapper {
80 typedef std::unique_ptr<AsyncSocket, Destructor> UniquePtr;
82 class ConnectCallback {
84 virtual ~ConnectCallback() = default;
87 * connectSuccess() will be invoked when the connection has been
88 * successfully established.
90 virtual void connectSuccess() noexcept = 0;
93 * connectErr() will be invoked if the connection attempt fails.
95 * @param ex An exception describing the error that occurred.
97 virtual void connectErr(const AsyncSocketException& ex)
101 class EvbChangeCallback {
103 virtual ~EvbChangeCallback() = default;
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;
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;
115 * This interface is implemented only for platforms supporting
116 * per-socket error queues.
118 class ErrMessageCallback {
120 virtual ~ErrMessageCallback() = default;
123 * errMessage() will be invoked when kernel puts a message to
124 * the error queue associated with the socket.
126 * @param cmsg Reference to cmsghdr structure describing
127 * a message read from error queue associated
131 errMessage(const cmsghdr& cmsg) noexcept = 0;
134 * errMessageError() will be invoked if an error occurs reading a message
135 * from the socket error stream.
137 * @param ex An exception describing the error that occurred.
139 virtual void errMessageError(const AsyncSocketException& ex) noexcept = 0;
142 class SendMsgParamsCallback {
144 virtual ~SendMsgParamsCallback() = default;
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.
153 * @param flags Write flags requested for the given write operation
155 int getFlags(folly::WriteFlags flags) noexcept {
156 return getFlagsImpl(flags, getDefaultFlags(flags));
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.
166 * @param flags Write flags requested for the given write operation
167 * @param data Pointer to ancillary data buffer to initialize.
169 virtual void getAncillaryData(
170 folly::WriteFlags /*flags*/,
171 void* /*data*/) noexcept {}
174 * getAncillaryDataSize() will be invoked to retrieve the size of
175 * ancillary data buffer which should be passed to ::sendmsg() system call
177 * @param flags Write flags requested for the given write operation
179 virtual uint32_t getAncillaryDataSize(folly::WriteFlags /*flags*/)
184 static const size_t maxAncillaryDataSize{0x5000};
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
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.
200 virtual int getFlagsImpl(folly::WriteFlags /*flags*/, int defaultFlags) {
205 * getDefaultFlags() will be invoked by getFlags(folly::WriteFlags flags)
206 * to retrieve the default set of flags, and pass them to getFlagsImpl(...)
208 * @param flags Write flags requested for the given write operation
210 int getDefaultFlags(folly::WriteFlags flags) noexcept;
213 explicit AsyncSocket();
215 * Create a new unconnected AsyncSocket.
217 * connect() must later be called on this socket to establish a connection.
219 explicit AsyncSocket(EventBase* evb);
221 void setShutdownSocketSet(ShutdownSocketSet* ss);
224 * Create a new AsyncSocket and begin the connection process.
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
231 AsyncSocket(EventBase* evb,
232 const folly::SocketAddress& address,
233 uint32_t connectTimeout = 0);
236 * Create a new AsyncSocket and begin the connection process.
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
244 AsyncSocket(EventBase* evb,
245 const std::string& ip,
247 uint32_t connectTimeout = 0);
250 * Create a AsyncSocket from an already connected socket file descriptor.
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.
258 * @param evb EventBase that will manage this socket.
259 * @param fd File descriptor to take over (should be a connected socket).
261 AsyncSocket(EventBase* evb, int fd);
264 * Create an AsyncSocket from a different, already connected AsyncSocket.
266 * Similar to AsyncSocket(evb, fd) when fd was previously owned by an
269 explicit AsyncSocket(AsyncSocket::UniquePtr);
272 * Helper function to create a shared_ptr<AsyncSocket>.
274 * This passes in the correct destructor object, since AsyncSocket's
275 * destructor is protected and cannot be invoked directly.
277 static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb) {
278 return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb),
283 * Helper function to create a shared_ptr<AsyncSocket>.
285 static std::shared_ptr<AsyncSocket> newSocket(
287 const folly::SocketAddress& address,
288 uint32_t connectTimeout = 0) {
289 return std::shared_ptr<AsyncSocket>(
290 new AsyncSocket(evb, address, connectTimeout),
295 * Helper function to create a shared_ptr<AsyncSocket>.
297 static std::shared_ptr<AsyncSocket> newSocket(
299 const std::string& ip,
301 uint32_t connectTimeout = 0) {
302 return std::shared_ptr<AsyncSocket>(
303 new AsyncSocket(evb, ip, port, connectTimeout),
308 * Helper function to create a shared_ptr<AsyncSocket>.
310 static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb, int fd) {
311 return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb, fd),
316 * Destroy the socket.
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
323 void destroy() override;
326 * Get the EventBase used by this socket.
328 EventBase* getEventBase() const override {
333 * Get the file descriptor used by the AsyncSocket.
335 virtual int getFd() const {
340 * Extract the file descriptor from the AsyncSocket.
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.
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.).
350 * Returns the file descriptor. The caller assumes ownership of the
351 * descriptor, and it will not be closed when the AsyncSocket is destroyed.
353 virtual int detachFd();
356 * Uniquely identifies a handle to a socket option value. Each
357 * combination of level and option name corresponds to one socket
362 bool operator<(const OptionKey& other) const {
363 if (level == other.level) {
364 return optname < other.optname;
366 return level < other.level;
368 int apply(int fd, int val) const {
369 return setsockopt(fd, level, optname, &val, sizeof(val));
375 // Maps from a socket option key to its value
376 typedef std::map<OptionKey, int> OptionMap;
378 static const OptionMap emptyOptionMap;
379 static const folly::SocketAddress& anyAddress();
382 * Initiate a connection.
384 * @param callback The callback to inform when the connection attempt
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.
391 virtual void connect(
392 ConnectCallback* callback,
393 const folly::SocketAddress& address,
395 const OptionMap& options = emptyOptionMap,
396 const folly::SocketAddress& bindAddr = anyAddress()) noexcept;
399 ConnectCallback* callback,
400 const std::string& ip,
403 const OptionMap& options = emptyOptionMap) noexcept;
406 * If a connect request is in-flight, cancels it and closes the socket
407 * immediately. Otherwise, this is a no-op.
409 * This does not invoke any connection related callbacks. Call this to
410 * prevent any connect callback while cleaning up, etc.
412 void cancelConnect();
415 * Set the send timeout.
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.
420 * If write requests are currently pending when setSendTimeout() is called,
421 * the timeout interval is immediately restarted using the new value.
423 * (See the comments for AsyncSocket for an explanation of why AsyncSocket
424 * provides setSendTimeout() but not setRecvTimeout().)
426 * @param milliseconds The timeout duration, in milliseconds. If 0, no
427 * timeout will be used.
429 void setSendTimeout(uint32_t milliseconds) override;
432 * Get the send timeout.
434 * @return Returns the current send timeout, in milliseconds. A return value
435 * of 0 indicates that no timeout is set.
437 uint32_t getSendTimeout() const override {
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
448 * @param maxReads Maximum number of reads per data-available event;
449 * a value of zero means unlimited.
451 void setMaxReadsPerEvent(uint16_t maxReads) {
452 maxReadsPerEvent_ = maxReads;
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.
460 * @returns Maximum number of reads per data-available event; a value
461 * of zero means unlimited.
463 uint16_t getMaxReadsPerEvent() const {
464 return maxReadsPerEvent_;
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
476 virtual void setErrMessageCB(ErrMessageCallback* callback);
479 * Get a pointer to ErrMessageCallback implementation currently
480 * registered with this socket.
483 virtual ErrMessageCallback* getErrMessageCallback() const;
486 * Set a pointer to SendMsgParamsCallback implementation which
487 * will be used to form ::sendmsg() system call parameters
490 virtual void setSendMsgParamCB(SendMsgParamsCallback* callback);
493 * Get a pointer to SendMsgParamsCallback implementation currently
494 * registered with this socket.
497 virtual SendMsgParamsCallback* getSendMsgParamsCB() const;
499 // Read and write methods
500 void setReadCB(ReadCallback* callback) override;
501 ReadCallback* getReadCallback() const override;
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;
512 virtual void writeRequest(WriteRequest* req);
513 void writeRequestReady() {
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;
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;
534 void getLocalAddress(
535 folly::SocketAddress* address) const override;
537 folly::SocketAddress* address) const override;
539 bool isEorTrackingEnabled() const override {
543 void setEorTracking(bool track) override {
547 bool connecting() const override {
548 return (state_ == StateEnum::CONNECTING);
551 virtual bool isClosedByPeer() const {
552 return (state_ == StateEnum::CLOSED &&
553 (readErr_ == READ_EOF || readErr_ == READ_ERROR));
556 virtual bool isClosedBySelf() const {
557 return (state_ == StateEnum::CLOSED &&
558 (readErr_ != READ_EOF && readErr_ != READ_ERROR));
561 size_t getAppBytesWritten() const override {
562 return appBytesWritten_;
565 size_t getRawBytesWritten() const override {
566 return getAppBytesWritten();
569 size_t getAppBytesReceived() const override {
570 return appBytesReceived_;
573 size_t getRawBytesReceived() const override {
574 return getAppBytesReceived();
577 std::chrono::nanoseconds getConnectTime() const {
578 return connectEndTime_ - connectStartTime_;
581 std::chrono::milliseconds getConnectTimeout() const {
582 return connectTimeout_;
585 bool getTFOAttempted() const {
586 return tfoAttempted_;
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
595 bool getTFOFinished() const {
600 * Returns whether or not TFO attempt succeded on this
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.
611 bool getTFOSucceded() const;
613 // Methods controlling socket options
616 * Force writes to be transmitted immediately.
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
623 * By default, TCP_NODELAY is enabled for AsyncSocket objects.
625 * This method will fail if the socket is not currently open.
627 * @return Returns 0 if the TCP_NODELAY flag was successfully updated,
628 * or a non-zero errno value on error.
630 int setNoDelay(bool noDelay);
634 * Set the FD_CLOEXEC flag so that the socket will be closed if the program
635 * later forks and execs.
637 void setCloseOnExec();
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
645 int setCongestionFlavor(const std::string &cname);
648 * Forces ACKs to be sent immediately
650 * @return Returns 0 if the TCP_QUICKACK flag was successfully updated,
651 * or a non-zero errno value on error.
653 int setQuickAck(bool quickack);
656 * Set the send bufsize
658 int setSendBufSize(size_t bufsize);
661 * Set the recv bufsize
663 int setRecvBufSize(size_t bufsize);
666 * Sets a specific tcp personality
667 * Available only on kernels 3.2 and greater
669 #define SO_SET_NAMESPACE 41
670 int setTCPProfile(int profd);
673 * Generic API for reading a socket option.
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
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().
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);
690 * Generic API for setting a socket option.
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().
697 template <typename T>
698 int setSockOpt(int level, int optname, const T *optval) {
699 return setsockopt(fd_, level, optname, optval, sizeof(T));
703 * Virtual method for reading a socket option returning integer
704 * value, which is the most typical case. Convenient for overriding
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().
714 getSockOptVirtual(int level, int optname, void* optval, socklen_t* optlen) {
715 return getsockopt(fd_, level, optname, optval, optlen);
719 * Virtual method for setting a socket option accepting integer
720 * value, which is the most typical case. Convenient for overriding
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().
729 virtual int setSockOptVirtual(
734 return setsockopt(fd_, level, optname, optval, optlen);
738 * Set pre-received data, to be returned to read callback before any data
741 virtual void setPreReceivedData(std::unique_ptr<IOBuf> data) {
742 if (preReceivedData_) {
743 preReceivedData_->prependChain(std::move(data));
745 preReceivedData_ = std::move(data);
750 * Enables TFO behavior on the AsyncSocket if FOLLY_ALLOW_TFO
754 // No-op if folly does not allow tfo
760 void disableTransparentTls() {
761 noTransparentTls_ = true;
764 enum class StateEnum : uint8_t {
773 void setBufferCallback(BufferCallback* cb);
775 // Callers should set this prior to connecting the socket for the safest
777 void setEvbChangedCallback(std::unique_ptr<EvbChangeCallback> cb) {
778 evbChangeCb_ = std::move(cb);
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.
789 explicit WriteResult(ssize_t ret) : writeReturn(ret) {}
791 WriteResult(ssize_t ret, std::unique_ptr<const AsyncSocketException> e)
792 : writeReturn(ret), exception(std::move(e)) {}
795 std::unique_ptr<const AsyncSocketException> exception;
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
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.
807 explicit ReadResult(ssize_t ret) : readReturn(ret) {}
809 ReadResult(ssize_t ret, std::unique_ptr<const AsyncSocketException> e)
810 : readReturn(ret), exception(std::move(e)) {}
813 std::unique_ptr<const AsyncSocketException> exception;
817 * A WriteRequest object tracks information about a pending write operation.
821 WriteRequest(AsyncSocket* socket, WriteCallback* callback) :
822 socket_(socket), callback_(callback) {}
824 virtual void start() {}
826 virtual void destroy() = 0;
828 virtual WriteResult performWrite() = 0;
830 virtual void consume() = 0;
832 virtual bool isComplete() = 0;
834 WriteRequest* getNext() const {
838 WriteCallback* getCallback() const {
842 uint32_t getTotalBytesWritten() const {
843 return totalBytesWritten_;
846 void append(WriteRequest* next) {
847 assert(next_ == nullptr);
851 void fail(const char* fn, const AsyncSocketException& ex) {
852 socket_->failWrite(fn, ex);
855 void bytesWritten(size_t count) {
856 totalBytesWritten_ += uint32_t(count);
857 socket_->appBytesWritten_ += count;
861 // protected destructor, to ensure callers use destroy()
862 virtual ~WriteRequest() {}
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
871 enum ReadResultEnum {
878 enum WriteResultEnum {
883 * Protected destructor.
885 * Users of AsyncSocket must never delete it directly. Instead, invoke
886 * destroy() instead. (See the documentation in DelayedDestruction.h for
889 ~AsyncSocket() override;
891 friend std::ostream& operator << (std::ostream& os, const StateEnum& state);
894 /// shutdownWrite() called, but we are still waiting on writes to drain
895 SHUT_WRITE_PENDING = 0x01,
896 /// writes have been completely shut down
899 * Reads have been shutdown.
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
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.)
914 class BytesWriteRequest;
916 class WriteTimeout : public AsyncTimeout {
918 WriteTimeout(AsyncSocket* socket, EventBase* eventBase)
919 : AsyncTimeout(eventBase)
922 void timeoutExpired() noexcept override {
923 socket_->timeoutExpired();
927 AsyncSocket* socket_;
930 class IoHandler : public EventHandler {
932 IoHandler(AsyncSocket* socket, EventBase* eventBase)
933 : EventHandler(eventBase, -1)
935 IoHandler(AsyncSocket* socket, EventBase* eventBase, int fd)
936 : EventHandler(eventBase, fd)
939 void handlerReady(uint16_t events) noexcept override {
940 socket_->ioReady(events);
944 AsyncSocket* socket_;
949 class ImmediateReadCB : public folly::EventBase::LoopCallback {
951 explicit ImmediateReadCB(AsyncSocket* socket) : socket_(socket) {}
952 void runLoopCallback() noexcept override {
953 DestructorGuard dg(socket_);
954 socket_->checkForImmediateRead();
957 AsyncSocket* socket_;
961 * Schedule checkForImmediateRead to be executed in the next loop
964 void scheduleImmediateRead() noexcept {
966 eventBase_->runInLoop(&immediateReadHandler_);
971 * Schedule handleInitalReadWrite to run in the next iteration.
973 void scheduleInitialReadWrite() noexcept {
975 DestructorGuard dg(this);
976 eventBase_->runInLoop([this, dg] {
978 handleInitialReadWrite();
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;
996 * Attempt to read from the socket.
998 * @param buf The buffer to read data into.
999 * @param buflen The length of the buffer.
1001 * @return Returns a read result. See read result for details.
1003 virtual ReadResult performRead(void** buf, size_t* buflen, size_t* offset);
1006 * Populate an iovec array from an IOBuf and attempt to write it.
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
1014 void writeChainImpl(WriteCallback* callback, iovec* vec,
1015 size_t count, std::unique_ptr<folly::IOBuf>&& buf,
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.
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.
1035 void writeImpl(WriteCallback* callback, const iovec* vec, size_t count,
1036 std::unique_ptr<folly::IOBuf>&& buf,
1037 WriteFlags flags = WriteFlags::NONE);
1040 * Attempt to write to the socket.
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
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.
1052 * @return Returns a WriteResult. See WriteResult for more details.
1054 virtual WriteResult performWrite(
1058 uint32_t* countWritten,
1059 uint32_t* partialWritten);
1062 * Sends the message over the socket using sendmsg
1064 * @param msg Message to send
1065 * @param msg_flags Flags to pass to sendmsg
1067 AsyncSocket::WriteResult
1068 sendSocketMessage(int fd, struct msghdr* msg, int msg_flags);
1070 virtual ssize_t tfoSendMsg(int fd, struct msghdr* msg, int msg_flags);
1072 int socketConnect(const struct sockaddr* addr, socklen_t len);
1074 virtual void scheduleConnectTimeout();
1075 void registerForConnectEvents();
1077 bool updateEventRegistration();
1080 * Update event registration.
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
1088 * @return true iff the update is successful.
1090 bool updateEventRegistration(uint16_t enable, uint16_t disable);
1092 // Actually close the file descriptor and set it to -1 so we don't
1093 // accidentally close it again.
1096 // error handling methods
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);
1116 std::string withAddr(const std::string& s);
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
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};
1144 // Pre-received data, to be returned to read callback before any data from the
1146 std::unique_ptr<IOBuf> preReceivedData_;
1148 int8_t readErr_{READ_NO_ERROR}; ///< The read error encountered, if any
1150 std::chrono::steady_clock::time_point connectStartTime_;
1151 std::chrono::steady_clock::time_point connectEndTime_;
1153 std::chrono::milliseconds connectTimeout_{0};
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};
1163 std::unique_ptr<EvbChangeCallback> evbChangeCb_{nullptr};
1166 #pragma vtordisp(pop)