2 * Copyright 2016 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/io/IOBuf.h>
22 #include <folly/io/ShutdownSocketSet.h>
23 #include <folly/io/async/AsyncSocketException.h>
24 #include <folly/io/async/AsyncTimeout.h>
25 #include <folly/io/async/AsyncTransport.h>
26 #include <folly/io/async/DelayedDestruction.h>
27 #include <folly/io/async/EventHandler.h>
28 #include <sys/socket.h>
29 #include <sys/types.h>
38 * A class for performing asynchronous I/O on a socket.
40 * AsyncSocket allows users to asynchronously wait for data on a socket, and
41 * to asynchronously send data.
43 * The APIs for reading and writing are intentionally asymmetric. Waiting for
44 * data to read is a persistent API: a callback is installed, and is notified
45 * whenever new data is available. It continues to be notified of new events
46 * until it is uninstalled.
48 * AsyncSocket does not provide read timeout functionality, because it
49 * typically cannot determine when the timeout should be active. Generally, a
50 * timeout should only be enabled when processing is blocked waiting on data
51 * from the remote endpoint. For server sockets, the timeout should not be
52 * active if the server is currently processing one or more outstanding
53 * requests for this socket. For client sockets, the timeout should not be
54 * active if there are no requests pending on the socket. Additionally, if a
55 * client has multiple pending requests, it will ususally want a separate
56 * timeout for each request, rather than a single read timeout.
58 * The write API is fairly intuitive: a user can request to send a block of
59 * data, and a callback will be informed once the entire block has been
60 * transferred to the kernel, or on error. AsyncSocket does provide a send
61 * timeout, since most callers want to give up if the remote end stops
62 * responding and no further progress can be made sending the data.
66 // We do a dynamic_cast on this, in
67 // AsyncTransportWrapper::getUnderlyingTransport so be safe and
68 // force displacements for it. See:
69 // https://msdn.microsoft.com/en-us/library/7sf3txa8.aspx
70 #pragma vtordisp(push, 2)
72 class AsyncSocket : virtual public AsyncTransportWrapper {
74 typedef std::unique_ptr<AsyncSocket, Destructor> UniquePtr;
76 class ConnectCallback {
78 virtual ~ConnectCallback() = default;
81 * connectSuccess() will be invoked when the connection has been
82 * successfully established.
84 virtual void connectSuccess() noexcept = 0;
87 * connectErr() will be invoked if the connection attempt fails.
89 * @param ex An exception describing the error that occurred.
91 virtual void connectErr(const AsyncSocketException& ex)
95 explicit AsyncSocket();
97 * Create a new unconnected AsyncSocket.
99 * connect() must later be called on this socket to establish a connection.
101 explicit AsyncSocket(EventBase* evb);
103 void setShutdownSocketSet(ShutdownSocketSet* ss);
106 * Create a new AsyncSocket and begin the connection process.
108 * @param evb EventBase that will manage this socket.
109 * @param address The address to connect to.
110 * @param connectTimeout Optional timeout in milliseconds for the connection
113 AsyncSocket(EventBase* evb,
114 const folly::SocketAddress& address,
115 uint32_t connectTimeout = 0);
118 * Create a new AsyncSocket and begin the connection process.
120 * @param evb EventBase that will manage this socket.
121 * @param ip IP address to connect to (dotted-quad).
122 * @param port Destination port in host byte order.
123 * @param connectTimeout Optional timeout in milliseconds for the connection
126 AsyncSocket(EventBase* evb,
127 const std::string& ip,
129 uint32_t connectTimeout = 0);
132 * Create a AsyncSocket from an already connected socket file descriptor.
134 * Note that while AsyncSocket enables TCP_NODELAY for sockets it creates
135 * when connecting, it does not change the socket options when given an
136 * existing file descriptor. If callers want TCP_NODELAY enabled when using
137 * this version of the constructor, they need to explicitly call
138 * setNoDelay(true) after the constructor returns.
140 * @param evb EventBase that will manage this socket.
141 * @param fd File descriptor to take over (should be a connected socket).
143 AsyncSocket(EventBase* evb, int fd);
146 * Helper function to create a shared_ptr<AsyncSocket>.
148 * This passes in the correct destructor object, since AsyncSocket's
149 * destructor is protected and cannot be invoked directly.
151 static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb) {
152 return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb),
157 * Helper function to create a shared_ptr<AsyncSocket>.
159 static std::shared_ptr<AsyncSocket> newSocket(
161 const folly::SocketAddress& address,
162 uint32_t connectTimeout = 0) {
163 return std::shared_ptr<AsyncSocket>(
164 new AsyncSocket(evb, address, connectTimeout),
169 * Helper function to create a shared_ptr<AsyncSocket>.
171 static std::shared_ptr<AsyncSocket> newSocket(
173 const std::string& ip,
175 uint32_t connectTimeout = 0) {
176 return std::shared_ptr<AsyncSocket>(
177 new AsyncSocket(evb, ip, port, connectTimeout),
182 * Helper function to create a shared_ptr<AsyncSocket>.
184 static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb, int fd) {
185 return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb, fd),
190 * Destroy the socket.
192 * AsyncSocket::destroy() must be called to destroy the socket.
193 * The normal destructor is private, and should not be invoked directly.
194 * This prevents callers from deleting a AsyncSocket while it is invoking a
197 virtual void destroy() override;
200 * Get the EventBase used by this socket.
202 EventBase* getEventBase() const override {
207 * Get the file descriptor used by the AsyncSocket.
209 virtual int getFd() const {
214 * Extract the file descriptor from the AsyncSocket.
216 * This will immediately cause any installed callbacks to be invoked with an
217 * error. The AsyncSocket may no longer be used after the file descriptor
218 * has been extracted.
220 * Returns the file descriptor. The caller assumes ownership of the
221 * descriptor, and it will not be closed when the AsyncSocket is destroyed.
223 virtual int detachFd();
226 * Uniquely identifies a handle to a socket option value. Each
227 * combination of level and option name corresponds to one socket
232 bool operator<(const OptionKey& other) const {
233 if (level == other.level) {
234 return optname < other.optname;
236 return level < other.level;
238 int apply(int fd, int val) const {
239 return setsockopt(fd, level, optname, &val, sizeof(val));
245 // Maps from a socket option key to its value
246 typedef std::map<OptionKey, int> OptionMap;
248 static const OptionMap emptyOptionMap;
249 static const folly::SocketAddress& anyAddress();
252 * Initiate a connection.
254 * @param callback The callback to inform when the connection attempt
256 * @param address The address to connect to.
257 * @param timeout A timeout value, in milliseconds. If the connection
258 * does not succeed within this period,
259 * callback->connectError() will be invoked.
261 virtual void connect(
262 ConnectCallback* callback,
263 const folly::SocketAddress& address,
265 const OptionMap& options = emptyOptionMap,
266 const folly::SocketAddress& bindAddr = anyAddress()) noexcept;
269 ConnectCallback* callback,
270 const std::string& ip,
273 const OptionMap& options = emptyOptionMap) noexcept;
276 * If a connect request is in-flight, cancels it and closes the socket
277 * immediately. Otherwise, this is a no-op.
279 * This does not invoke any connection related callbacks. Call this to
280 * prevent any connect callback while cleaning up, etc.
282 void cancelConnect();
285 * Set the send timeout.
287 * If write requests do not make any progress for more than the specified
288 * number of milliseconds, fail all pending writes and close the socket.
290 * If write requests are currently pending when setSendTimeout() is called,
291 * the timeout interval is immediately restarted using the new value.
293 * (See the comments for AsyncSocket for an explanation of why AsyncSocket
294 * provides setSendTimeout() but not setRecvTimeout().)
296 * @param milliseconds The timeout duration, in milliseconds. If 0, no
297 * timeout will be used.
299 void setSendTimeout(uint32_t milliseconds) override;
302 * Get the send timeout.
304 * @return Returns the current send timeout, in milliseconds. A return value
305 * of 0 indicates that no timeout is set.
307 uint32_t getSendTimeout() const override {
312 * Set the maximum number of reads to execute from the underlying
313 * socket each time the EventBase detects that new ingress data is
314 * available. The default is unlimited, but callers can use this method
315 * to limit the amount of data read from the socket per event loop
318 * @param maxReads Maximum number of reads per data-available event;
319 * a value of zero means unlimited.
321 void setMaxReadsPerEvent(uint16_t maxReads) {
322 maxReadsPerEvent_ = maxReads;
326 * Get the maximum number of reads this object will execute from
327 * the underlying socket each time the EventBase detects that new
328 * ingress data is available.
330 * @returns Maximum number of reads per data-available event; a value
331 * of zero means unlimited.
333 uint16_t getMaxReadsPerEvent() const {
334 return maxReadsPerEvent_;
337 // Read and write methods
338 void setReadCB(ReadCallback* callback) override;
339 ReadCallback* getReadCallback() const override;
341 void write(WriteCallback* callback, const void* buf, size_t bytes,
342 WriteFlags flags = WriteFlags::NONE) override;
343 void writev(WriteCallback* callback, const iovec* vec, size_t count,
344 WriteFlags flags = WriteFlags::NONE) override;
345 void writeChain(WriteCallback* callback,
346 std::unique_ptr<folly::IOBuf>&& buf,
347 WriteFlags flags = WriteFlags::NONE) override;
350 virtual void writeRequest(WriteRequest* req);
351 void writeRequestReady() {
355 // Methods inherited from AsyncTransport
356 void close() override;
357 void closeNow() override;
358 void closeWithReset() override;
359 void shutdownWrite() override;
360 void shutdownWriteNow() override;
362 bool readable() const override;
363 bool isPending() const override;
364 virtual bool hangup() const;
365 bool good() const override;
366 bool error() const override;
367 void attachEventBase(EventBase* eventBase) override;
368 void detachEventBase() override;
369 bool isDetachable() const override;
371 void getLocalAddress(
372 folly::SocketAddress* address) const override;
374 folly::SocketAddress* address) const override;
376 bool isEorTrackingEnabled() const override { return false; }
378 void setEorTracking(bool /*track*/) override {}
380 bool connecting() const override {
381 return (state_ == StateEnum::CONNECTING);
384 virtual bool isClosedByPeer() const {
385 return (state_ == StateEnum::CLOSED &&
386 (readErr_ == READ_EOF || readErr_ == READ_ERROR));
389 virtual bool isClosedBySelf() const {
390 return (state_ == StateEnum::CLOSED &&
391 (readErr_ != READ_EOF && readErr_ != READ_ERROR));
394 size_t getAppBytesWritten() const override {
395 return appBytesWritten_;
398 size_t getRawBytesWritten() const override {
399 return getAppBytesWritten();
402 size_t getAppBytesReceived() const override {
403 return appBytesReceived_;
406 size_t getRawBytesReceived() const override {
407 return getAppBytesReceived();
410 std::chrono::nanoseconds getConnectTime() const {
411 return connectEndTime_ - connectStartTime_;
414 std::chrono::milliseconds getConnectTimeout() const {
415 return connectTimeout_;
418 // Methods controlling socket options
421 * Force writes to be transmitted immediately.
423 * This controls the TCP_NODELAY socket option. When enabled, TCP segments
424 * are sent as soon as possible, even if it is not a full frame of data.
425 * When disabled, the data may be buffered briefly to try and wait for a full
428 * By default, TCP_NODELAY is enabled for AsyncSocket objects.
430 * This method will fail if the socket is not currently open.
432 * @return Returns 0 if the TCP_NODELAY flag was successfully updated,
433 * or a non-zero errno value on error.
435 int setNoDelay(bool noDelay);
439 * Set the FD_CLOEXEC flag so that the socket will be closed if the program
440 * later forks and execs.
442 void setCloseOnExec();
445 * Set the Flavor of Congestion Control to be used for this Socket
446 * Please check '/lib/modules/<kernel>/kernel/net/ipv4' for tcp_*.ko
447 * first to make sure the module is available for plugging in
448 * Alternatively you can choose from net.ipv4.tcp_allowed_congestion_control
450 int setCongestionFlavor(const std::string &cname);
453 * Forces ACKs to be sent immediately
455 * @return Returns 0 if the TCP_QUICKACK flag was successfully updated,
456 * or a non-zero errno value on error.
458 int setQuickAck(bool quickack);
461 * Set the send bufsize
463 int setSendBufSize(size_t bufsize);
466 * Set the recv bufsize
468 int setRecvBufSize(size_t bufsize);
471 * Sets a specific tcp personality
472 * Available only on kernels 3.2 and greater
474 #define SO_SET_NAMESPACE 41
475 int setTCPProfile(int profd);
478 * Generic API for reading a socket option.
480 * @param level same as the "level" parameter in getsockopt().
481 * @param optname same as the "optname" parameter in getsockopt().
482 * @param optval pointer to the variable in which the option value should
484 * @param optlen value-result argument, initially containing the size of
485 * the buffer pointed to by optval, and modified on return
486 * to indicate the actual size of the value returned.
487 * @return same as the return value of getsockopt().
489 template <typename T>
490 int getSockOpt(int level, int optname, T* optval, socklen_t* optlen) {
491 return getsockopt(fd_, level, optname, (void*) optval, optlen);
495 * Generic API for setting a socket option.
497 * @param level same as the "level" parameter in getsockopt().
498 * @param optname same as the "optname" parameter in getsockopt().
499 * @param optval the option value to set.
500 * @return same as the return value of setsockopt().
502 template <typename T>
503 int setSockOpt(int level, int optname, const T *optval) {
504 return setsockopt(fd_, level, optname, optval, sizeof(T));
507 virtual void setPeek(bool peek) {
511 enum class StateEnum : uint8_t {
519 void setBufferCallback(BufferCallback* cb);
522 * writeReturn is the total number of bytes written, or WRITE_ERROR on error.
523 * If no data has been written, 0 is returned.
524 * exception is a more specific exception that cause a write error.
525 * Not all writes have exceptions associated with them thus writeReturn
526 * should be checked to determine whether the operation resulted in an error.
529 explicit WriteResult(ssize_t ret) : writeReturn(ret) {}
531 WriteResult(ssize_t ret, std::unique_ptr<const AsyncSocketException> e)
532 : writeReturn(ret), exception(std::move(e)) {}
535 std::unique_ptr<const AsyncSocketException> exception;
539 * readReturn is the number of bytes read, or READ_EOF on EOF, or
540 * READ_ERROR on error, or READ_BLOCKING if the operation will
542 * exception is a more specific exception that may have caused a read error.
543 * Not all read errors have exceptions associated with them thus readReturn
544 * should be checked to determine whether the operation resulted in an error.
547 explicit ReadResult(ssize_t ret) : readReturn(ret) {}
549 ReadResult(ssize_t ret, std::unique_ptr<const AsyncSocketException> e)
550 : readReturn(ret), exception(std::move(e)) {}
553 std::unique_ptr<const AsyncSocketException> exception;
557 * A WriteRequest object tracks information about a pending write operation.
561 WriteRequest(AsyncSocket* socket, WriteCallback* callback) :
562 socket_(socket), callback_(callback) {}
564 virtual void start() {};
566 virtual void destroy() = 0;
568 virtual WriteResult performWrite() = 0;
570 virtual void consume() = 0;
572 virtual bool isComplete() = 0;
574 WriteRequest* getNext() const {
578 WriteCallback* getCallback() const {
582 uint32_t getTotalBytesWritten() const {
583 return totalBytesWritten_;
586 void append(WriteRequest* next) {
587 assert(next_ == nullptr);
591 void fail(const char* fn, const AsyncSocketException& ex) {
592 socket_->failWrite(fn, ex);
595 void bytesWritten(size_t count) {
596 totalBytesWritten_ += count;
597 socket_->appBytesWritten_ += count;
601 // protected destructor, to ensure callers use destroy()
602 virtual ~WriteRequest() {}
604 AsyncSocket* socket_; ///< parent socket
605 WriteRequest* next_{nullptr}; ///< pointer to next WriteRequest
606 WriteCallback* callback_; ///< completion callback
607 uint32_t totalBytesWritten_{0}; ///< total bytes written
611 enum ReadResultEnum {
618 enum WriteResultEnum {
623 * Protected destructor.
625 * Users of AsyncSocket must never delete it directly. Instead, invoke
626 * destroy() instead. (See the documentation in DelayedDestruction.h for
631 friend std::ostream& operator << (std::ostream& os, const StateEnum& state);
634 /// shutdownWrite() called, but we are still waiting on writes to drain
635 SHUT_WRITE_PENDING = 0x01,
636 /// writes have been completely shut down
639 * Reads have been shutdown.
641 * At the moment we don't distinguish between remote read shutdown
642 * (received EOF from the remote end) and local read shutdown. We can
643 * only receive EOF when a read callback is set, and we immediately inform
644 * it of the EOF. Therefore there doesn't seem to be any reason to have a
645 * separate state of "received EOF but the local side may still want to
648 * We also don't currently provide any API for only shutting down the read
649 * side of a socket. (This is a no-op as far as TCP is concerned, anyway.)
654 class BytesWriteRequest;
656 class WriteTimeout : public AsyncTimeout {
658 WriteTimeout(AsyncSocket* socket, EventBase* eventBase)
659 : AsyncTimeout(eventBase)
662 virtual void timeoutExpired() noexcept {
663 socket_->timeoutExpired();
667 AsyncSocket* socket_;
670 class IoHandler : public EventHandler {
672 IoHandler(AsyncSocket* socket, EventBase* eventBase)
673 : EventHandler(eventBase, -1)
675 IoHandler(AsyncSocket* socket, EventBase* eventBase, int fd)
676 : EventHandler(eventBase, fd)
679 virtual void handlerReady(uint16_t events) noexcept {
680 socket_->ioReady(events);
684 AsyncSocket* socket_;
689 class ImmediateReadCB : public folly::EventBase::LoopCallback {
691 explicit ImmediateReadCB(AsyncSocket* socket) : socket_(socket) {}
692 void runLoopCallback() noexcept override {
693 DestructorGuard dg(socket_);
694 socket_->checkForImmediateRead();
697 AsyncSocket* socket_;
701 * Schedule checkForImmediateRead to be executed in the next loop
704 void scheduleImmediateRead() noexcept {
706 eventBase_->runInLoop(&immediateReadHandler_);
710 // event notification methods
711 void ioReady(uint16_t events) noexcept;
712 virtual void checkForImmediateRead() noexcept;
713 virtual void handleInitialReadWrite() noexcept;
714 virtual void prepareReadBuffer(void** buf, size_t* buflen) noexcept;
715 virtual void handleRead() noexcept;
716 virtual void handleWrite() noexcept;
717 virtual void handleConnect() noexcept;
718 void timeoutExpired() noexcept;
721 * Attempt to read from the socket.
723 * @param buf The buffer to read data into.
724 * @param buflen The length of the buffer.
726 * @return Returns a read result. See read result for details.
728 virtual ReadResult performRead(void** buf, size_t* buflen, size_t* offset);
731 * Populate an iovec array from an IOBuf and attempt to write it.
733 * @param callback Write completion/error callback.
734 * @param vec Target iovec array; caller retains ownership.
735 * @param count Number of IOBufs to write, beginning at start of buf.
736 * @param buf Chain of iovecs.
737 * @param flags set of flags for the underlying write calls, like cork
739 void writeChainImpl(WriteCallback* callback, iovec* vec,
740 size_t count, std::unique_ptr<folly::IOBuf>&& buf,
744 * Write as much data as possible to the socket without blocking,
745 * and queue up any leftover data to send when the socket can
746 * handle writes again.
748 * @param callback The callback to invoke when the write is completed.
749 * @param vec Array of buffers to write; this method will make a
750 * copy of the vector (but not the buffers themselves)
751 * if the write has to be completed asynchronously.
752 * @param count Number of elements in vec.
753 * @param buf The IOBuf that manages the buffers referenced by
754 * vec, or a pointer to nullptr if the buffers are not
755 * associated with an IOBuf. Note that ownership of
756 * the IOBuf is transferred here; upon completion of
757 * the write, the AsyncSocket deletes the IOBuf.
758 * @param flags Set of write flags.
760 void writeImpl(WriteCallback* callback, const iovec* vec, size_t count,
761 std::unique_ptr<folly::IOBuf>&& buf,
762 WriteFlags flags = WriteFlags::NONE);
765 * Attempt to write to the socket.
767 * @param vec The iovec array pointing to the buffers to write.
768 * @param count The length of the iovec array.
769 * @param flags Set of write flags.
770 * @param countWritten On return, the value pointed to by this parameter
771 * will contain the number of iovec entries that were
773 * @param partialWritten On return, the value pointed to by this parameter
774 * will contain the number of bytes written in the
775 * partially written iovec entry.
777 * @return Returns a WriteResult. See WriteResult for more details.
779 virtual WriteResult performWrite(
783 uint32_t* countWritten,
784 uint32_t* partialWritten);
786 bool updateEventRegistration();
789 * Update event registration.
791 * @param enable Flags of events to enable. Set it to 0 if no events
792 * need to be enabled in this call.
793 * @param disable Flags of events
794 * to disable. Set it to 0 if no events need to be disabled in this
797 * @return true iff the update is successful.
799 bool updateEventRegistration(uint16_t enable, uint16_t disable);
801 // Actually close the file descriptor and set it to -1 so we don't
802 // accidentally close it again.
805 // error handling methods
808 void fail(const char* fn, const AsyncSocketException& ex);
809 void failConnect(const char* fn, const AsyncSocketException& ex);
810 void failRead(const char* fn, const AsyncSocketException& ex);
811 void failWrite(const char* fn, WriteCallback* callback, size_t bytesWritten,
812 const AsyncSocketException& ex);
813 void failWrite(const char* fn, const AsyncSocketException& ex);
814 void failAllWrites(const AsyncSocketException& ex);
815 void invokeConnectErr(const AsyncSocketException& ex);
816 void invokeConnectSuccess();
817 void invalidState(ConnectCallback* callback);
818 void invalidState(ReadCallback* callback);
819 void invalidState(WriteCallback* callback);
821 std::string withAddr(const std::string& s);
823 StateEnum state_; ///< StateEnum describing current state
824 uint8_t shutdownFlags_; ///< Shutdown state (ShutdownFlags)
825 uint16_t eventFlags_; ///< EventBase::HandlerFlags settings
826 int fd_; ///< The socket file descriptor
827 mutable folly::SocketAddress addr_; ///< The address we tried to connect to
828 mutable folly::SocketAddress localAddr_;
829 ///< The address we are connecting from
830 uint32_t sendTimeout_; ///< The send timeout, in milliseconds
831 uint16_t maxReadsPerEvent_; ///< Max reads per event loop iteration
832 EventBase* eventBase_; ///< The EventBase
833 WriteTimeout writeTimeout_; ///< A timeout for connect and write
834 IoHandler ioHandler_; ///< A EventHandler to monitor the fd
835 ImmediateReadCB immediateReadHandler_; ///< LoopCallback for checking read
837 ConnectCallback* connectCallback_; ///< ConnectCallback
838 ReadCallback* readCallback_; ///< ReadCallback
839 WriteRequest* writeReqHead_; ///< Chain of WriteRequests
840 WriteRequest* writeReqTail_; ///< End of WriteRequest chain
841 ShutdownSocketSet* shutdownSocketSet_;
842 size_t appBytesReceived_; ///< Num of bytes received from socket
843 size_t appBytesWritten_; ///< Num of bytes written to socket
844 bool isBufferMovable_{false};
846 bool peek_{false}; // Peek bytes.
848 int8_t readErr_{READ_NO_ERROR}; ///< The read error encountered, if any.
850 std::chrono::steady_clock::time_point connectStartTime_;
851 std::chrono::steady_clock::time_point connectEndTime_;
853 std::chrono::milliseconds connectTimeout_{0};
855 BufferCallback* bufferCallback_{nullptr};
858 #pragma vtordisp(pop)