2 * Copyright 2014 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>
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.
64 class AsyncSocket : virtual public AsyncTransport {
66 typedef std::unique_ptr<AsyncSocket, Destructor> UniquePtr;
68 class ConnectCallback {
70 virtual ~ConnectCallback() {}
73 * connectSuccess() will be invoked when the connection has been
74 * successfully established.
76 virtual void connectSuccess() noexcept = 0;
79 * connectErr() will be invoked if the connection attempt fails.
81 * @param ex An exception describing the error that occurred.
83 virtual void connectErr(const AsyncSocketException& ex)
89 virtual ~ReadCallback() {}
92 * When data becomes available, getReadBuffer() will be invoked to get the
93 * buffer into which data should be read.
95 * This method allows the ReadCallback to delay buffer allocation until
96 * data becomes available. This allows applications to manage large
97 * numbers of idle connections, without having to maintain a separate read
98 * buffer for each idle connection.
100 * It is possible that in some cases, getReadBuffer() may be called
101 * multiple times before readDataAvailable() is invoked. In this case, the
102 * data will be written to the buffer returned from the most recent call to
103 * readDataAvailable(). If the previous calls to readDataAvailable()
104 * returned different buffers, the ReadCallback is responsible for ensuring
105 * that they are not leaked.
107 * If getReadBuffer() throws an exception, returns a nullptr buffer, or
108 * returns a 0 length, the ReadCallback will be uninstalled and its
109 * readError() method will be invoked.
111 * getReadBuffer() is not allowed to change the transport state before it
112 * returns. (For example, it should never uninstall the read callback, or
113 * set a different read callback.)
115 * @param bufReturn getReadBuffer() should update *bufReturn to contain the
116 * address of the read buffer. This parameter will never
118 * @param lenReturn getReadBuffer() should update *lenReturn to contain the
119 * maximum number of bytes that may be written to the read
120 * buffer. This parameter will never be nullptr.
122 virtual void getReadBuffer(void** bufReturn, size_t* lenReturn) = 0;
125 * readDataAvailable() will be invoked when data has been successfully read
126 * into the buffer returned by the last call to getReadBuffer().
128 * The read callback remains installed after readDataAvailable() returns.
129 * It must be explicitly uninstalled to stop receiving read events.
130 * getReadBuffer() will be called at least once before each call to
131 * readDataAvailable(). getReadBuffer() will also be called before any
134 * @param len The number of bytes placed in the buffer.
136 virtual void readDataAvailable(size_t len) noexcept = 0;
139 * readEOF() will be invoked when the transport is closed.
141 * The read callback will be automatically uninstalled immediately before
142 * readEOF() is invoked.
144 virtual void readEOF() noexcept = 0;
147 * readError() will be invoked if an error occurs reading from the
150 * The read callback will be automatically uninstalled immediately before
151 * readError() is invoked.
153 * @param ex An exception describing the error that occurred.
155 virtual void readErr(const AsyncSocketException& ex)
159 class WriteCallback {
161 virtual ~WriteCallback() {}
164 * writeSuccess() will be invoked when all of the data has been
165 * successfully written.
167 * Note that this mainly signals that the buffer containing the data to
168 * write is no longer needed and may be freed or re-used. It does not
169 * guarantee that the data has been fully transmitted to the remote
170 * endpoint. For example, on socket-based transports, writeSuccess() only
171 * indicates that the data has been given to the kernel for eventual
174 virtual void writeSuccess() noexcept = 0;
177 * writeError() will be invoked if an error occurs writing the data.
179 * @param bytesWritten The number of bytes that were successfull
180 * @param ex An exception describing the error that occurred.
182 virtual void writeErr(size_t bytesWritten,
183 const AsyncSocketException& ex)
188 * Create a new unconnected AsyncSocket.
190 * connect() must later be called on this socket to establish a connection.
192 explicit AsyncSocket(EventBase* evb);
194 void setShutdownSocketSet(ShutdownSocketSet* ss);
197 * Create a new AsyncSocket and begin the connection process.
199 * @param evb EventBase that will manage this socket.
200 * @param address The address to connect to.
201 * @param connectTimeout Optional timeout in milliseconds for the connection
204 AsyncSocket(EventBase* evb,
205 const folly::SocketAddress& address,
206 uint32_t connectTimeout = 0);
209 * Create a new AsyncSocket and begin the connection process.
211 * @param evb EventBase that will manage this socket.
212 * @param ip IP address to connect to (dotted-quad).
213 * @param port Destination port in host byte order.
214 * @param connectTimeout Optional timeout in milliseconds for the connection
217 AsyncSocket(EventBase* evb,
218 const std::string& ip,
220 uint32_t connectTimeout = 0);
223 * Create a AsyncSocket from an already connected socket file descriptor.
225 * Note that while AsyncSocket enables TCP_NODELAY for sockets it creates
226 * when connecting, it does not change the socket options when given an
227 * existing file descriptor. If callers want TCP_NODELAY enabled when using
228 * this version of the constructor, they need to explicitly call
229 * setNoDelay(true) after the constructor returns.
231 * @param evb EventBase that will manage this socket.
232 * @param fd File descriptor to take over (should be a connected socket).
234 AsyncSocket(EventBase* evb, int fd);
237 * Helper function to create a shared_ptr<AsyncSocket>.
239 * This passes in the correct destructor object, since AsyncSocket's
240 * destructor is protected and cannot be invoked directly.
242 static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb) {
243 return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb),
248 * Helper function to create a shared_ptr<AsyncSocket>.
250 static std::shared_ptr<AsyncSocket> newSocket(
252 const folly::SocketAddress& address,
253 uint32_t connectTimeout = 0) {
254 return std::shared_ptr<AsyncSocket>(
255 new AsyncSocket(evb, address, connectTimeout),
260 * Helper function to create a shared_ptr<AsyncSocket>.
262 static std::shared_ptr<AsyncSocket> newSocket(
264 const std::string& ip,
266 uint32_t connectTimeout = 0) {
267 return std::shared_ptr<AsyncSocket>(
268 new AsyncSocket(evb, ip, port, connectTimeout),
273 * Helper function to create a shared_ptr<AsyncSocket>.
275 static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb, int fd) {
276 return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb, fd),
281 * Destroy the socket.
283 * AsyncSocket::destroy() must be called to destroy the socket.
284 * The normal destructor is private, and should not be invoked directly.
285 * This prevents callers from deleting a AsyncSocket while it is invoking a
288 virtual void destroy();
291 * Get the EventBase used by this socket.
293 EventBase* getEventBase() const override {
298 * Get the file descriptor used by the AsyncSocket.
300 virtual int getFd() const {
305 * Extract the file descriptor from the AsyncSocket.
307 * This will immediately cause any installed callbacks to be invoked with an
308 * error. The AsyncSocket may no longer be used after the file descriptor
309 * has been extracted.
311 * Returns the file descriptor. The caller assumes ownership of the
312 * descriptor, and it will not be closed when the AsyncSocket is destroyed.
314 virtual int detachFd();
317 * Uniquely identifies a handle to a socket option value. Each
318 * combination of level and option name corresponds to one socket
323 bool operator<(const OptionKey& other) const {
324 if (level == other.level) {
325 return optname < other.optname;
327 return level < other.level;
329 int apply(int fd, int val) const {
330 return setsockopt(fd, level, optname, &val, sizeof(val));
336 // Maps from a socket option key to its value
337 typedef std::map<OptionKey, int> OptionMap;
339 static const OptionMap emptyOptionMap;
340 static const folly::SocketAddress anyAddress;
343 * Initiate a connection.
345 * @param callback The callback to inform when the connection attempt
347 * @param address The address to connect to.
348 * @param timeout A timeout value, in milliseconds. If the connection
349 * does not succeed within this period,
350 * callback->connectError() will be invoked.
352 virtual void connect(ConnectCallback* callback,
353 const folly::SocketAddress& address,
355 const OptionMap &options = emptyOptionMap,
356 const folly::SocketAddress& bindAddr = anyAddress
358 void connect(ConnectCallback* callback, const std::string& ip, uint16_t port,
360 const OptionMap &options = emptyOptionMap) noexcept;
363 * Set the send timeout.
365 * If write requests do not make any progress for more than the specified
366 * number of milliseconds, fail all pending writes and close the socket.
368 * If write requests are currently pending when setSendTimeout() is called,
369 * the timeout interval is immediately restarted using the new value.
371 * (See the comments for AsyncSocket for an explanation of why AsyncSocket
372 * provides setSendTimeout() but not setRecvTimeout().)
374 * @param milliseconds The timeout duration, in milliseconds. If 0, no
375 * timeout will be used.
377 void setSendTimeout(uint32_t milliseconds) override;
380 * Get the send timeout.
382 * @return Returns the current send timeout, in milliseconds. A return value
383 * of 0 indicates that no timeout is set.
385 uint32_t getSendTimeout() const override {
390 * Set the maximum number of reads to execute from the underlying
391 * socket each time the EventBase detects that new ingress data is
392 * available. The default is unlimited, but callers can use this method
393 * to limit the amount of data read from the socket per event loop
396 * @param maxReads Maximum number of reads per data-available event;
397 * a value of zero means unlimited.
399 void setMaxReadsPerEvent(uint16_t maxReads) {
400 maxReadsPerEvent_ = maxReads;
404 * Get the maximum number of reads this object will execute from
405 * the underlying socket each time the EventBase detects that new
406 * ingress data is available.
408 * @returns Maximum number of reads per data-available event; a value
409 * of zero means unlimited.
411 uint16_t getMaxReadsPerEvent() const {
412 return maxReadsPerEvent_;
415 // Read and write methods
416 void setReadCB(ReadCallback* callback);
417 ReadCallback* getReadCallback() const;
419 void write(WriteCallback* callback, const void* buf, size_t bytes,
420 WriteFlags flags = WriteFlags::NONE);
421 void writev(WriteCallback* callback, const iovec* vec, size_t count,
422 WriteFlags flags = WriteFlags::NONE);
423 void writeChain(WriteCallback* callback,
424 std::unique_ptr<folly::IOBuf>&& buf,
425 WriteFlags flags = WriteFlags::NONE);
427 // Methods inherited from AsyncTransport
428 void close() override;
429 void closeNow() override;
430 void closeWithReset() override;
431 void shutdownWrite() override;
432 void shutdownWriteNow() override;
434 bool readable() const override;
435 bool isPending() const override;
436 virtual bool hangup() const;
437 bool good() const override;
438 bool error() const override;
439 void attachEventBase(EventBase* eventBase) override;
440 void detachEventBase() override;
441 bool isDetachable() const override;
443 void getLocalAddress(
444 folly::SocketAddress* address) const override;
446 folly::SocketAddress* address) const override;
448 bool isEorTrackingEnabled() const override { return false; }
450 void setEorTracking(bool track) override {}
452 bool connecting() const override {
453 return (state_ == StateEnum::CONNECTING);
456 size_t getAppBytesWritten() const override {
457 return appBytesWritten_;
460 size_t getRawBytesWritten() const override {
461 return getAppBytesWritten();
464 size_t getAppBytesReceived() const override {
465 return appBytesReceived_;
468 size_t getRawBytesReceived() const override {
469 return getAppBytesReceived();
472 // Methods controlling socket options
475 * Force writes to be transmitted immediately.
477 * This controls the TCP_NODELAY socket option. When enabled, TCP segments
478 * are sent as soon as possible, even if it is not a full frame of data.
479 * When disabled, the data may be buffered briefly to try and wait for a full
482 * By default, TCP_NODELAY is enabled for AsyncSocket objects.
484 * This method will fail if the socket is not currently open.
486 * @return Returns 0 if the TCP_NODELAY flag was successfully updated,
487 * or a non-zero errno value on error.
489 int setNoDelay(bool noDelay);
492 * Set the Flavor of Congestion Control to be used for this Socket
493 * Please check '/lib/modules/<kernel>/kernel/net/ipv4' for tcp_*.ko
494 * first to make sure the module is available for plugging in
495 * Alternatively you can choose from net.ipv4.tcp_allowed_congestion_control
497 int setCongestionFlavor(const std::string &cname);
500 * Forces ACKs to be sent immediately
502 * @return Returns 0 if the TCP_QUICKACK flag was successfully updated,
503 * or a non-zero errno value on error.
505 int setQuickAck(bool quickack);
508 * Set the send bufsize
510 int setSendBufSize(size_t bufsize);
513 * Set the recv bufsize
515 int setRecvBufSize(size_t bufsize);
518 * Sets a specific tcp personality
519 * Available only on kernels 3.2 and greater
521 #define SO_SET_NAMESPACE 41
522 int setTCPProfile(int profd);
526 * Generic API for reading a socket option.
528 * @param level same as the "level" parameter in getsockopt().
529 * @param optname same as the "optname" parameter in getsockopt().
530 * @param optval pointer to the variable in which the option value should
532 * @return same as the return value of getsockopt().
534 template <typename T>
535 int getSockOpt(int level, int optname, T *optval) {
536 return getsockopt(fd_, level, optname, optval, sizeof(T));
540 * Generic API for setting a socket option.
542 * @param level same as the "level" parameter in getsockopt().
543 * @param optname same as the "optname" parameter in getsockopt().
544 * @param optval the option value to set.
545 * @return same as the return value of setsockopt().
547 template <typename T>
548 int setSockOpt(int level, int optname, const T *optval) {
549 return setsockopt(fd_, level, optname, optval, sizeof(T));
553 enum ReadResultEnum {
560 * Protected destructor.
562 * Users of AsyncSocket must never delete it directly. Instead, invoke
563 * destroy() instead. (See the documentation in DelayedDestruction.h for
568 enum class StateEnum : uint8_t {
576 friend std::ostream& operator << (std::ostream& os, const StateEnum& state);
579 /// shutdownWrite() called, but we are still waiting on writes to drain
580 SHUT_WRITE_PENDING = 0x01,
581 /// writes have been completely shut down
584 * Reads have been shutdown.
586 * At the moment we don't distinguish between remote read shutdown
587 * (received EOF from the remote end) and local read shutdown. We can
588 * only receive EOF when a read callback is set, and we immediately inform
589 * it of the EOF. Therefore there doesn't seem to be any reason to have a
590 * separate state of "received EOF but the local side may still want to
593 * We also don't currently provide any API for only shutting down the read
594 * side of a socket. (This is a no-op as far as TCP is concerned, anyway.)
601 class WriteTimeout : public AsyncTimeout {
603 WriteTimeout(AsyncSocket* socket, EventBase* eventBase)
604 : AsyncTimeout(eventBase)
607 virtual void timeoutExpired() noexcept {
608 socket_->timeoutExpired();
612 AsyncSocket* socket_;
615 class IoHandler : public EventHandler {
617 IoHandler(AsyncSocket* socket, EventBase* eventBase)
618 : EventHandler(eventBase, -1)
620 IoHandler(AsyncSocket* socket, EventBase* eventBase, int fd)
621 : EventHandler(eventBase, fd)
624 virtual void handlerReady(uint16_t events) noexcept {
625 socket_->ioReady(events);
629 AsyncSocket* socket_;
634 // event notification methods
635 void ioReady(uint16_t events) noexcept;
636 virtual void checkForImmediateRead() noexcept;
637 virtual void handleInitialReadWrite() noexcept;
638 virtual void handleRead() noexcept;
639 virtual void handleWrite() noexcept;
640 virtual void handleConnect() noexcept;
641 void timeoutExpired() noexcept;
644 * Attempt to read from the socket.
646 * @param buf The buffer to read data into.
647 * @param buflen The length of the buffer.
649 * @return Returns the number of bytes read, or READ_EOF on EOF, or
650 * READ_ERROR on error, or READ_BLOCKING if the operation will
653 virtual ssize_t performRead(void* buf, size_t buflen);
656 * Populate an iovec array from an IOBuf and attempt to write it.
658 * @param callback Write completion/error callback.
659 * @param vec Target iovec array; caller retains ownership.
660 * @param count Number of IOBufs to write, beginning at start of buf.
661 * @param buf Chain of iovecs.
662 * @param flags set of flags for the underlying write calls, like cork
664 void writeChainImpl(WriteCallback* callback, iovec* vec,
665 size_t count, std::unique_ptr<folly::IOBuf>&& buf,
669 * Write as much data as possible to the socket without blocking,
670 * and queue up any leftover data to send when the socket can
671 * handle writes again.
673 * @param callback The callback to invoke when the write is completed.
674 * @param vec Array of buffers to write; this method will make a
675 * copy of the vector (but not the buffers themselves)
676 * if the write has to be completed asynchronously.
677 * @param count Number of elements in vec.
678 * @param buf The IOBuf that manages the buffers referenced by
679 * vec, or a pointer to nullptr if the buffers are not
680 * associated with an IOBuf. Note that ownership of
681 * the IOBuf is transferred here; upon completion of
682 * the write, the AsyncSocket deletes the IOBuf.
683 * @param flags Set of write flags.
685 void writeImpl(WriteCallback* callback, const iovec* vec, size_t count,
686 std::unique_ptr<folly::IOBuf>&& buf,
687 WriteFlags flags = WriteFlags::NONE);
690 * Attempt to write to the socket.
692 * @param vec The iovec array pointing to the buffers to write.
693 * @param count The length of the iovec array.
694 * @param flags Set of write flags.
695 * @param countWritten On return, the value pointed to by this parameter
696 * will contain the number of iovec entries that were
698 * @param partialWritten On return, the value pointed to by this parameter
699 * will contain the number of bytes written in the
700 * partially written iovec entry.
702 * @return Returns the total number of bytes written, or -1 on error. If no
703 * data can be written immediately, 0 is returned.
705 virtual ssize_t performWrite(const iovec* vec, uint32_t count,
706 WriteFlags flags, uint32_t* countWritten,
707 uint32_t* partialWritten);
709 bool updateEventRegistration();
712 * Update event registration.
714 * @param enable Flags of events to enable. Set it to 0 if no events
715 * need to be enabled in this call.
716 * @param disable Flags of events
717 * to disable. Set it to 0 if no events need to be disabled in this
720 * @return true iff the update is successful.
722 bool updateEventRegistration(uint16_t enable, uint16_t disable);
724 // Actually close the file descriptor and set it to -1 so we don't
725 // accidentally close it again.
728 // error handling methods
731 void fail(const char* fn, const AsyncSocketException& ex);
732 void failConnect(const char* fn, const AsyncSocketException& ex);
733 void failRead(const char* fn, const AsyncSocketException& ex);
734 void failWrite(const char* fn, WriteCallback* callback, size_t bytesWritten,
735 const AsyncSocketException& ex);
736 void failWrite(const char* fn, const AsyncSocketException& ex);
737 void failAllWrites(const AsyncSocketException& ex);
738 void invalidState(ConnectCallback* callback);
739 void invalidState(ReadCallback* callback);
740 void invalidState(WriteCallback* callback);
742 std::string withAddr(const std::string& s);
744 StateEnum state_; ///< StateEnum describing current state
745 uint8_t shutdownFlags_; ///< Shutdown state (ShutdownFlags)
746 uint16_t eventFlags_; ///< EventBase::HandlerFlags settings
747 int fd_; ///< The socket file descriptor
749 folly::SocketAddress addr_; ///< The address we tried to connect to
750 uint32_t sendTimeout_; ///< The send timeout, in milliseconds
751 uint16_t maxReadsPerEvent_; ///< Max reads per event loop iteration
752 EventBase* eventBase_; ///< The EventBase
753 WriteTimeout writeTimeout_; ///< A timeout for connect and write
754 IoHandler ioHandler_; ///< A EventHandler to monitor the fd
756 ConnectCallback* connectCallback_; ///< ConnectCallback
757 ReadCallback* readCallback_; ///< ReadCallback
758 WriteRequest* writeReqHead_; ///< Chain of WriteRequests
759 WriteRequest* writeReqTail_; ///< End of WriteRequest chain
760 ShutdownSocketSet* shutdownSocketSet_;
761 size_t appBytesReceived_; ///< Num of bytes received from socket
762 size_t appBytesWritten_; ///< Num of bytes written to socket