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;
114 explicit AsyncSocket();
116 * Create a new unconnected AsyncSocket.
118 * connect() must later be called on this socket to establish a connection.
120 explicit AsyncSocket(EventBase* evb);
122 void setShutdownSocketSet(ShutdownSocketSet* ss);
125 * Create a new AsyncSocket and begin the connection process.
127 * @param evb EventBase that will manage this socket.
128 * @param address The address to connect to.
129 * @param connectTimeout Optional timeout in milliseconds for the connection
132 AsyncSocket(EventBase* evb,
133 const folly::SocketAddress& address,
134 uint32_t connectTimeout = 0);
137 * Create a new AsyncSocket and begin the connection process.
139 * @param evb EventBase that will manage this socket.
140 * @param ip IP address to connect to (dotted-quad).
141 * @param port Destination port in host byte order.
142 * @param connectTimeout Optional timeout in milliseconds for the connection
145 AsyncSocket(EventBase* evb,
146 const std::string& ip,
148 uint32_t connectTimeout = 0);
151 * Create a AsyncSocket from an already connected socket file descriptor.
153 * Note that while AsyncSocket enables TCP_NODELAY for sockets it creates
154 * when connecting, it does not change the socket options when given an
155 * existing file descriptor. If callers want TCP_NODELAY enabled when using
156 * this version of the constructor, they need to explicitly call
157 * setNoDelay(true) after the constructor returns.
159 * @param evb EventBase that will manage this socket.
160 * @param fd File descriptor to take over (should be a connected socket).
162 AsyncSocket(EventBase* evb, int fd);
165 * Helper function to create a shared_ptr<AsyncSocket>.
167 * This passes in the correct destructor object, since AsyncSocket's
168 * destructor is protected and cannot be invoked directly.
170 static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb) {
171 return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb),
176 * Helper function to create a shared_ptr<AsyncSocket>.
178 static std::shared_ptr<AsyncSocket> newSocket(
180 const folly::SocketAddress& address,
181 uint32_t connectTimeout = 0) {
182 return std::shared_ptr<AsyncSocket>(
183 new AsyncSocket(evb, address, connectTimeout),
188 * Helper function to create a shared_ptr<AsyncSocket>.
190 static std::shared_ptr<AsyncSocket> newSocket(
192 const std::string& ip,
194 uint32_t connectTimeout = 0) {
195 return std::shared_ptr<AsyncSocket>(
196 new AsyncSocket(evb, ip, port, connectTimeout),
201 * Helper function to create a shared_ptr<AsyncSocket>.
203 static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb, int fd) {
204 return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb, fd),
209 * Destroy the socket.
211 * AsyncSocket::destroy() must be called to destroy the socket.
212 * The normal destructor is private, and should not be invoked directly.
213 * This prevents callers from deleting a AsyncSocket while it is invoking a
216 virtual void destroy() override;
219 * Get the EventBase used by this socket.
221 EventBase* getEventBase() const override {
226 * Get the file descriptor used by the AsyncSocket.
228 virtual int getFd() const {
233 * Extract the file descriptor from the AsyncSocket.
235 * This will immediately cause any installed callbacks to be invoked with an
236 * error. The AsyncSocket may no longer be used after the file descriptor
237 * has been extracted.
239 * Returns the file descriptor. The caller assumes ownership of the
240 * descriptor, and it will not be closed when the AsyncSocket is destroyed.
242 virtual int detachFd();
245 * Uniquely identifies a handle to a socket option value. Each
246 * combination of level and option name corresponds to one socket
251 bool operator<(const OptionKey& other) const {
252 if (level == other.level) {
253 return optname < other.optname;
255 return level < other.level;
257 int apply(int fd, int val) const {
258 return setsockopt(fd, level, optname, &val, sizeof(val));
264 // Maps from a socket option key to its value
265 typedef std::map<OptionKey, int> OptionMap;
267 static const OptionMap emptyOptionMap;
268 static const folly::SocketAddress& anyAddress();
271 * Initiate a connection.
273 * @param callback The callback to inform when the connection attempt
275 * @param address The address to connect to.
276 * @param timeout A timeout value, in milliseconds. If the connection
277 * does not succeed within this period,
278 * callback->connectError() will be invoked.
280 virtual void connect(
281 ConnectCallback* callback,
282 const folly::SocketAddress& address,
284 const OptionMap& options = emptyOptionMap,
285 const folly::SocketAddress& bindAddr = anyAddress()) noexcept;
288 ConnectCallback* callback,
289 const std::string& ip,
292 const OptionMap& options = emptyOptionMap) noexcept;
295 * If a connect request is in-flight, cancels it and closes the socket
296 * immediately. Otherwise, this is a no-op.
298 * This does not invoke any connection related callbacks. Call this to
299 * prevent any connect callback while cleaning up, etc.
301 void cancelConnect();
304 * Set the send timeout.
306 * If write requests do not make any progress for more than the specified
307 * number of milliseconds, fail all pending writes and close the socket.
309 * If write requests are currently pending when setSendTimeout() is called,
310 * the timeout interval is immediately restarted using the new value.
312 * (See the comments for AsyncSocket for an explanation of why AsyncSocket
313 * provides setSendTimeout() but not setRecvTimeout().)
315 * @param milliseconds The timeout duration, in milliseconds. If 0, no
316 * timeout will be used.
318 void setSendTimeout(uint32_t milliseconds) override;
321 * Get the send timeout.
323 * @return Returns the current send timeout, in milliseconds. A return value
324 * of 0 indicates that no timeout is set.
326 uint32_t getSendTimeout() const override {
331 * Set the maximum number of reads to execute from the underlying
332 * socket each time the EventBase detects that new ingress data is
333 * available. The default is unlimited, but callers can use this method
334 * to limit the amount of data read from the socket per event loop
337 * @param maxReads Maximum number of reads per data-available event;
338 * a value of zero means unlimited.
340 void setMaxReadsPerEvent(uint16_t maxReads) {
341 maxReadsPerEvent_ = maxReads;
345 * Get the maximum number of reads this object will execute from
346 * the underlying socket each time the EventBase detects that new
347 * ingress data is available.
349 * @returns Maximum number of reads per data-available event; a value
350 * of zero means unlimited.
352 uint16_t getMaxReadsPerEvent() const {
353 return maxReadsPerEvent_;
356 // Read and write methods
357 void setReadCB(ReadCallback* callback) override;
358 ReadCallback* getReadCallback() const override;
360 void write(WriteCallback* callback, const void* buf, size_t bytes,
361 WriteFlags flags = WriteFlags::NONE) override;
362 void writev(WriteCallback* callback, const iovec* vec, size_t count,
363 WriteFlags flags = WriteFlags::NONE) override;
364 void writeChain(WriteCallback* callback,
365 std::unique_ptr<folly::IOBuf>&& buf,
366 WriteFlags flags = WriteFlags::NONE) override;
369 virtual void writeRequest(WriteRequest* req);
370 void writeRequestReady() {
374 // Methods inherited from AsyncTransport
375 void close() override;
376 void closeNow() override;
377 void closeWithReset() override;
378 void shutdownWrite() override;
379 void shutdownWriteNow() override;
381 bool readable() const override;
382 bool isPending() const override;
383 virtual bool hangup() const;
384 bool good() const override;
385 bool error() const override;
386 void attachEventBase(EventBase* eventBase) override;
387 void detachEventBase() override;
388 bool isDetachable() const override;
390 void getLocalAddress(
391 folly::SocketAddress* address) const override;
393 folly::SocketAddress* address) const override;
395 bool isEorTrackingEnabled() const override {
399 void setEorTracking(bool track) override {
403 bool connecting() const override {
404 return (state_ == StateEnum::CONNECTING);
407 virtual bool isClosedByPeer() const {
408 return (state_ == StateEnum::CLOSED &&
409 (readErr_ == READ_EOF || readErr_ == READ_ERROR));
412 virtual bool isClosedBySelf() const {
413 return (state_ == StateEnum::CLOSED &&
414 (readErr_ != READ_EOF && readErr_ != READ_ERROR));
417 size_t getAppBytesWritten() const override {
418 return appBytesWritten_;
421 size_t getRawBytesWritten() const override {
422 return getAppBytesWritten();
425 size_t getAppBytesReceived() const override {
426 return appBytesReceived_;
429 size_t getRawBytesReceived() const override {
430 return getAppBytesReceived();
433 std::chrono::nanoseconds getConnectTime() const {
434 return connectEndTime_ - connectStartTime_;
437 std::chrono::milliseconds getConnectTimeout() const {
438 return connectTimeout_;
441 bool getTFOAttempted() const {
442 return tfoAttempted_;
446 * Returns whether or not the attempt to use TFO
447 * finished successfully. This does not necessarily
448 * mean TFO worked, just that trying to use TFO
451 bool getTFOFinished() const {
456 * Returns whether or not TFO attempt succeded on this
458 * For servers this is pretty straightforward API and can
459 * be invoked right after the connection is accepted. This API
460 * will perform one syscall.
461 * This API is a bit tricky to use for clients, since clients
462 * only know this for sure after the SYN-ACK is returned. So it's
463 * appropriate to call this only after the first application
464 * data is read from the socket when the caller knows that
465 * the SYN has been ACKed by the server.
467 bool getTFOSucceded() const;
469 // Methods controlling socket options
472 * Force writes to be transmitted immediately.
474 * This controls the TCP_NODELAY socket option. When enabled, TCP segments
475 * are sent as soon as possible, even if it is not a full frame of data.
476 * When disabled, the data may be buffered briefly to try and wait for a full
479 * By default, TCP_NODELAY is enabled for AsyncSocket objects.
481 * This method will fail if the socket is not currently open.
483 * @return Returns 0 if the TCP_NODELAY flag was successfully updated,
484 * or a non-zero errno value on error.
486 int setNoDelay(bool noDelay);
490 * Set the FD_CLOEXEC flag so that the socket will be closed if the program
491 * later forks and execs.
493 void setCloseOnExec();
496 * Set the Flavor of Congestion Control to be used for this Socket
497 * Please check '/lib/modules/<kernel>/kernel/net/ipv4' for tcp_*.ko
498 * first to make sure the module is available for plugging in
499 * Alternatively you can choose from net.ipv4.tcp_allowed_congestion_control
501 int setCongestionFlavor(const std::string &cname);
504 * Forces ACKs to be sent immediately
506 * @return Returns 0 if the TCP_QUICKACK flag was successfully updated,
507 * or a non-zero errno value on error.
509 int setQuickAck(bool quickack);
512 * Set the send bufsize
514 int setSendBufSize(size_t bufsize);
517 * Set the recv bufsize
519 int setRecvBufSize(size_t bufsize);
522 * Sets a specific tcp personality
523 * Available only on kernels 3.2 and greater
525 #define SO_SET_NAMESPACE 41
526 int setTCPProfile(int profd);
529 * Generic API for reading a socket option.
531 * @param level same as the "level" parameter in getsockopt().
532 * @param optname same as the "optname" parameter in getsockopt().
533 * @param optval pointer to the variable in which the option value should
535 * @param optlen value-result argument, initially containing the size of
536 * the buffer pointed to by optval, and modified on return
537 * to indicate the actual size of the value returned.
538 * @return same as the return value of getsockopt().
540 template <typename T>
541 int getSockOpt(int level, int optname, T* optval, socklen_t* optlen) {
542 return getsockopt(fd_, level, optname, (void*) optval, optlen);
546 * Generic API for setting a socket option.
548 * @param level same as the "level" parameter in getsockopt().
549 * @param optname same as the "optname" parameter in getsockopt().
550 * @param optval the option value to set.
551 * @return same as the return value of setsockopt().
553 template <typename T>
554 int setSockOpt(int level, int optname, const T *optval) {
555 return setsockopt(fd_, level, optname, optval, sizeof(T));
558 virtual void setPeek(bool peek) {
563 * Enables TFO behavior on the AsyncSocket if FOLLY_ALLOW_TFO
567 // No-op if folly does not allow tfo
573 void disableTransparentTls() {
574 noTransparentTls_ = true;
577 enum class StateEnum : uint8_t {
586 void setBufferCallback(BufferCallback* cb);
588 // Callers should set this prior to connecting the socket for the safest
590 void setEvbChangedCallback(std::unique_ptr<EvbChangeCallback> cb) {
591 evbChangeCb_ = std::move(cb);
595 * writeReturn is the total number of bytes written, or WRITE_ERROR on error.
596 * If no data has been written, 0 is returned.
597 * exception is a more specific exception that cause a write error.
598 * Not all writes have exceptions associated with them thus writeReturn
599 * should be checked to determine whether the operation resulted in an error.
602 explicit WriteResult(ssize_t ret) : writeReturn(ret) {}
604 WriteResult(ssize_t ret, std::unique_ptr<const AsyncSocketException> e)
605 : writeReturn(ret), exception(std::move(e)) {}
608 std::unique_ptr<const AsyncSocketException> exception;
612 * readReturn is the number of bytes read, or READ_EOF on EOF, or
613 * READ_ERROR on error, or READ_BLOCKING if the operation will
615 * exception is a more specific exception that may have caused a read error.
616 * Not all read errors have exceptions associated with them thus readReturn
617 * should be checked to determine whether the operation resulted in an error.
620 explicit ReadResult(ssize_t ret) : readReturn(ret) {}
622 ReadResult(ssize_t ret, std::unique_ptr<const AsyncSocketException> e)
623 : readReturn(ret), exception(std::move(e)) {}
626 std::unique_ptr<const AsyncSocketException> exception;
630 * A WriteRequest object tracks information about a pending write operation.
634 WriteRequest(AsyncSocket* socket, WriteCallback* callback) :
635 socket_(socket), callback_(callback) {}
637 virtual void start() {}
639 virtual void destroy() = 0;
641 virtual WriteResult performWrite() = 0;
643 virtual void consume() = 0;
645 virtual bool isComplete() = 0;
647 WriteRequest* getNext() const {
651 WriteCallback* getCallback() const {
655 uint32_t getTotalBytesWritten() const {
656 return totalBytesWritten_;
659 void append(WriteRequest* next) {
660 assert(next_ == nullptr);
664 void fail(const char* fn, const AsyncSocketException& ex) {
665 socket_->failWrite(fn, ex);
668 void bytesWritten(size_t count) {
669 totalBytesWritten_ += uint32_t(count);
670 socket_->appBytesWritten_ += count;
674 // protected destructor, to ensure callers use destroy()
675 virtual ~WriteRequest() {}
677 AsyncSocket* socket_; ///< parent socket
678 WriteRequest* next_{nullptr}; ///< pointer to next WriteRequest
679 WriteCallback* callback_; ///< completion callback
680 uint32_t totalBytesWritten_{0}; ///< total bytes written
684 enum ReadResultEnum {
691 enum WriteResultEnum {
696 * Protected destructor.
698 * Users of AsyncSocket must never delete it directly. Instead, invoke
699 * destroy() instead. (See the documentation in DelayedDestruction.h for
704 friend std::ostream& operator << (std::ostream& os, const StateEnum& state);
707 /// shutdownWrite() called, but we are still waiting on writes to drain
708 SHUT_WRITE_PENDING = 0x01,
709 /// writes have been completely shut down
712 * Reads have been shutdown.
714 * At the moment we don't distinguish between remote read shutdown
715 * (received EOF from the remote end) and local read shutdown. We can
716 * only receive EOF when a read callback is set, and we immediately inform
717 * it of the EOF. Therefore there doesn't seem to be any reason to have a
718 * separate state of "received EOF but the local side may still want to
721 * We also don't currently provide any API for only shutting down the read
722 * side of a socket. (This is a no-op as far as TCP is concerned, anyway.)
727 class BytesWriteRequest;
729 class WriteTimeout : public AsyncTimeout {
731 WriteTimeout(AsyncSocket* socket, EventBase* eventBase)
732 : AsyncTimeout(eventBase)
735 virtual void timeoutExpired() noexcept {
736 socket_->timeoutExpired();
740 AsyncSocket* socket_;
743 class IoHandler : public EventHandler {
745 IoHandler(AsyncSocket* socket, EventBase* eventBase)
746 : EventHandler(eventBase, -1)
748 IoHandler(AsyncSocket* socket, EventBase* eventBase, int fd)
749 : EventHandler(eventBase, fd)
752 virtual void handlerReady(uint16_t events) noexcept {
753 socket_->ioReady(events);
757 AsyncSocket* socket_;
762 class ImmediateReadCB : public folly::EventBase::LoopCallback {
764 explicit ImmediateReadCB(AsyncSocket* socket) : socket_(socket) {}
765 void runLoopCallback() noexcept override {
766 DestructorGuard dg(socket_);
767 socket_->checkForImmediateRead();
770 AsyncSocket* socket_;
774 * Schedule checkForImmediateRead to be executed in the next loop
777 void scheduleImmediateRead() noexcept {
779 eventBase_->runInLoop(&immediateReadHandler_);
784 * Schedule handleInitalReadWrite to run in the next iteration.
786 void scheduleInitialReadWrite() noexcept {
788 DestructorGuard dg(this);
789 eventBase_->runInLoop([this, dg] {
791 handleInitialReadWrite();
797 // event notification methods
798 void ioReady(uint16_t events) noexcept;
799 virtual void checkForImmediateRead() noexcept;
800 virtual void handleInitialReadWrite() noexcept;
801 virtual void prepareReadBuffer(void** buf, size_t* buflen);
802 virtual void handleRead() noexcept;
803 virtual void handleWrite() noexcept;
804 virtual void handleConnect() noexcept;
805 void timeoutExpired() noexcept;
808 * Attempt to read from the socket.
810 * @param buf The buffer to read data into.
811 * @param buflen The length of the buffer.
813 * @return Returns a read result. See read result for details.
815 virtual ReadResult performRead(void** buf, size_t* buflen, size_t* offset);
818 * Populate an iovec array from an IOBuf and attempt to write it.
820 * @param callback Write completion/error callback.
821 * @param vec Target iovec array; caller retains ownership.
822 * @param count Number of IOBufs to write, beginning at start of buf.
823 * @param buf Chain of iovecs.
824 * @param flags set of flags for the underlying write calls, like cork
826 void writeChainImpl(WriteCallback* callback, iovec* vec,
827 size_t count, std::unique_ptr<folly::IOBuf>&& buf,
831 * Write as much data as possible to the socket without blocking,
832 * and queue up any leftover data to send when the socket can
833 * handle writes again.
835 * @param callback The callback to invoke when the write is completed.
836 * @param vec Array of buffers to write; this method will make a
837 * copy of the vector (but not the buffers themselves)
838 * if the write has to be completed asynchronously.
839 * @param count Number of elements in vec.
840 * @param buf The IOBuf that manages the buffers referenced by
841 * vec, or a pointer to nullptr if the buffers are not
842 * associated with an IOBuf. Note that ownership of
843 * the IOBuf is transferred here; upon completion of
844 * the write, the AsyncSocket deletes the IOBuf.
845 * @param flags Set of write flags.
847 void writeImpl(WriteCallback* callback, const iovec* vec, size_t count,
848 std::unique_ptr<folly::IOBuf>&& buf,
849 WriteFlags flags = WriteFlags::NONE);
852 * Attempt to write to the socket.
854 * @param vec The iovec array pointing to the buffers to write.
855 * @param count The length of the iovec array.
856 * @param flags Set of write flags.
857 * @param countWritten On return, the value pointed to by this parameter
858 * will contain the number of iovec entries that were
860 * @param partialWritten On return, the value pointed to by this parameter
861 * will contain the number of bytes written in the
862 * partially written iovec entry.
864 * @return Returns a WriteResult. See WriteResult for more details.
866 virtual WriteResult performWrite(
870 uint32_t* countWritten,
871 uint32_t* partialWritten);
874 * Sends the message over the socket using sendmsg
876 * @param msg Message to send
877 * @param msg_flags Flags to pass to sendmsg
879 AsyncSocket::WriteResult
880 sendSocketMessage(int fd, struct msghdr* msg, int msg_flags);
882 virtual ssize_t tfoSendMsg(int fd, struct msghdr* msg, int msg_flags);
884 int socketConnect(const struct sockaddr* addr, socklen_t len);
886 virtual void scheduleConnectTimeout();
887 void registerForConnectEvents();
889 bool updateEventRegistration();
892 * Update event registration.
894 * @param enable Flags of events to enable. Set it to 0 if no events
895 * need to be enabled in this call.
896 * @param disable Flags of events
897 * to disable. Set it to 0 if no events need to be disabled in this
900 * @return true iff the update is successful.
902 bool updateEventRegistration(uint16_t enable, uint16_t disable);
904 // Actually close the file descriptor and set it to -1 so we don't
905 // accidentally close it again.
908 // error handling methods
911 void finishFail(const AsyncSocketException& ex);
912 void invokeAllErrors(const AsyncSocketException& ex);
913 void fail(const char* fn, const AsyncSocketException& ex);
914 void failConnect(const char* fn, const AsyncSocketException& ex);
915 void failRead(const char* fn, const AsyncSocketException& ex);
916 void failWrite(const char* fn, WriteCallback* callback, size_t bytesWritten,
917 const AsyncSocketException& ex);
918 void failWrite(const char* fn, const AsyncSocketException& ex);
919 void failAllWrites(const AsyncSocketException& ex);
920 virtual void invokeConnectErr(const AsyncSocketException& ex);
921 virtual void invokeConnectSuccess();
922 void invalidState(ConnectCallback* callback);
923 void invalidState(ReadCallback* callback);
924 void invalidState(WriteCallback* callback);
926 std::string withAddr(const std::string& s);
928 StateEnum state_; ///< StateEnum describing current state
929 uint8_t shutdownFlags_; ///< Shutdown state (ShutdownFlags)
930 uint16_t eventFlags_; ///< EventBase::HandlerFlags settings
931 int fd_; ///< The socket file descriptor
932 mutable folly::SocketAddress addr_; ///< The address we tried to connect to
933 mutable folly::SocketAddress localAddr_;
934 ///< The address we are connecting from
935 uint32_t sendTimeout_; ///< The send timeout, in milliseconds
936 uint16_t maxReadsPerEvent_; ///< Max reads per event loop iteration
937 EventBase* eventBase_; ///< The EventBase
938 WriteTimeout writeTimeout_; ///< A timeout for connect and write
939 IoHandler ioHandler_; ///< A EventHandler to monitor the fd
940 ImmediateReadCB immediateReadHandler_; ///< LoopCallback for checking read
942 ConnectCallback* connectCallback_; ///< ConnectCallback
943 ReadCallback* readCallback_; ///< ReadCallback
944 WriteRequest* writeReqHead_; ///< Chain of WriteRequests
945 WriteRequest* writeReqTail_; ///< End of WriteRequest chain
946 ShutdownSocketSet* shutdownSocketSet_;
947 size_t appBytesReceived_; ///< Num of bytes received from socket
948 size_t appBytesWritten_; ///< Num of bytes written to socket
949 bool isBufferMovable_{false};
951 bool peek_{false}; // Peek bytes.
953 int8_t readErr_{READ_NO_ERROR}; ///< The read error encountered, if any.
955 std::chrono::steady_clock::time_point connectStartTime_;
956 std::chrono::steady_clock::time_point connectEndTime_;
958 std::chrono::milliseconds connectTimeout_{0};
960 BufferCallback* bufferCallback_{nullptr};
961 bool tfoEnabled_{false};
962 bool tfoAttempted_{false};
963 bool tfoFinished_{false};
964 bool noTransparentTls_{false};
965 // Whether to track EOR or not.
966 bool trackEor_{false};
968 std::unique_ptr<EvbChangeCallback> evbChangeCb_{nullptr};
971 #pragma vtordisp(pop)