2 * Copyright 2015 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 <sys/types.h>
20 #include <sys/socket.h>
21 #include <glog/logging.h>
22 #include <folly/SocketAddress.h>
23 #include <folly/io/ShutdownSocketSet.h>
24 #include <folly/io/IOBuf.h>
25 #include <folly/io/async/AsyncTimeout.h>
26 #include <folly/io/async/AsyncSocketException.h>
27 #include <folly/io/async/AsyncTransport.h>
28 #include <folly/io/async/EventHandler.h>
29 #include <folly/io/async/DelayedDestruction.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.
65 class AsyncSocket : virtual public AsyncTransportWrapper {
67 typedef std::unique_ptr<AsyncSocket, Destructor> UniquePtr;
69 class ConnectCallback {
71 virtual ~ConnectCallback() = default;
74 * connectSuccess() will be invoked when the connection has been
75 * successfully established.
77 virtual void connectSuccess() noexcept = 0;
80 * connectErr() will be invoked if the connection attempt fails.
82 * @param ex An exception describing the error that occurred.
84 virtual void connectErr(const AsyncSocketException& ex)
88 explicit AsyncSocket();
90 * Create a new unconnected AsyncSocket.
92 * connect() must later be called on this socket to establish a connection.
94 explicit AsyncSocket(EventBase* evb);
96 void setShutdownSocketSet(ShutdownSocketSet* ss);
99 * Create a new AsyncSocket and begin the connection process.
101 * @param evb EventBase that will manage this socket.
102 * @param address The address to connect to.
103 * @param connectTimeout Optional timeout in milliseconds for the connection
106 AsyncSocket(EventBase* evb,
107 const folly::SocketAddress& address,
108 uint32_t connectTimeout = 0);
111 * Create a new AsyncSocket and begin the connection process.
113 * @param evb EventBase that will manage this socket.
114 * @param ip IP address to connect to (dotted-quad).
115 * @param port Destination port in host byte order.
116 * @param connectTimeout Optional timeout in milliseconds for the connection
119 AsyncSocket(EventBase* evb,
120 const std::string& ip,
122 uint32_t connectTimeout = 0);
125 * Create a AsyncSocket from an already connected socket file descriptor.
127 * Note that while AsyncSocket enables TCP_NODELAY for sockets it creates
128 * when connecting, it does not change the socket options when given an
129 * existing file descriptor. If callers want TCP_NODELAY enabled when using
130 * this version of the constructor, they need to explicitly call
131 * setNoDelay(true) after the constructor returns.
133 * @param evb EventBase that will manage this socket.
134 * @param fd File descriptor to take over (should be a connected socket).
136 AsyncSocket(EventBase* evb, int fd);
139 * Helper function to create a shared_ptr<AsyncSocket>.
141 * This passes in the correct destructor object, since AsyncSocket's
142 * destructor is protected and cannot be invoked directly.
144 static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb) {
145 return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb),
150 * Helper function to create a shared_ptr<AsyncSocket>.
152 static std::shared_ptr<AsyncSocket> newSocket(
154 const folly::SocketAddress& address,
155 uint32_t connectTimeout = 0) {
156 return std::shared_ptr<AsyncSocket>(
157 new AsyncSocket(evb, address, connectTimeout),
162 * Helper function to create a shared_ptr<AsyncSocket>.
164 static std::shared_ptr<AsyncSocket> newSocket(
166 const std::string& ip,
168 uint32_t connectTimeout = 0) {
169 return std::shared_ptr<AsyncSocket>(
170 new AsyncSocket(evb, ip, port, connectTimeout),
175 * Helper function to create a shared_ptr<AsyncSocket>.
177 static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb, int fd) {
178 return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb, fd),
183 * Destroy the socket.
185 * AsyncSocket::destroy() must be called to destroy the socket.
186 * The normal destructor is private, and should not be invoked directly.
187 * This prevents callers from deleting a AsyncSocket while it is invoking a
190 virtual void destroy() override;
193 * Get the EventBase used by this socket.
195 EventBase* getEventBase() const override {
200 * Get the file descriptor used by the AsyncSocket.
202 virtual int getFd() const {
207 * Extract the file descriptor from the AsyncSocket.
209 * This will immediately cause any installed callbacks to be invoked with an
210 * error. The AsyncSocket may no longer be used after the file descriptor
211 * has been extracted.
213 * Returns the file descriptor. The caller assumes ownership of the
214 * descriptor, and it will not be closed when the AsyncSocket is destroyed.
216 virtual int detachFd();
219 * Uniquely identifies a handle to a socket option value. Each
220 * combination of level and option name corresponds to one socket
225 bool operator<(const OptionKey& other) const {
226 if (level == other.level) {
227 return optname < other.optname;
229 return level < other.level;
231 int apply(int fd, int val) const {
232 return setsockopt(fd, level, optname, &val, sizeof(val));
238 // Maps from a socket option key to its value
239 typedef std::map<OptionKey, int> OptionMap;
241 static const OptionMap emptyOptionMap;
242 static const folly::SocketAddress& anyAddress();
245 * Initiate a connection.
247 * @param callback The callback to inform when the connection attempt
249 * @param address The address to connect to.
250 * @param timeout A timeout value, in milliseconds. If the connection
251 * does not succeed within this period,
252 * callback->connectError() will be invoked.
254 virtual void connect(ConnectCallback* callback,
255 const folly::SocketAddress& address,
257 const OptionMap &options = emptyOptionMap,
258 const folly::SocketAddress& bindAddr = anyAddress()
260 void connect(ConnectCallback* callback, const std::string& ip, uint16_t port,
262 const OptionMap &options = emptyOptionMap) noexcept;
265 * If a connect request is in-flight, cancels it and closes the socket
266 * immediately. Otherwise, this is a no-op.
268 * This does not invoke any connection related callbacks. Call this to
269 * prevent any connect callback while cleaning up, etc.
271 void cancelConnect();
274 * Set the send timeout.
276 * If write requests do not make any progress for more than the specified
277 * number of milliseconds, fail all pending writes and close the socket.
279 * If write requests are currently pending when setSendTimeout() is called,
280 * the timeout interval is immediately restarted using the new value.
282 * (See the comments for AsyncSocket for an explanation of why AsyncSocket
283 * provides setSendTimeout() but not setRecvTimeout().)
285 * @param milliseconds The timeout duration, in milliseconds. If 0, no
286 * timeout will be used.
288 void setSendTimeout(uint32_t milliseconds) override;
291 * Get the send timeout.
293 * @return Returns the current send timeout, in milliseconds. A return value
294 * of 0 indicates that no timeout is set.
296 uint32_t getSendTimeout() const override {
301 * Set the maximum number of reads to execute from the underlying
302 * socket each time the EventBase detects that new ingress data is
303 * available. The default is unlimited, but callers can use this method
304 * to limit the amount of data read from the socket per event loop
307 * @param maxReads Maximum number of reads per data-available event;
308 * a value of zero means unlimited.
310 void setMaxReadsPerEvent(uint16_t maxReads) {
311 maxReadsPerEvent_ = maxReads;
315 * Get the maximum number of reads this object will execute from
316 * the underlying socket each time the EventBase detects that new
317 * ingress data is available.
319 * @returns Maximum number of reads per data-available event; a value
320 * of zero means unlimited.
322 uint16_t getMaxReadsPerEvent() const {
323 return maxReadsPerEvent_;
326 // Read and write methods
327 void setReadCB(ReadCallback* callback) override;
328 ReadCallback* getReadCallback() const override;
330 void write(WriteCallback* callback, const void* buf, size_t bytes,
331 WriteFlags flags = WriteFlags::NONE,
332 BufferCallback* bufCallback = nullptr) override;
333 void writev(WriteCallback* callback, const iovec* vec, size_t count,
334 WriteFlags flags = WriteFlags::NONE,
335 BufferCallback* bufCallback = nullptr) override;
336 void writeChain(WriteCallback* callback,
337 std::unique_ptr<folly::IOBuf>&& buf,
338 WriteFlags flags = WriteFlags::NONE,
339 BufferCallback* bufCallback = nullptr) override;
342 virtual void writeRequest(WriteRequest* req);
343 void writeRequestReady() {
347 // Methods inherited from AsyncTransport
348 void close() override;
349 void closeNow() override;
350 void closeWithReset() override;
351 void shutdownWrite() override;
352 void shutdownWriteNow() override;
354 bool readable() const override;
355 bool isPending() const override;
356 virtual bool hangup() const;
357 bool good() const override;
358 bool error() const override;
359 void attachEventBase(EventBase* eventBase) override;
360 void detachEventBase() override;
361 bool isDetachable() const override;
363 void getLocalAddress(
364 folly::SocketAddress* address) const override;
366 folly::SocketAddress* address) const override;
368 bool isEorTrackingEnabled() const override { return false; }
370 void setEorTracking(bool /*track*/) override {}
372 bool connecting() const override {
373 return (state_ == StateEnum::CONNECTING);
376 virtual bool isClosedByPeer() const {
377 return (state_ == StateEnum::CLOSED &&
378 (readErr_ == READ_EOF || readErr_ == READ_ERROR));
381 virtual bool isClosedBySelf() const {
382 return (state_ == StateEnum::CLOSED &&
383 (readErr_ != READ_EOF && readErr_ != READ_ERROR));
386 size_t getAppBytesWritten() const override {
387 return appBytesWritten_;
390 size_t getRawBytesWritten() const override {
391 return getAppBytesWritten();
394 size_t getAppBytesReceived() const override {
395 return appBytesReceived_;
398 size_t getRawBytesReceived() const override {
399 return getAppBytesReceived();
402 std::chrono::nanoseconds getConnectTime() const {
403 return connectEndTime_ - connectStartTime_;
406 // Methods controlling socket options
409 * Force writes to be transmitted immediately.
411 * This controls the TCP_NODELAY socket option. When enabled, TCP segments
412 * are sent as soon as possible, even if it is not a full frame of data.
413 * When disabled, the data may be buffered briefly to try and wait for a full
416 * By default, TCP_NODELAY is enabled for AsyncSocket objects.
418 * This method will fail if the socket is not currently open.
420 * @return Returns 0 if the TCP_NODELAY flag was successfully updated,
421 * or a non-zero errno value on error.
423 int setNoDelay(bool noDelay);
427 * Set the FD_CLOEXEC flag so that the socket will be closed if the program
428 * later forks and execs.
430 void setCloseOnExec();
433 * Set the Flavor of Congestion Control to be used for this Socket
434 * Please check '/lib/modules/<kernel>/kernel/net/ipv4' for tcp_*.ko
435 * first to make sure the module is available for plugging in
436 * Alternatively you can choose from net.ipv4.tcp_allowed_congestion_control
438 int setCongestionFlavor(const std::string &cname);
441 * Forces ACKs to be sent immediately
443 * @return Returns 0 if the TCP_QUICKACK flag was successfully updated,
444 * or a non-zero errno value on error.
446 int setQuickAck(bool quickack);
449 * Set the send bufsize
451 int setSendBufSize(size_t bufsize);
454 * Set the recv bufsize
456 int setRecvBufSize(size_t bufsize);
459 * Sets a specific tcp personality
460 * Available only on kernels 3.2 and greater
462 #define SO_SET_NAMESPACE 41
463 int setTCPProfile(int profd);
467 * Generic API for reading a socket option.
469 * @param level same as the "level" parameter in getsockopt().
470 * @param optname same as the "optname" parameter in getsockopt().
471 * @param optval pointer to the variable in which the option value should
473 * @param optlen value-result argument, initially containing the size of
474 * the buffer pointed to by optval, and modified on return
475 * to indicate the actual size of the value returned.
476 * @return same as the return value of getsockopt().
478 template <typename T>
479 int getSockOpt(int level, int optname, T* optval, socklen_t* optlen) {
480 return getsockopt(fd_, level, optname, (void*) optval, optlen);
484 * Generic API for setting a socket option.
486 * @param level same as the "level" parameter in getsockopt().
487 * @param optname same as the "optname" parameter in getsockopt().
488 * @param optval the option value to set.
489 * @return same as the return value of setsockopt().
491 template <typename T>
492 int setSockOpt(int level, int optname, const T *optval) {
493 return setsockopt(fd_, level, optname, optval, sizeof(T));
496 virtual void setPeek(bool peek) {
500 enum class StateEnum : uint8_t {
509 * A WriteRequest object tracks information about a pending write operation.
515 WriteCallback* callback,
516 BufferCallback* bufferCallback = nullptr) :
517 socket_(socket), callback_(callback), bufferCallback_(bufferCallback) {}
519 virtual void start() {};
521 virtual void destroy() = 0;
523 virtual bool performWrite() = 0;
525 virtual void consume() = 0;
527 virtual bool isComplete() = 0;
529 WriteRequest* getNext() const {
533 WriteCallback* getCallback() const {
537 uint32_t getTotalBytesWritten() const {
538 return totalBytesWritten_;
541 void append(WriteRequest* next) {
542 assert(next_ == nullptr);
546 void fail(const char* fn, const AsyncSocketException& ex) {
547 socket_->failWrite(fn, ex);
550 void bytesWritten(size_t count) {
551 totalBytesWritten_ += count;
552 socket_->appBytesWritten_ += count;
555 BufferCallback* getBufferCallback() const {
556 return bufferCallback_;
560 // protected destructor, to ensure callers use destroy()
561 virtual ~WriteRequest() {}
563 AsyncSocket* socket_; ///< parent socket
564 WriteRequest* next_{nullptr}; ///< pointer to next WriteRequest
565 WriteCallback* callback_; ///< completion callback
566 uint32_t totalBytesWritten_{0}; ///< total bytes written
567 BufferCallback* bufferCallback_{nullptr};
571 enum ReadResultEnum {
579 * Protected destructor.
581 * Users of AsyncSocket must never delete it directly. Instead, invoke
582 * destroy() instead. (See the documentation in DelayedDestruction.h for
587 friend std::ostream& operator << (std::ostream& os, const StateEnum& state);
590 /// shutdownWrite() called, but we are still waiting on writes to drain
591 SHUT_WRITE_PENDING = 0x01,
592 /// writes have been completely shut down
595 * Reads have been shutdown.
597 * At the moment we don't distinguish between remote read shutdown
598 * (received EOF from the remote end) and local read shutdown. We can
599 * only receive EOF when a read callback is set, and we immediately inform
600 * it of the EOF. Therefore there doesn't seem to be any reason to have a
601 * separate state of "received EOF but the local side may still want to
604 * We also don't currently provide any API for only shutting down the read
605 * side of a socket. (This is a no-op as far as TCP is concerned, anyway.)
610 class BytesWriteRequest;
612 class WriteTimeout : public AsyncTimeout {
614 WriteTimeout(AsyncSocket* socket, EventBase* eventBase)
615 : AsyncTimeout(eventBase)
618 virtual void timeoutExpired() noexcept {
619 socket_->timeoutExpired();
623 AsyncSocket* socket_;
626 class IoHandler : public EventHandler {
628 IoHandler(AsyncSocket* socket, EventBase* eventBase)
629 : EventHandler(eventBase, -1)
631 IoHandler(AsyncSocket* socket, EventBase* eventBase, int fd)
632 : EventHandler(eventBase, fd)
635 virtual void handlerReady(uint16_t events) noexcept {
636 socket_->ioReady(events);
640 AsyncSocket* socket_;
645 class ImmediateReadCB : public folly::EventBase::LoopCallback {
647 explicit ImmediateReadCB(AsyncSocket* socket) : socket_(socket) {}
648 void runLoopCallback() noexcept override {
649 DestructorGuard dg(socket_);
650 socket_->checkForImmediateRead();
653 AsyncSocket* socket_;
657 * Schedule checkForImmediateRead to be executed in the next loop
660 void scheduleImmediateRead() noexcept {
662 eventBase_->runInLoop(&immediateReadHandler_);
666 // event notification methods
667 void ioReady(uint16_t events) noexcept;
668 virtual void checkForImmediateRead() noexcept;
669 virtual void handleInitialReadWrite() noexcept;
670 virtual void prepareReadBuffer(void** buf, size_t* buflen) noexcept;
671 virtual void handleRead() noexcept;
672 virtual void handleWrite() noexcept;
673 virtual void handleConnect() noexcept;
674 void timeoutExpired() noexcept;
677 * Attempt to read from the socket.
679 * @param buf The buffer to read data into.
680 * @param buflen The length of the buffer.
682 * @return Returns the number of bytes read, or READ_EOF on EOF, or
683 * READ_ERROR on error, or READ_BLOCKING if the operation will
686 virtual ssize_t performRead(void** buf, size_t* buflen, size_t* offset);
689 * Populate an iovec array from an IOBuf and attempt to write it.
691 * @param callback Write completion/error callback.
692 * @param vec Target iovec array; caller retains ownership.
693 * @param count Number of IOBufs to write, beginning at start of buf.
694 * @param buf Chain of iovecs.
695 * @param flags set of flags for the underlying write calls, like cork
696 * @param bufCallback Callback when egress data begins to buffer
698 void writeChainImpl(WriteCallback* callback, iovec* vec,
699 size_t count, std::unique_ptr<folly::IOBuf>&& buf,
700 WriteFlags flags, BufferCallback* bufCallback = nullptr);
703 * Write as much data as possible to the socket without blocking,
704 * and queue up any leftover data to send when the socket can
705 * handle writes again.
707 * @param callback The callback to invoke when the write is completed.
708 * @param vec Array of buffers to write; this method will make a
709 * copy of the vector (but not the buffers themselves)
710 * if the write has to be completed asynchronously.
711 * @param count Number of elements in vec.
712 * @param buf The IOBuf that manages the buffers referenced by
713 * vec, or a pointer to nullptr if the buffers are not
714 * associated with an IOBuf. Note that ownership of
715 * the IOBuf is transferred here; upon completion of
716 * the write, the AsyncSocket deletes the IOBuf.
717 * @param flags Set of write flags.
718 * @param bufCallback Callback when egress data buffers up
720 void writeImpl(WriteCallback* callback, const iovec* vec, size_t count,
721 std::unique_ptr<folly::IOBuf>&& buf,
722 WriteFlags flags = WriteFlags::NONE,
723 BufferCallback* bufCallback = nullptr);
726 * Attempt to write to the socket.
728 * @param vec The iovec array pointing to the buffers to write.
729 * @param count The length of the iovec array.
730 * @param flags Set of write flags.
731 * @param countWritten On return, the value pointed to by this parameter
732 * will contain the number of iovec entries that were
734 * @param partialWritten On return, the value pointed to by this parameter
735 * will contain the number of bytes written in the
736 * partially written iovec entry.
738 * @return Returns the total number of bytes written, or -1 on error. If no
739 * data can be written immediately, 0 is returned.
741 virtual ssize_t performWrite(const iovec* vec, uint32_t count,
742 WriteFlags flags, uint32_t* countWritten,
743 uint32_t* partialWritten);
745 bool updateEventRegistration();
748 * Update event registration.
750 * @param enable Flags of events to enable. Set it to 0 if no events
751 * need to be enabled in this call.
752 * @param disable Flags of events
753 * to disable. Set it to 0 if no events need to be disabled in this
756 * @return true iff the update is successful.
758 bool updateEventRegistration(uint16_t enable, uint16_t disable);
760 // Actually close the file descriptor and set it to -1 so we don't
761 // accidentally close it again.
764 // error handling methods
767 void fail(const char* fn, const AsyncSocketException& ex);
768 void failConnect(const char* fn, const AsyncSocketException& ex);
769 void failRead(const char* fn, const AsyncSocketException& ex);
770 void failWrite(const char* fn, WriteCallback* callback, size_t bytesWritten,
771 const AsyncSocketException& ex);
772 void failWrite(const char* fn, const AsyncSocketException& ex);
773 void failAllWrites(const AsyncSocketException& ex);
774 void invokeConnectErr(const AsyncSocketException& ex);
775 void invokeConnectSuccess();
776 void invalidState(ConnectCallback* callback);
777 void invalidState(ReadCallback* callback);
778 void invalidState(WriteCallback* callback);
780 std::string withAddr(const std::string& s);
782 StateEnum state_; ///< StateEnum describing current state
783 uint8_t shutdownFlags_; ///< Shutdown state (ShutdownFlags)
784 uint16_t eventFlags_; ///< EventBase::HandlerFlags settings
785 int fd_; ///< The socket file descriptor
787 folly::SocketAddress addr_; ///< The address we tried to connect to
788 uint32_t sendTimeout_; ///< The send timeout, in milliseconds
789 uint16_t maxReadsPerEvent_; ///< Max reads per event loop iteration
790 EventBase* eventBase_; ///< The EventBase
791 WriteTimeout writeTimeout_; ///< A timeout for connect and write
792 IoHandler ioHandler_; ///< A EventHandler to monitor the fd
793 ImmediateReadCB immediateReadHandler_; ///< LoopCallback for checking read
795 ConnectCallback* connectCallback_; ///< ConnectCallback
796 ReadCallback* readCallback_; ///< ReadCallback
797 WriteRequest* writeReqHead_; ///< Chain of WriteRequests
798 WriteRequest* writeReqTail_; ///< End of WriteRequest chain
799 ShutdownSocketSet* shutdownSocketSet_;
800 size_t appBytesReceived_; ///< Num of bytes received from socket
801 size_t appBytesWritten_; ///< Num of bytes written to socket
802 bool isBufferMovable_{false};
804 bool peek_{false}; // Peek bytes.
806 int8_t readErr_{READ_NO_ERROR}; ///< The read error encountered, if any.
808 std::chrono::steady_clock::time_point connectStartTime_;
809 std::chrono::steady_clock::time_point connectEndTime_;