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 <sys/types.h>
20 #include <sys/socket.h>
21 #include <folly/SocketAddress.h>
22 #include <folly/io/ShutdownSocketSet.h>
23 #include <folly/io/IOBuf.h>
24 #include <folly/io/async/AsyncTimeout.h>
25 #include <folly/io/async/AsyncSocketException.h>
26 #include <folly/io/async/AsyncTransport.h>
27 #include <folly/io/async/EventHandler.h>
28 #include <folly/io/async/DelayedDestruction.h>
37 * A class for performing asynchronous I/O on a socket.
39 * AsyncSocket allows users to asynchronously wait for data on a socket, and
40 * to asynchronously send data.
42 * The APIs for reading and writing are intentionally asymmetric. Waiting for
43 * data to read is a persistent API: a callback is installed, and is notified
44 * whenever new data is available. It continues to be notified of new events
45 * until it is uninstalled.
47 * AsyncSocket does not provide read timeout functionality, because it
48 * typically cannot determine when the timeout should be active. Generally, a
49 * timeout should only be enabled when processing is blocked waiting on data
50 * from the remote endpoint. For server sockets, the timeout should not be
51 * active if the server is currently processing one or more outstanding
52 * requests for this socket. For client sockets, the timeout should not be
53 * active if there are no requests pending on the socket. Additionally, if a
54 * client has multiple pending requests, it will ususally want a separate
55 * timeout for each request, rather than a single read timeout.
57 * The write API is fairly intuitive: a user can request to send a block of
58 * data, and a callback will be informed once the entire block has been
59 * transferred to the kernel, or on error. AsyncSocket does provide a send
60 * timeout, since most callers want to give up if the remote end stops
61 * responding and no further progress can be made sending the data.
65 // We do a dynamic_cast on this, in
66 // AsyncTransportWrapper::getUnderlyingTransport so be safe and
67 // force displacements for it. See:
68 // https://msdn.microsoft.com/en-us/library/7sf3txa8.aspx
69 #pragma vtordisp(push, 2)
71 class AsyncSocket : virtual public AsyncTransportWrapper {
73 typedef std::unique_ptr<AsyncSocket, Destructor> UniquePtr;
75 class ConnectCallback {
77 virtual ~ConnectCallback() = default;
80 * connectSuccess() will be invoked when the connection has been
81 * successfully established.
83 virtual void connectSuccess() noexcept = 0;
86 * connectErr() will be invoked if the connection attempt fails.
88 * @param ex An exception describing the error that occurred.
90 virtual void connectErr(const AsyncSocketException& ex)
94 explicit AsyncSocket();
96 * Create a new unconnected AsyncSocket.
98 * connect() must later be called on this socket to establish a connection.
100 explicit AsyncSocket(EventBase* evb);
102 void setShutdownSocketSet(ShutdownSocketSet* ss);
105 * Create a new AsyncSocket and begin the connection process.
107 * @param evb EventBase that will manage this socket.
108 * @param address The address to connect to.
109 * @param connectTimeout Optional timeout in milliseconds for the connection
112 AsyncSocket(EventBase* evb,
113 const folly::SocketAddress& address,
114 uint32_t connectTimeout = 0);
117 * Create a new AsyncSocket and begin the connection process.
119 * @param evb EventBase that will manage this socket.
120 * @param ip IP address to connect to (dotted-quad).
121 * @param port Destination port in host byte order.
122 * @param connectTimeout Optional timeout in milliseconds for the connection
125 AsyncSocket(EventBase* evb,
126 const std::string& ip,
128 uint32_t connectTimeout = 0);
131 * Create a AsyncSocket from an already connected socket file descriptor.
133 * Note that while AsyncSocket enables TCP_NODELAY for sockets it creates
134 * when connecting, it does not change the socket options when given an
135 * existing file descriptor. If callers want TCP_NODELAY enabled when using
136 * this version of the constructor, they need to explicitly call
137 * setNoDelay(true) after the constructor returns.
139 * @param evb EventBase that will manage this socket.
140 * @param fd File descriptor to take over (should be a connected socket).
142 AsyncSocket(EventBase* evb, int fd);
145 * Helper function to create a shared_ptr<AsyncSocket>.
147 * This passes in the correct destructor object, since AsyncSocket's
148 * destructor is protected and cannot be invoked directly.
150 static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb) {
151 return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb),
156 * Helper function to create a shared_ptr<AsyncSocket>.
158 static std::shared_ptr<AsyncSocket> newSocket(
160 const folly::SocketAddress& address,
161 uint32_t connectTimeout = 0) {
162 return std::shared_ptr<AsyncSocket>(
163 new AsyncSocket(evb, address, connectTimeout),
168 * Helper function to create a shared_ptr<AsyncSocket>.
170 static std::shared_ptr<AsyncSocket> newSocket(
172 const std::string& ip,
174 uint32_t connectTimeout = 0) {
175 return std::shared_ptr<AsyncSocket>(
176 new AsyncSocket(evb, ip, port, connectTimeout),
181 * Helper function to create a shared_ptr<AsyncSocket>.
183 static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb, int fd) {
184 return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb, fd),
189 * Destroy the socket.
191 * AsyncSocket::destroy() must be called to destroy the socket.
192 * The normal destructor is private, and should not be invoked directly.
193 * This prevents callers from deleting a AsyncSocket while it is invoking a
196 virtual void destroy() override;
199 * Get the EventBase used by this socket.
201 EventBase* getEventBase() const override {
206 * Get the file descriptor used by the AsyncSocket.
208 virtual int getFd() const {
213 * Extract the file descriptor from the AsyncSocket.
215 * This will immediately cause any installed callbacks to be invoked with an
216 * error. The AsyncSocket may no longer be used after the file descriptor
217 * has been extracted.
219 * Returns the file descriptor. The caller assumes ownership of the
220 * descriptor, and it will not be closed when the AsyncSocket is destroyed.
222 virtual int detachFd();
225 * Uniquely identifies a handle to a socket option value. Each
226 * combination of level and option name corresponds to one socket
231 bool operator<(const OptionKey& other) const {
232 if (level == other.level) {
233 return optname < other.optname;
235 return level < other.level;
237 int apply(int fd, int val) const {
238 return setsockopt(fd, level, optname, &val, sizeof(val));
244 // Maps from a socket option key to its value
245 typedef std::map<OptionKey, int> OptionMap;
247 static const OptionMap emptyOptionMap;
248 static const folly::SocketAddress& anyAddress();
251 * Initiate a connection.
253 * @param callback The callback to inform when the connection attempt
255 * @param address The address to connect to.
256 * @param timeout A timeout value, in milliseconds. If the connection
257 * does not succeed within this period,
258 * callback->connectError() will be invoked.
260 virtual void connect(ConnectCallback* callback,
261 const folly::SocketAddress& address,
263 const OptionMap &options = emptyOptionMap,
264 const folly::SocketAddress& bindAddr = anyAddress()
266 void connect(ConnectCallback* callback, const std::string& ip, uint16_t port,
268 const OptionMap &options = emptyOptionMap) noexcept;
271 * If a connect request is in-flight, cancels it and closes the socket
272 * immediately. Otherwise, this is a no-op.
274 * This does not invoke any connection related callbacks. Call this to
275 * prevent any connect callback while cleaning up, etc.
277 void cancelConnect();
280 * Set the send timeout.
282 * If write requests do not make any progress for more than the specified
283 * number of milliseconds, fail all pending writes and close the socket.
285 * If write requests are currently pending when setSendTimeout() is called,
286 * the timeout interval is immediately restarted using the new value.
288 * (See the comments for AsyncSocket for an explanation of why AsyncSocket
289 * provides setSendTimeout() but not setRecvTimeout().)
291 * @param milliseconds The timeout duration, in milliseconds. If 0, no
292 * timeout will be used.
294 void setSendTimeout(uint32_t milliseconds) override;
297 * Get the send timeout.
299 * @return Returns the current send timeout, in milliseconds. A return value
300 * of 0 indicates that no timeout is set.
302 uint32_t getSendTimeout() const override {
307 * Set the maximum number of reads to execute from the underlying
308 * socket each time the EventBase detects that new ingress data is
309 * available. The default is unlimited, but callers can use this method
310 * to limit the amount of data read from the socket per event loop
313 * @param maxReads Maximum number of reads per data-available event;
314 * a value of zero means unlimited.
316 void setMaxReadsPerEvent(uint16_t maxReads) {
317 maxReadsPerEvent_ = maxReads;
321 * Get the maximum number of reads this object will execute from
322 * the underlying socket each time the EventBase detects that new
323 * ingress data is available.
325 * @returns Maximum number of reads per data-available event; a value
326 * of zero means unlimited.
328 uint16_t getMaxReadsPerEvent() const {
329 return maxReadsPerEvent_;
332 // Read and write methods
333 void setReadCB(ReadCallback* callback) override;
334 ReadCallback* getReadCallback() const override;
336 void write(WriteCallback* callback, const void* buf, size_t bytes,
337 WriteFlags flags = WriteFlags::NONE) override;
338 void writev(WriteCallback* callback, const iovec* vec, size_t count,
339 WriteFlags flags = WriteFlags::NONE) override;
340 void writeChain(WriteCallback* callback,
341 std::unique_ptr<folly::IOBuf>&& buf,
342 WriteFlags flags = WriteFlags::NONE) override;
345 virtual void writeRequest(WriteRequest* req);
346 void writeRequestReady() {
350 // Methods inherited from AsyncTransport
351 void close() override;
352 void closeNow() override;
353 void closeWithReset() override;
354 void shutdownWrite() override;
355 void shutdownWriteNow() override;
357 bool readable() const override;
358 bool isPending() const override;
359 virtual bool hangup() const;
360 bool good() const override;
361 bool error() const override;
362 void attachEventBase(EventBase* eventBase) override;
363 void detachEventBase() override;
364 bool isDetachable() const override;
366 void getLocalAddress(
367 folly::SocketAddress* address) const override;
369 folly::SocketAddress* address) const override;
371 bool isEorTrackingEnabled() const override { return false; }
373 void setEorTracking(bool /*track*/) override {}
375 bool connecting() const override {
376 return (state_ == StateEnum::CONNECTING);
379 virtual bool isClosedByPeer() const {
380 return (state_ == StateEnum::CLOSED &&
381 (readErr_ == READ_EOF || readErr_ == READ_ERROR));
384 virtual bool isClosedBySelf() const {
385 return (state_ == StateEnum::CLOSED &&
386 (readErr_ != READ_EOF && readErr_ != READ_ERROR));
389 size_t getAppBytesWritten() const override {
390 return appBytesWritten_;
393 size_t getRawBytesWritten() const override {
394 return getAppBytesWritten();
397 size_t getAppBytesReceived() const override {
398 return appBytesReceived_;
401 size_t getRawBytesReceived() const override {
402 return getAppBytesReceived();
405 std::chrono::nanoseconds getConnectTime() const {
406 return connectEndTime_ - connectStartTime_;
409 // Methods controlling socket options
412 * Force writes to be transmitted immediately.
414 * This controls the TCP_NODELAY socket option. When enabled, TCP segments
415 * are sent as soon as possible, even if it is not a full frame of data.
416 * When disabled, the data may be buffered briefly to try and wait for a full
419 * By default, TCP_NODELAY is enabled for AsyncSocket objects.
421 * This method will fail if the socket is not currently open.
423 * @return Returns 0 if the TCP_NODELAY flag was successfully updated,
424 * or a non-zero errno value on error.
426 int setNoDelay(bool noDelay);
430 * Set the FD_CLOEXEC flag so that the socket will be closed if the program
431 * later forks and execs.
433 void setCloseOnExec();
436 * Set the Flavor of Congestion Control to be used for this Socket
437 * Please check '/lib/modules/<kernel>/kernel/net/ipv4' for tcp_*.ko
438 * first to make sure the module is available for plugging in
439 * Alternatively you can choose from net.ipv4.tcp_allowed_congestion_control
441 int setCongestionFlavor(const std::string &cname);
444 * Forces ACKs to be sent immediately
446 * @return Returns 0 if the TCP_QUICKACK flag was successfully updated,
447 * or a non-zero errno value on error.
449 int setQuickAck(bool quickack);
452 * Set the send bufsize
454 int setSendBufSize(size_t bufsize);
457 * Set the recv bufsize
459 int setRecvBufSize(size_t bufsize);
462 * Sets a specific tcp personality
463 * Available only on kernels 3.2 and greater
465 #define SO_SET_NAMESPACE 41
466 int setTCPProfile(int profd);
469 * Set TCP_CORK on the socket, and turn on/off the persistentCork_ flag
471 * When persistentCork_ is true, CorkGuard in AsyncSSLSocket will not be
472 * able to toggle TCP_CORK
475 void setPersistentCork(bool cork);
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 * A WriteRequest object tracks information about a pending write operation.
526 WriteRequest(AsyncSocket* socket, WriteCallback* callback) :
527 socket_(socket), callback_(callback) {}
529 virtual void start() {};
531 virtual void destroy() = 0;
533 virtual bool performWrite() = 0;
535 virtual void consume() = 0;
537 virtual bool isComplete() = 0;
539 WriteRequest* getNext() const {
543 WriteCallback* getCallback() const {
547 uint32_t getTotalBytesWritten() const {
548 return totalBytesWritten_;
551 void append(WriteRequest* next) {
552 assert(next_ == nullptr);
556 void fail(const char* fn, const AsyncSocketException& ex) {
557 socket_->failWrite(fn, ex);
560 void bytesWritten(size_t count) {
561 totalBytesWritten_ += count;
562 socket_->appBytesWritten_ += count;
566 // protected destructor, to ensure callers use destroy()
567 virtual ~WriteRequest() {}
569 AsyncSocket* socket_; ///< parent socket
570 WriteRequest* next_{nullptr}; ///< pointer to next WriteRequest
571 WriteCallback* callback_; ///< completion callback
572 uint32_t totalBytesWritten_{0}; ///< total bytes written
576 enum ReadResultEnum {
584 * Protected destructor.
586 * Users of AsyncSocket must never delete it directly. Instead, invoke
587 * destroy() instead. (See the documentation in DelayedDestruction.h for
592 friend std::ostream& operator << (std::ostream& os, const StateEnum& state);
595 /// shutdownWrite() called, but we are still waiting on writes to drain
596 SHUT_WRITE_PENDING = 0x01,
597 /// writes have been completely shut down
600 * Reads have been shutdown.
602 * At the moment we don't distinguish between remote read shutdown
603 * (received EOF from the remote end) and local read shutdown. We can
604 * only receive EOF when a read callback is set, and we immediately inform
605 * it of the EOF. Therefore there doesn't seem to be any reason to have a
606 * separate state of "received EOF but the local side may still want to
609 * We also don't currently provide any API for only shutting down the read
610 * side of a socket. (This is a no-op as far as TCP is concerned, anyway.)
615 class BytesWriteRequest;
617 class WriteTimeout : public AsyncTimeout {
619 WriteTimeout(AsyncSocket* socket, EventBase* eventBase)
620 : AsyncTimeout(eventBase)
623 virtual void timeoutExpired() noexcept {
624 socket_->timeoutExpired();
628 AsyncSocket* socket_;
631 class IoHandler : public EventHandler {
633 IoHandler(AsyncSocket* socket, EventBase* eventBase)
634 : EventHandler(eventBase, -1)
636 IoHandler(AsyncSocket* socket, EventBase* eventBase, int fd)
637 : EventHandler(eventBase, fd)
640 virtual void handlerReady(uint16_t events) noexcept {
641 socket_->ioReady(events);
645 AsyncSocket* socket_;
650 class ImmediateReadCB : public folly::EventBase::LoopCallback {
652 explicit ImmediateReadCB(AsyncSocket* socket) : socket_(socket) {}
653 void runLoopCallback() noexcept override {
654 DestructorGuard dg(socket_);
655 socket_->checkForImmediateRead();
658 AsyncSocket* socket_;
662 * Schedule checkForImmediateRead to be executed in the next loop
665 void scheduleImmediateRead() noexcept {
667 eventBase_->runInLoop(&immediateReadHandler_);
671 // event notification methods
672 void ioReady(uint16_t events) noexcept;
673 virtual void checkForImmediateRead() noexcept;
674 virtual void handleInitialReadWrite() noexcept;
675 virtual void prepareReadBuffer(void** buf, size_t* buflen) noexcept;
676 virtual void handleRead() noexcept;
677 virtual void handleWrite() noexcept;
678 virtual void handleConnect() noexcept;
679 void timeoutExpired() noexcept;
682 * Attempt to read from the socket.
684 * @param buf The buffer to read data into.
685 * @param buflen The length of the buffer.
687 * @return Returns the number of bytes read, or READ_EOF on EOF, or
688 * READ_ERROR on error, or READ_BLOCKING if the operation will
691 virtual ssize_t performRead(void** buf, size_t* buflen, size_t* offset);
694 * Populate an iovec array from an IOBuf and attempt to write it.
696 * @param callback Write completion/error callback.
697 * @param vec Target iovec array; caller retains ownership.
698 * @param count Number of IOBufs to write, beginning at start of buf.
699 * @param buf Chain of iovecs.
700 * @param flags set of flags for the underlying write calls, like cork
702 void writeChainImpl(WriteCallback* callback, iovec* vec,
703 size_t count, std::unique_ptr<folly::IOBuf>&& buf,
707 * Write as much data as possible to the socket without blocking,
708 * and queue up any leftover data to send when the socket can
709 * handle writes again.
711 * @param callback The callback to invoke when the write is completed.
712 * @param vec Array of buffers to write; this method will make a
713 * copy of the vector (but not the buffers themselves)
714 * if the write has to be completed asynchronously.
715 * @param count Number of elements in vec.
716 * @param buf The IOBuf that manages the buffers referenced by
717 * vec, or a pointer to nullptr if the buffers are not
718 * associated with an IOBuf. Note that ownership of
719 * the IOBuf is transferred here; upon completion of
720 * the write, the AsyncSocket deletes the IOBuf.
721 * @param flags Set of write flags.
723 void writeImpl(WriteCallback* callback, const iovec* vec, size_t count,
724 std::unique_ptr<folly::IOBuf>&& buf,
725 WriteFlags flags = WriteFlags::NONE);
728 * Attempt to write to the socket.
730 * @param vec The iovec array pointing to the buffers to write.
731 * @param count The length of the iovec array.
732 * @param flags Set of write flags.
733 * @param countWritten On return, the value pointed to by this parameter
734 * will contain the number of iovec entries that were
736 * @param partialWritten On return, the value pointed to by this parameter
737 * will contain the number of bytes written in the
738 * partially written iovec entry.
740 * @return Returns the total number of bytes written, or -1 on error. If no
741 * data can be written immediately, 0 is returned.
743 virtual ssize_t performWrite(const iovec* vec, uint32_t count,
744 WriteFlags flags, uint32_t* countWritten,
745 uint32_t* partialWritten);
747 bool updateEventRegistration();
750 * Update event registration.
752 * @param enable Flags of events to enable. Set it to 0 if no events
753 * need to be enabled in this call.
754 * @param disable Flags of events
755 * to disable. Set it to 0 if no events need to be disabled in this
758 * @return true iff the update is successful.
760 bool updateEventRegistration(uint16_t enable, uint16_t disable);
762 // Actually close the file descriptor and set it to -1 so we don't
763 // accidentally close it again.
766 // error handling methods
769 void fail(const char* fn, const AsyncSocketException& ex);
770 void failConnect(const char* fn, const AsyncSocketException& ex);
771 void failRead(const char* fn, const AsyncSocketException& ex);
772 void failWrite(const char* fn, WriteCallback* callback, size_t bytesWritten,
773 const AsyncSocketException& ex);
774 void failWrite(const char* fn, const AsyncSocketException& ex);
775 void failAllWrites(const AsyncSocketException& ex);
776 void invokeConnectErr(const AsyncSocketException& ex);
777 void invokeConnectSuccess();
778 void invalidState(ConnectCallback* callback);
779 void invalidState(ReadCallback* callback);
780 void invalidState(WriteCallback* callback);
782 std::string withAddr(const std::string& s);
785 * Set TCP_CORK on this socket
787 * @return 0 if Cork is turned on, or non-zero errno on error
789 int setCork(bool cork);
791 StateEnum state_; ///< StateEnum describing current state
792 uint8_t shutdownFlags_; ///< Shutdown state (ShutdownFlags)
793 uint16_t eventFlags_; ///< EventBase::HandlerFlags settings
794 int fd_; ///< The socket file descriptor
795 mutable folly::SocketAddress addr_; ///< The address we tried to connect to
796 mutable folly::SocketAddress localAddr_;
797 ///< The address we are connecting from
798 uint32_t sendTimeout_; ///< The send timeout, in milliseconds
799 uint16_t maxReadsPerEvent_; ///< Max reads per event loop iteration
800 EventBase* eventBase_; ///< The EventBase
801 WriteTimeout writeTimeout_; ///< A timeout for connect and write
802 IoHandler ioHandler_; ///< A EventHandler to monitor the fd
803 ImmediateReadCB immediateReadHandler_; ///< LoopCallback for checking read
805 ConnectCallback* connectCallback_; ///< ConnectCallback
806 ReadCallback* readCallback_; ///< ReadCallback
807 WriteRequest* writeReqHead_; ///< Chain of WriteRequests
808 WriteRequest* writeReqTail_; ///< End of WriteRequest chain
809 ShutdownSocketSet* shutdownSocketSet_;
810 size_t appBytesReceived_; ///< Num of bytes received from socket
811 size_t appBytesWritten_; ///< Num of bytes written to socket
812 bool isBufferMovable_{false};
814 bool peek_{false}; // Peek bytes.
816 int8_t readErr_{READ_NO_ERROR}; ///< The read error encountered, if any.
818 std::chrono::steady_clock::time_point connectStartTime_;
819 std::chrono::steady_clock::time_point connectEndTime_;
821 // Whether this connection is persistently corked
822 bool persistentCork_{false};
823 // Whether we've applied the TCP_CORK option to the socket
826 BufferCallback* bufferCallback_{nullptr};
829 #pragma vtordisp(pop)