2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <folly/Optional.h>
20 #include <folly/SocketAddress.h>
21 #include <folly/detail/SocketFastOpen.h>
22 #include <folly/io/IOBuf.h>
23 #include <folly/io/ShutdownSocketSet.h>
24 #include <folly/io/async/AsyncSocketException.h>
25 #include <folly/io/async/AsyncTimeout.h>
26 #include <folly/io/async/AsyncTransport.h>
27 #include <folly/io/async/DelayedDestruction.h>
28 #include <folly/io/async/EventHandler.h>
29 #include <folly/portability/Sockets.h>
31 #include <sys/types.h>
40 * A class for performing asynchronous I/O on a socket.
42 * AsyncSocket allows users to asynchronously wait for data on a socket, and
43 * to asynchronously send data.
45 * The APIs for reading and writing are intentionally asymmetric. Waiting for
46 * data to read is a persistent API: a callback is installed, and is notified
47 * whenever new data is available. It continues to be notified of new events
48 * until it is uninstalled.
50 * AsyncSocket does not provide read timeout functionality, because it
51 * typically cannot determine when the timeout should be active. Generally, a
52 * timeout should only be enabled when processing is blocked waiting on data
53 * from the remote endpoint. For server sockets, the timeout should not be
54 * active if the server is currently processing one or more outstanding
55 * requests for this socket. For client sockets, the timeout should not be
56 * active if there are no requests pending on the socket. Additionally, if a
57 * client has multiple pending requests, it will ususally want a separate
58 * timeout for each request, rather than a single read timeout.
60 * The write API is fairly intuitive: a user can request to send a block of
61 * data, and a callback will be informed once the entire block has been
62 * transferred to the kernel, or on error. AsyncSocket does provide a send
63 * timeout, since most callers want to give up if the remote end stops
64 * responding and no further progress can be made sending the data.
67 #if defined __linux__ && !defined SO_NO_TRANSPARENT_TLS
68 #define SO_NO_TRANSPARENT_TLS 200
72 // We do a dynamic_cast on this, in
73 // AsyncTransportWrapper::getUnderlyingTransport so be safe and
74 // force displacements for it. See:
75 // https://msdn.microsoft.com/en-us/library/7sf3txa8.aspx
76 #pragma vtordisp(push, 2)
78 class AsyncSocket : virtual public AsyncTransportWrapper {
80 typedef std::unique_ptr<AsyncSocket, Destructor> UniquePtr;
82 class ConnectCallback {
84 virtual ~ConnectCallback() = default;
87 * connectSuccess() will be invoked when the connection has been
88 * successfully established.
90 virtual void connectSuccess() noexcept = 0;
93 * connectErr() will be invoked if the connection attempt fails.
95 * @param ex An exception describing the error that occurred.
97 virtual void connectErr(const AsyncSocketException& ex)
101 class EvbChangeCallback {
103 virtual ~EvbChangeCallback() = default;
105 // Called when the socket has been attached to a new EVB
106 // and is called from within that EVB thread
107 virtual void evbAttached(AsyncSocket* socket) = 0;
109 // Called when the socket is detached from an EVB and
110 // is called from the EVB thread being detached
111 virtual void evbDetached(AsyncSocket* socket) = 0;
115 * This interface is implemented only for platforms supporting
116 * per-socket error queues.
118 class ErrMessageCallback {
120 virtual ~ErrMessageCallback() = default;
123 * errMessage() will be invoked when kernel puts a message to
124 * the error queue associated with the socket.
126 * @param cmsg Reference to cmsghdr structure describing
127 * a message read from error queue associated
131 errMessage(const cmsghdr& cmsg) noexcept = 0;
134 * errMessageError() will be invoked if an error occurs reading a message
135 * from the socket error stream.
137 * @param ex An exception describing the error that occurred.
139 virtual void errMessageError(const AsyncSocketException& ex) noexcept = 0;
142 explicit AsyncSocket();
144 * Create a new unconnected AsyncSocket.
146 * connect() must later be called on this socket to establish a connection.
148 explicit AsyncSocket(EventBase* evb);
150 void setShutdownSocketSet(ShutdownSocketSet* ss);
153 * Create a new AsyncSocket and begin the connection process.
155 * @param evb EventBase that will manage this socket.
156 * @param address The address to connect to.
157 * @param connectTimeout Optional timeout in milliseconds for the connection
160 AsyncSocket(EventBase* evb,
161 const folly::SocketAddress& address,
162 uint32_t connectTimeout = 0);
165 * Create a new AsyncSocket and begin the connection process.
167 * @param evb EventBase that will manage this socket.
168 * @param ip IP address to connect to (dotted-quad).
169 * @param port Destination port in host byte order.
170 * @param connectTimeout Optional timeout in milliseconds for the connection
173 AsyncSocket(EventBase* evb,
174 const std::string& ip,
176 uint32_t connectTimeout = 0);
179 * Create a AsyncSocket from an already connected socket file descriptor.
181 * Note that while AsyncSocket enables TCP_NODELAY for sockets it creates
182 * when connecting, it does not change the socket options when given an
183 * existing file descriptor. If callers want TCP_NODELAY enabled when using
184 * this version of the constructor, they need to explicitly call
185 * setNoDelay(true) after the constructor returns.
187 * @param evb EventBase that will manage this socket.
188 * @param fd File descriptor to take over (should be a connected socket).
190 AsyncSocket(EventBase* evb, int fd);
193 * Helper function to create a shared_ptr<AsyncSocket>.
195 * This passes in the correct destructor object, since AsyncSocket's
196 * destructor is protected and cannot be invoked directly.
198 static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb) {
199 return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb),
204 * Helper function to create a shared_ptr<AsyncSocket>.
206 static std::shared_ptr<AsyncSocket> newSocket(
208 const folly::SocketAddress& address,
209 uint32_t connectTimeout = 0) {
210 return std::shared_ptr<AsyncSocket>(
211 new AsyncSocket(evb, address, connectTimeout),
216 * Helper function to create a shared_ptr<AsyncSocket>.
218 static std::shared_ptr<AsyncSocket> newSocket(
220 const std::string& ip,
222 uint32_t connectTimeout = 0) {
223 return std::shared_ptr<AsyncSocket>(
224 new AsyncSocket(evb, ip, port, connectTimeout),
229 * Helper function to create a shared_ptr<AsyncSocket>.
231 static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb, int fd) {
232 return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb, fd),
237 * Destroy the socket.
239 * AsyncSocket::destroy() must be called to destroy the socket.
240 * The normal destructor is private, and should not be invoked directly.
241 * This prevents callers from deleting a AsyncSocket while it is invoking a
244 virtual void destroy() override;
247 * Get the EventBase used by this socket.
249 EventBase* getEventBase() const override {
254 * Get the file descriptor used by the AsyncSocket.
256 virtual int getFd() const {
261 * Extract the file descriptor from the AsyncSocket.
263 * This will immediately cause any installed callbacks to be invoked with an
264 * error. The AsyncSocket may no longer be used after the file descriptor
265 * has been extracted.
267 * Returns the file descriptor. The caller assumes ownership of the
268 * descriptor, and it will not be closed when the AsyncSocket is destroyed.
270 virtual int detachFd();
273 * Uniquely identifies a handle to a socket option value. Each
274 * combination of level and option name corresponds to one socket
279 bool operator<(const OptionKey& other) const {
280 if (level == other.level) {
281 return optname < other.optname;
283 return level < other.level;
285 int apply(int fd, int val) const {
286 return setsockopt(fd, level, optname, &val, sizeof(val));
292 // Maps from a socket option key to its value
293 typedef std::map<OptionKey, int> OptionMap;
295 static const OptionMap emptyOptionMap;
296 static const folly::SocketAddress& anyAddress();
299 * Initiate a connection.
301 * @param callback The callback to inform when the connection attempt
303 * @param address The address to connect to.
304 * @param timeout A timeout value, in milliseconds. If the connection
305 * does not succeed within this period,
306 * callback->connectError() will be invoked.
308 virtual void connect(
309 ConnectCallback* callback,
310 const folly::SocketAddress& address,
312 const OptionMap& options = emptyOptionMap,
313 const folly::SocketAddress& bindAddr = anyAddress()) noexcept;
316 ConnectCallback* callback,
317 const std::string& ip,
320 const OptionMap& options = emptyOptionMap) noexcept;
323 * If a connect request is in-flight, cancels it and closes the socket
324 * immediately. Otherwise, this is a no-op.
326 * This does not invoke any connection related callbacks. Call this to
327 * prevent any connect callback while cleaning up, etc.
329 void cancelConnect();
332 * Set the send timeout.
334 * If write requests do not make any progress for more than the specified
335 * number of milliseconds, fail all pending writes and close the socket.
337 * If write requests are currently pending when setSendTimeout() is called,
338 * the timeout interval is immediately restarted using the new value.
340 * (See the comments for AsyncSocket for an explanation of why AsyncSocket
341 * provides setSendTimeout() but not setRecvTimeout().)
343 * @param milliseconds The timeout duration, in milliseconds. If 0, no
344 * timeout will be used.
346 void setSendTimeout(uint32_t milliseconds) override;
349 * Get the send timeout.
351 * @return Returns the current send timeout, in milliseconds. A return value
352 * of 0 indicates that no timeout is set.
354 uint32_t getSendTimeout() const override {
359 * Set the maximum number of reads to execute from the underlying
360 * socket each time the EventBase detects that new ingress data is
361 * available. The default is unlimited, but callers can use this method
362 * to limit the amount of data read from the socket per event loop
365 * @param maxReads Maximum number of reads per data-available event;
366 * a value of zero means unlimited.
368 void setMaxReadsPerEvent(uint16_t maxReads) {
369 maxReadsPerEvent_ = maxReads;
373 * Get the maximum number of reads this object will execute from
374 * the underlying socket each time the EventBase detects that new
375 * ingress data is available.
377 * @returns Maximum number of reads per data-available event; a value
378 * of zero means unlimited.
380 uint16_t getMaxReadsPerEvent() const {
381 return maxReadsPerEvent_;
385 * Set a pointer to ErrMessageCallback implementation which will be
386 * receiving notifications for messages posted to the error queue
387 * associated with the socket.
388 * ErrMessageCallback is implemented only for platforms with
389 * per-socket error message queus support (recvmsg() system call must
393 void setErrMessageCB(ErrMessageCallback* callback);
396 * Get a pointer to ErrMessageCallback implementation currently
397 * registered with this socket.
400 ErrMessageCallback* getErrMessageCallback() const;
402 // Read and write methods
403 void setReadCB(ReadCallback* callback) override;
404 ReadCallback* getReadCallback() const override;
406 void write(WriteCallback* callback, const void* buf, size_t bytes,
407 WriteFlags flags = WriteFlags::NONE) override;
408 void writev(WriteCallback* callback, const iovec* vec, size_t count,
409 WriteFlags flags = WriteFlags::NONE) override;
410 void writeChain(WriteCallback* callback,
411 std::unique_ptr<folly::IOBuf>&& buf,
412 WriteFlags flags = WriteFlags::NONE) override;
415 virtual void writeRequest(WriteRequest* req);
416 void writeRequestReady() {
420 // Methods inherited from AsyncTransport
421 void close() override;
422 void closeNow() override;
423 void closeWithReset() override;
424 void shutdownWrite() override;
425 void shutdownWriteNow() override;
427 bool readable() const override;
428 bool isPending() const override;
429 virtual bool hangup() const;
430 bool good() const override;
431 bool error() const override;
432 void attachEventBase(EventBase* eventBase) override;
433 void detachEventBase() override;
434 bool isDetachable() const override;
436 void getLocalAddress(
437 folly::SocketAddress* address) const override;
439 folly::SocketAddress* address) const override;
441 bool isEorTrackingEnabled() const override {
445 void setEorTracking(bool track) override {
449 bool connecting() const override {
450 return (state_ == StateEnum::CONNECTING);
453 virtual bool isClosedByPeer() const {
454 return (state_ == StateEnum::CLOSED &&
455 (readErr_ == READ_EOF || readErr_ == READ_ERROR));
458 virtual bool isClosedBySelf() const {
459 return (state_ == StateEnum::CLOSED &&
460 (readErr_ != READ_EOF && readErr_ != READ_ERROR));
463 size_t getAppBytesWritten() const override {
464 return appBytesWritten_;
467 size_t getRawBytesWritten() const override {
468 return getAppBytesWritten();
471 size_t getAppBytesReceived() const override {
472 return appBytesReceived_;
475 size_t getRawBytesReceived() const override {
476 return getAppBytesReceived();
479 std::chrono::nanoseconds getConnectTime() const {
480 return connectEndTime_ - connectStartTime_;
483 std::chrono::milliseconds getConnectTimeout() const {
484 return connectTimeout_;
487 bool getTFOAttempted() const {
488 return tfoAttempted_;
492 * Returns whether or not the attempt to use TFO
493 * finished successfully. This does not necessarily
494 * mean TFO worked, just that trying to use TFO
497 bool getTFOFinished() const {
502 * Returns whether or not TFO attempt succeded on this
504 * For servers this is pretty straightforward API and can
505 * be invoked right after the connection is accepted. This API
506 * will perform one syscall.
507 * This API is a bit tricky to use for clients, since clients
508 * only know this for sure after the SYN-ACK is returned. So it's
509 * appropriate to call this only after the first application
510 * data is read from the socket when the caller knows that
511 * the SYN has been ACKed by the server.
513 bool getTFOSucceded() const;
515 // Methods controlling socket options
518 * Force writes to be transmitted immediately.
520 * This controls the TCP_NODELAY socket option. When enabled, TCP segments
521 * are sent as soon as possible, even if it is not a full frame of data.
522 * When disabled, the data may be buffered briefly to try and wait for a full
525 * By default, TCP_NODELAY is enabled for AsyncSocket objects.
527 * This method will fail if the socket is not currently open.
529 * @return Returns 0 if the TCP_NODELAY flag was successfully updated,
530 * or a non-zero errno value on error.
532 int setNoDelay(bool noDelay);
536 * Set the FD_CLOEXEC flag so that the socket will be closed if the program
537 * later forks and execs.
539 void setCloseOnExec();
542 * Set the Flavor of Congestion Control to be used for this Socket
543 * Please check '/lib/modules/<kernel>/kernel/net/ipv4' for tcp_*.ko
544 * first to make sure the module is available for plugging in
545 * Alternatively you can choose from net.ipv4.tcp_allowed_congestion_control
547 int setCongestionFlavor(const std::string &cname);
550 * Forces ACKs to be sent immediately
552 * @return Returns 0 if the TCP_QUICKACK flag was successfully updated,
553 * or a non-zero errno value on error.
555 int setQuickAck(bool quickack);
558 * Set the send bufsize
560 int setSendBufSize(size_t bufsize);
563 * Set the recv bufsize
565 int setRecvBufSize(size_t bufsize);
568 * Sets a specific tcp personality
569 * Available only on kernels 3.2 and greater
571 #define SO_SET_NAMESPACE 41
572 int setTCPProfile(int profd);
575 * Generic API for reading a socket option.
577 * @param level same as the "level" parameter in getsockopt().
578 * @param optname same as the "optname" parameter in getsockopt().
579 * @param optval pointer to the variable in which the option value should
581 * @param optlen value-result argument, initially containing the size of
582 * the buffer pointed to by optval, and modified on return
583 * to indicate the actual size of the value returned.
584 * @return same as the return value of getsockopt().
586 template <typename T>
587 int getSockOpt(int level, int optname, T* optval, socklen_t* optlen) {
588 return getsockopt(fd_, level, optname, (void*) optval, optlen);
592 * Generic API for setting a socket option.
594 * @param level same as the "level" parameter in getsockopt().
595 * @param optname same as the "optname" parameter in getsockopt().
596 * @param optval the option value to set.
597 * @return same as the return value of setsockopt().
599 template <typename T>
600 int setSockOpt(int level, int optname, const T *optval) {
601 return setsockopt(fd_, level, optname, optval, sizeof(T));
604 virtual void setPeek(bool peek) {
609 * Enables TFO behavior on the AsyncSocket if FOLLY_ALLOW_TFO
613 // No-op if folly does not allow tfo
619 void disableTransparentTls() {
620 noTransparentTls_ = true;
623 enum class StateEnum : uint8_t {
632 void setBufferCallback(BufferCallback* cb);
634 // Callers should set this prior to connecting the socket for the safest
636 void setEvbChangedCallback(std::unique_ptr<EvbChangeCallback> cb) {
637 evbChangeCb_ = std::move(cb);
641 * writeReturn is the total number of bytes written, or WRITE_ERROR on error.
642 * If no data has been written, 0 is returned.
643 * exception is a more specific exception that cause a write error.
644 * Not all writes have exceptions associated with them thus writeReturn
645 * should be checked to determine whether the operation resulted in an error.
648 explicit WriteResult(ssize_t ret) : writeReturn(ret) {}
650 WriteResult(ssize_t ret, std::unique_ptr<const AsyncSocketException> e)
651 : writeReturn(ret), exception(std::move(e)) {}
654 std::unique_ptr<const AsyncSocketException> exception;
658 * readReturn is the number of bytes read, or READ_EOF on EOF, or
659 * READ_ERROR on error, or READ_BLOCKING if the operation will
661 * exception is a more specific exception that may have caused a read error.
662 * Not all read errors have exceptions associated with them thus readReturn
663 * should be checked to determine whether the operation resulted in an error.
666 explicit ReadResult(ssize_t ret) : readReturn(ret) {}
668 ReadResult(ssize_t ret, std::unique_ptr<const AsyncSocketException> e)
669 : readReturn(ret), exception(std::move(e)) {}
672 std::unique_ptr<const AsyncSocketException> exception;
676 * A WriteRequest object tracks information about a pending write operation.
680 WriteRequest(AsyncSocket* socket, WriteCallback* callback) :
681 socket_(socket), callback_(callback) {}
683 virtual void start() {}
685 virtual void destroy() = 0;
687 virtual WriteResult performWrite() = 0;
689 virtual void consume() = 0;
691 virtual bool isComplete() = 0;
693 WriteRequest* getNext() const {
697 WriteCallback* getCallback() const {
701 uint32_t getTotalBytesWritten() const {
702 return totalBytesWritten_;
705 void append(WriteRequest* next) {
706 assert(next_ == nullptr);
710 void fail(const char* fn, const AsyncSocketException& ex) {
711 socket_->failWrite(fn, ex);
714 void bytesWritten(size_t count) {
715 totalBytesWritten_ += uint32_t(count);
716 socket_->appBytesWritten_ += count;
720 // protected destructor, to ensure callers use destroy()
721 virtual ~WriteRequest() {}
723 AsyncSocket* socket_; ///< parent socket
724 WriteRequest* next_{nullptr}; ///< pointer to next WriteRequest
725 WriteCallback* callback_; ///< completion callback
726 uint32_t totalBytesWritten_{0}; ///< total bytes written
730 enum ReadResultEnum {
737 enum WriteResultEnum {
742 * Protected destructor.
744 * Users of AsyncSocket must never delete it directly. Instead, invoke
745 * destroy() instead. (See the documentation in DelayedDestruction.h for
750 friend std::ostream& operator << (std::ostream& os, const StateEnum& state);
753 /// shutdownWrite() called, but we are still waiting on writes to drain
754 SHUT_WRITE_PENDING = 0x01,
755 /// writes have been completely shut down
758 * Reads have been shutdown.
760 * At the moment we don't distinguish between remote read shutdown
761 * (received EOF from the remote end) and local read shutdown. We can
762 * only receive EOF when a read callback is set, and we immediately inform
763 * it of the EOF. Therefore there doesn't seem to be any reason to have a
764 * separate state of "received EOF but the local side may still want to
767 * We also don't currently provide any API for only shutting down the read
768 * side of a socket. (This is a no-op as far as TCP is concerned, anyway.)
773 class BytesWriteRequest;
775 class WriteTimeout : public AsyncTimeout {
777 WriteTimeout(AsyncSocket* socket, EventBase* eventBase)
778 : AsyncTimeout(eventBase)
781 virtual void timeoutExpired() noexcept {
782 socket_->timeoutExpired();
786 AsyncSocket* socket_;
789 class IoHandler : public EventHandler {
791 IoHandler(AsyncSocket* socket, EventBase* eventBase)
792 : EventHandler(eventBase, -1)
794 IoHandler(AsyncSocket* socket, EventBase* eventBase, int fd)
795 : EventHandler(eventBase, fd)
798 virtual void handlerReady(uint16_t events) noexcept {
799 socket_->ioReady(events);
803 AsyncSocket* socket_;
808 class ImmediateReadCB : public folly::EventBase::LoopCallback {
810 explicit ImmediateReadCB(AsyncSocket* socket) : socket_(socket) {}
811 void runLoopCallback() noexcept override {
812 DestructorGuard dg(socket_);
813 socket_->checkForImmediateRead();
816 AsyncSocket* socket_;
820 * Schedule checkForImmediateRead to be executed in the next loop
823 void scheduleImmediateRead() noexcept {
825 eventBase_->runInLoop(&immediateReadHandler_);
830 * Schedule handleInitalReadWrite to run in the next iteration.
832 void scheduleInitialReadWrite() noexcept {
834 DestructorGuard dg(this);
835 eventBase_->runInLoop([this, dg] {
837 handleInitialReadWrite();
843 // event notification methods
844 void ioReady(uint16_t events) noexcept;
845 virtual void checkForImmediateRead() noexcept;
846 virtual void handleInitialReadWrite() noexcept;
847 virtual void prepareReadBuffer(void** buf, size_t* buflen);
848 virtual void handleErrMessages() noexcept;
849 virtual void handleRead() noexcept;
850 virtual void handleWrite() noexcept;
851 virtual void handleConnect() noexcept;
852 void timeoutExpired() noexcept;
855 * Attempt to read from the socket.
857 * @param buf The buffer to read data into.
858 * @param buflen The length of the buffer.
860 * @return Returns a read result. See read result for details.
862 virtual ReadResult performRead(void** buf, size_t* buflen, size_t* offset);
865 * Populate an iovec array from an IOBuf and attempt to write it.
867 * @param callback Write completion/error callback.
868 * @param vec Target iovec array; caller retains ownership.
869 * @param count Number of IOBufs to write, beginning at start of buf.
870 * @param buf Chain of iovecs.
871 * @param flags set of flags for the underlying write calls, like cork
873 void writeChainImpl(WriteCallback* callback, iovec* vec,
874 size_t count, std::unique_ptr<folly::IOBuf>&& buf,
878 * Write as much data as possible to the socket without blocking,
879 * and queue up any leftover data to send when the socket can
880 * handle writes again.
882 * @param callback The callback to invoke when the write is completed.
883 * @param vec Array of buffers to write; this method will make a
884 * copy of the vector (but not the buffers themselves)
885 * if the write has to be completed asynchronously.
886 * @param count Number of elements in vec.
887 * @param buf The IOBuf that manages the buffers referenced by
888 * vec, or a pointer to nullptr if the buffers are not
889 * associated with an IOBuf. Note that ownership of
890 * the IOBuf is transferred here; upon completion of
891 * the write, the AsyncSocket deletes the IOBuf.
892 * @param flags Set of write flags.
894 void writeImpl(WriteCallback* callback, const iovec* vec, size_t count,
895 std::unique_ptr<folly::IOBuf>&& buf,
896 WriteFlags flags = WriteFlags::NONE);
899 * Attempt to write to the socket.
901 * @param vec The iovec array pointing to the buffers to write.
902 * @param count The length of the iovec array.
903 * @param flags Set of write flags.
904 * @param countWritten On return, the value pointed to by this parameter
905 * will contain the number of iovec entries that were
907 * @param partialWritten On return, the value pointed to by this parameter
908 * will contain the number of bytes written in the
909 * partially written iovec entry.
911 * @return Returns a WriteResult. See WriteResult for more details.
913 virtual WriteResult performWrite(
917 uint32_t* countWritten,
918 uint32_t* partialWritten);
921 * Sends the message over the socket using sendmsg
923 * @param msg Message to send
924 * @param msg_flags Flags to pass to sendmsg
926 AsyncSocket::WriteResult
927 sendSocketMessage(int fd, struct msghdr* msg, int msg_flags);
929 virtual ssize_t tfoSendMsg(int fd, struct msghdr* msg, int msg_flags);
931 int socketConnect(const struct sockaddr* addr, socklen_t len);
933 virtual void scheduleConnectTimeout();
934 void registerForConnectEvents();
936 bool updateEventRegistration();
939 * Update event registration.
941 * @param enable Flags of events to enable. Set it to 0 if no events
942 * need to be enabled in this call.
943 * @param disable Flags of events
944 * to disable. Set it to 0 if no events need to be disabled in this
947 * @return true iff the update is successful.
949 bool updateEventRegistration(uint16_t enable, uint16_t disable);
951 // Actually close the file descriptor and set it to -1 so we don't
952 // accidentally close it again.
955 // error handling methods
958 void finishFail(const AsyncSocketException& ex);
959 void invokeAllErrors(const AsyncSocketException& ex);
960 void fail(const char* fn, const AsyncSocketException& ex);
961 void failConnect(const char* fn, const AsyncSocketException& ex);
962 void failRead(const char* fn, const AsyncSocketException& ex);
963 void failErrMessageRead(const char* fn, const AsyncSocketException& ex);
964 void failWrite(const char* fn, WriteCallback* callback, size_t bytesWritten,
965 const AsyncSocketException& ex);
966 void failWrite(const char* fn, const AsyncSocketException& ex);
967 void failAllWrites(const AsyncSocketException& ex);
968 virtual void invokeConnectErr(const AsyncSocketException& ex);
969 virtual void invokeConnectSuccess();
970 void invalidState(ConnectCallback* callback);
971 void invalidState(ErrMessageCallback* callback);
972 void invalidState(ReadCallback* callback);
973 void invalidState(WriteCallback* callback);
975 std::string withAddr(const std::string& s);
977 StateEnum state_; ///< StateEnum describing current state
978 uint8_t shutdownFlags_; ///< Shutdown state (ShutdownFlags)
979 uint16_t eventFlags_; ///< EventBase::HandlerFlags settings
980 int fd_; ///< The socket file descriptor
981 mutable folly::SocketAddress addr_; ///< The address we tried to connect to
982 mutable folly::SocketAddress localAddr_;
983 ///< The address we are connecting from
984 uint32_t sendTimeout_; ///< The send timeout, in milliseconds
985 uint16_t maxReadsPerEvent_; ///< Max reads per event loop iteration
986 EventBase* eventBase_; ///< The EventBase
987 WriteTimeout writeTimeout_; ///< A timeout for connect and write
988 IoHandler ioHandler_; ///< A EventHandler to monitor the fd
989 ImmediateReadCB immediateReadHandler_; ///< LoopCallback for checking read
991 ConnectCallback* connectCallback_; ///< ConnectCallback
992 ErrMessageCallback* errMessageCallback_; ///< TimestampCallback
993 ReadCallback* readCallback_; ///< ReadCallback
994 WriteRequest* writeReqHead_; ///< Chain of WriteRequests
995 WriteRequest* writeReqTail_; ///< End of WriteRequest chain
996 ShutdownSocketSet* shutdownSocketSet_;
997 size_t appBytesReceived_; ///< Num of bytes received from socket
998 size_t appBytesWritten_; ///< Num of bytes written to socket
999 bool isBufferMovable_{false};
1001 bool peek_{false}; // Peek bytes.
1003 int8_t readErr_{READ_NO_ERROR}; ///< The read error encountered, if any.
1005 std::chrono::steady_clock::time_point connectStartTime_;
1006 std::chrono::steady_clock::time_point connectEndTime_;
1008 std::chrono::milliseconds connectTimeout_{0};
1010 BufferCallback* bufferCallback_{nullptr};
1011 bool tfoEnabled_{false};
1012 bool tfoAttempted_{false};
1013 bool tfoFinished_{false};
1014 bool noTransparentTls_{false};
1015 // Whether to track EOR or not.
1016 bool trackEor_{false};
1018 std::unique_ptr<EvbChangeCallback> evbChangeCb_{nullptr};
1021 #pragma vtordisp(pop)