proxygen
folly::AsyncSocket Class Reference

#include <AsyncSocket.h>

Inheritance diagram for folly::AsyncSocket:
folly::AsyncTransportWrapper folly::AsyncTransport folly::AsyncReader folly::AsyncWriter folly::DelayedDestruction folly::AsyncSocketBase folly::DelayedDestructionBase AsyncSocketImmediateRead folly::AsyncSSLSocket folly::test::MockAsyncSocket folly::MockAsyncSSLSocket folly::test::MockAsyncSSLSocket

Classes

class  BytesWriteRequest
 
class  ConnectCallback
 
class  ErrMessageCallback
 
class  EvbChangeCallback
 
class  ImmediateReadCB
 
struct  IOBufInfo
 
class  IoHandler
 
class  OptionKey
 
struct  ReadResult
 
class  SendMsgParamsCallback
 
class  WriteRequest
 
struct  WriteResult
 
class  WriteTimeout
 

Public Types

enum  StateEnum : uint8_t {
  StateEnum::UNINIT, StateEnum::CONNECTING, StateEnum::ESTABLISHED, StateEnum::CLOSED,
  StateEnum::ERROR, StateEnum::FAST_OPEN
}
 
typedef std::unique_ptr< AsyncSocket, DestructorUniquePtr
 
typedef std::map< OptionKey, int > OptionMap
 
- Public Types inherited from folly::AsyncTransportWrapper
using UniquePtr = std::unique_ptr< AsyncTransportWrapper, Destructor >
 
using ReadCallback = AsyncReader::ReadCallback
 
using WriteCallback = AsyncWriter::WriteCallback
 
- Public Types inherited from folly::AsyncTransport
typedef std::unique_ptr< AsyncTransport, DestructorUniquePtr
 

Public Member Functions

 AsyncSocket ()
 
 AsyncSocket (EventBase *evb)
 
void setShutdownSocketSet (const std::weak_ptr< ShutdownSocketSet > &wSS)
 
 AsyncSocket (EventBase *evb, const folly::SocketAddress &address, uint32_t connectTimeout=0)
 
 AsyncSocket (EventBase *evb, const std::string &ip, uint16_t port, uint32_t connectTimeout=0)
 
 AsyncSocket (EventBase *evb, int fd, uint32_t zeroCopyBufId=0)
 
 AsyncSocket (AsyncSocket::UniquePtr)
 
void destroy () override
 
EventBasegetEventBase () const override
 
virtual int getFd () const
 
virtual int detachFd ()
 
virtual void connect (ConnectCallback *callback, const folly::SocketAddress &address, int timeout=0, const OptionMap &options=emptyOptionMap, const folly::SocketAddress &bindAddr=anyAddress()) noexcept
 
void connect (ConnectCallback *callback, const std::string &ip, uint16_t port, int timeout=0, const OptionMap &options=emptyOptionMap) noexcept
 
void cancelConnect ()
 
void setSendTimeout (uint32_t milliseconds) override
 
uint32_t getSendTimeout () const override
 
void setMaxReadsPerEvent (uint16_t maxReads)
 
uint16_t getMaxReadsPerEvent () const
 
virtual void setErrMessageCB (ErrMessageCallback *callback)
 
virtual ErrMessageCallbackgetErrMessageCallback () const
 
virtual void setSendMsgParamCB (SendMsgParamsCallback *callback)
 
virtual SendMsgParamsCallbackgetSendMsgParamsCB () const
 
void setReadCB (ReadCallback *callback) override
 
ReadCallbackgetReadCallback () const override
 
bool setZeroCopy (bool enable)
 
bool getZeroCopy () const
 
uint32_t getZeroCopyBufId () const
 
size_t getZeroCopyReenableThreshold () const
 
void setZeroCopyReenableThreshold (size_t threshold)
 
void write (WriteCallback *callback, const void *buf, size_t bytes, WriteFlags flags=WriteFlags::NONE) override
 
void writev (WriteCallback *callback, const iovec *vec, size_t count, WriteFlags flags=WriteFlags::NONE) override
 
void writeChain (WriteCallback *callback, std::unique_ptr< folly::IOBuf > &&buf, WriteFlags flags=WriteFlags::NONE) override
 
virtual void writeRequest (WriteRequest *req)
 
void writeRequestReady ()
 
void close () override
 
void closeNow () override
 
void closeWithReset () override
 
void shutdownWrite () override
 
void shutdownWriteNow () override
 
bool readable () const override
 
bool writable () const override
 
bool isPending () const override
 
virtual bool hangup () const
 
bool good () const override
 
bool error () const override
 
void attachEventBase (EventBase *eventBase) override
 
void detachEventBase () override
 
bool isDetachable () const override
 
void getLocalAddress (folly::SocketAddress *address) const override
 
void getPeerAddress (folly::SocketAddress *address) const override
 
bool isEorTrackingEnabled () const override
 
void setEorTracking (bool track) override
 
bool connecting () const override
 
virtual bool isClosedByPeer () const
 
virtual bool isClosedBySelf () const
 
size_t getAppBytesWritten () const override
 
size_t getRawBytesWritten () const override
 
size_t getAppBytesReceived () const override
 
size_t getRawBytesReceived () const override
 
std::chrono::nanoseconds getConnectTime () const
 
std::chrono::milliseconds getConnectTimeout () const
 
std::chrono::steady_clock::time_point getConnectStartTime () const
 
std::chrono::steady_clock::time_point getConnectEndTime () const
 
bool getTFOAttempted () const
 
bool getTFOFinished () const
 
bool getTFOSucceded () const
 
int setNoDelay (bool noDelay)
 
void setCloseOnExec ()
 
int setCongestionFlavor (const std::string &cname)
 
int setQuickAck (bool quickack)
 
int setSendBufSize (size_t bufsize)
 
int setRecvBufSize (size_t bufsize)
 
int setTCPProfile (int profd)
 
template<typename T >
int getSockOpt (int level, int optname, T *optval, socklen_t *optlen)
 
template<typename T >
int setSockOpt (int level, int optname, const T *optval)
 
virtual int getSockOptVirtual (int level, int optname, void *optval, socklen_t *optlen)
 
virtual int setSockOptVirtual (int level, int optname, void const *optval, socklen_t optlen)
 
virtual void setPreReceivedData (std::unique_ptr< IOBuf > data)
 
void enableTFO ()
 
void disableTransparentTls ()
 
void disableTSocks ()
 
void setBufferCallback (BufferCallback *cb)
 
void setEvbChangedCallback (std::unique_ptr< EvbChangeCallback > cb)
 
void cacheAddresses ()
 
bool isZeroCopyWriteInProgress () const noexcept
 
bool processZeroCopyWriteInProgress () noexcept
 
void setPeerCertificate (std::unique_ptr< const AsyncTransportCertificate > cert)
 
const AsyncTransportCertificategetPeerCertificate () const override
 
void setSelfCertificate (std::unique_ptr< const AsyncTransportCertificate > cert)
 
const AsyncTransportCertificategetSelfCertificate () const override
 
- Public Member Functions inherited from folly::AsyncTransportWrapper
virtual const AsyncTransportWrappergetWrappedTransport () const
 
template<class T >
const TgetUnderlyingTransport () const
 
template<class T >
TgetUnderlyingTransport ()
 
- Public Member Functions inherited from folly::AsyncTransport
SocketAddress getLocalAddress () const
 
void getAddress (SocketAddress *address) const override
 
SocketAddress getPeerAddress () const
 
virtual ssl::X509UniquePtr getPeerCert () const
 
virtual const X509 * getSelfCert () const
 
virtual std::string getApplicationProtocol () const noexcept
 
virtual std::string getSecurityProtocol () const
 
virtual bool isReplaySafe () const
 
virtual void setReplaySafetyCallback (ReplaySafetyCallback *callback)
 
- Public Member Functions inherited from folly::DelayedDestruction
bool getDestroyPending () const
 
- Public Member Functions inherited from folly::DelayedDestructionBase
virtual ~DelayedDestructionBase ()=default
 
- Public Member Functions inherited from folly::AsyncSocketBase
virtual ~AsyncSocketBase ()=default
 

Static Public Member Functions

static std::shared_ptr< AsyncSocketnewSocket (EventBase *evb)
 
static std::shared_ptr< AsyncSocketnewSocket (EventBase *evb, const folly::SocketAddress &address, uint32_t connectTimeout=0)
 
static std::shared_ptr< AsyncSocketnewSocket (EventBase *evb, const std::string &ip, uint16_t port, uint32_t connectTimeout=0)
 
static std::shared_ptr< AsyncSocketnewSocket (EventBase *evb, int fd)
 
static const folly::SocketAddressanyAddress ()
 

Static Public Attributes

static const OptionMap emptyOptionMap
 

Protected Types

enum  ReadResultEnum { READ_EOF = 0, READ_ERROR = -1, READ_BLOCKING = -2, READ_NO_ERROR = -3 }
 
enum  WriteResultEnum { WRITE_ERROR = -1 }
 
enum  ShutdownFlags { SHUT_WRITE_PENDING = 0x01, SHUT_WRITE = 0x02, SHUT_READ = 0x04 }
 

Protected Member Functions

 ~AsyncSocket () override
 
void init ()
 
void scheduleImmediateRead () noexcept
 
void scheduleInitialReadWrite () noexcept
 
void ioReady (uint16_t events) noexcept
 
virtual void checkForImmediateRead () noexcept
 
virtual void handleInitialReadWrite () noexcept
 
virtual void prepareReadBuffer (void **buf, size_t *buflen)
 
virtual size_t handleErrMessages () noexcept
 
virtual void handleRead () noexcept
 
virtual void handleWrite () noexcept
 
virtual void handleConnect () noexcept
 
void timeoutExpired () noexcept
 
virtual ReadResult performRead (void **buf, size_t *buflen, size_t *offset)
 
void writeChainImpl (WriteCallback *callback, iovec *vec, size_t count, std::unique_ptr< folly::IOBuf > &&buf, WriteFlags flags)
 
void writeImpl (WriteCallback *callback, const iovec *vec, size_t count, std::unique_ptr< folly::IOBuf > &&buf, WriteFlags flags=WriteFlags::NONE)
 
virtual WriteResult performWrite (const iovec *vec, uint32_t count, WriteFlags flags, uint32_t *countWritten, uint32_t *partialWritten)
 
AsyncSocket::WriteResult sendSocketMessage (int fd, struct msghdr *msg, int msg_flags)
 
virtual ssize_t tfoSendMsg (int fd, struct msghdr *msg, int msg_flags)
 
int socketConnect (const struct sockaddr *addr, socklen_t len)
 
virtual void scheduleConnectTimeout ()
 
void registerForConnectEvents ()
 
bool updateEventRegistration ()
 
bool updateEventRegistration (uint16_t enable, uint16_t disable)
 
void doClose ()
 
void startFail ()
 
void finishFail ()
 
void finishFail (const AsyncSocketException &ex)
 
void invokeAllErrors (const AsyncSocketException &ex)
 
void fail (const char *fn, const AsyncSocketException &ex)
 
void failConnect (const char *fn, const AsyncSocketException &ex)
 
void failRead (const char *fn, const AsyncSocketException &ex)
 
void failErrMessageRead (const char *fn, const AsyncSocketException &ex)
 
void failWrite (const char *fn, WriteCallback *callback, size_t bytesWritten, const AsyncSocketException &ex)
 
void failWrite (const char *fn, const AsyncSocketException &ex)
 
void failAllWrites (const AsyncSocketException &ex)
 
virtual void invokeConnectErr (const AsyncSocketException &ex)
 
virtual void invokeConnectSuccess ()
 
void invalidState (ConnectCallback *callback)
 
void invalidState (ErrMessageCallback *callback)
 
void invalidState (ReadCallback *callback)
 
void invalidState (WriteCallback *callback)
 
std::string withAddr (const std::string &s)
 
void cacheLocalAddress () const
 
void cachePeerAddress () const
 
bool isZeroCopyRequest (WriteFlags flags)
 
bool isZeroCopyMsg (const cmsghdr &cmsg) const
 
void processZeroCopyMsg (const cmsghdr &cmsg)
 
uint32_t getNextZeroCopyBufId ()
 
void adjustZeroCopyFlags (folly::WriteFlags &flags)
 
void addZeroCopyBuf (std::unique_ptr< folly::IOBuf > &&buf)
 
void addZeroCopyBuf (folly::IOBuf *ptr)
 
void setZeroCopyBuf (std::unique_ptr< folly::IOBuf > &&buf)
 
bool containsZeroCopyBuf (folly::IOBuf *ptr)
 
void releaseZeroCopyBuf (uint32_t id)
 
- Protected Member Functions inherited from folly::AsyncTransport
 ~AsyncTransport () override=default
 
- Protected Member Functions inherited from folly::DelayedDestruction
 ~DelayedDestruction () override=default
 
 DelayedDestruction ()
 
- Protected Member Functions inherited from folly::DelayedDestructionBase
 DelayedDestructionBase ()
 
uint32_t getDestructorGuardCount () const
 
- Protected Member Functions inherited from folly::AsyncReader
virtual ~AsyncReader ()=default
 
- Protected Member Functions inherited from folly::AsyncWriter
virtual ~AsyncWriter ()=default
 

Protected Attributes

uint32_t zeroCopyBufId_ {0}
 
std::unordered_map< uint32_t, folly::IOBuf * > idZeroCopyBufPtrMap_
 
std::unordered_map< folly::IOBuf *, IOBufInfoidZeroCopyBufInfoMap_
 
StateEnum state_
 StateEnum describing current state. More...
 
uint8_t shutdownFlags_
 Shutdown state (ShutdownFlags) More...
 
uint16_t eventFlags_
 EventBase::HandlerFlags settings. More...
 
int fd_
 The socket file descriptor. More...
 
folly::SocketAddress addr_
 The address we tried to connect to. More...
 
folly::SocketAddress localAddr_
 The address we are connecting from. More...
 
uint32_t sendTimeout_
 The send timeout, in milliseconds. More...
 
uint16_t maxReadsPerEvent_
 Max reads per event loop iteration. More...
 
bool isBufferMovable_ {false}
 
int8_t readErr_ {READ_NO_ERROR}
 The read error encountered, if any. More...
 
EventBaseeventBase_
 The EventBase. More...
 
WriteTimeout writeTimeout_
 A timeout for connect and write. More...
 
IoHandler ioHandler_
 A EventHandler to monitor the fd. More...
 
ImmediateReadCB immediateReadHandler_
 LoopCallback for checking read. More...
 
ConnectCallbackconnectCallback_
 ConnectCallback. More...
 
ErrMessageCallbackerrMessageCallback_
 TimestampCallback. More...
 
SendMsgParamsCallbacksendMsgParamCallback_
 < Callback for retrieving More...
 
ReadCallbackreadCallback_
 ReadCallback. More...
 
WriteRequestwriteReqHead_
 Chain of WriteRequests. More...
 
WriteRequestwriteReqTail_
 End of WriteRequest chain. More...
 
std::weak_ptr< ShutdownSocketSetwShutdownSocketSet_
 
size_t appBytesReceived_
 Num of bytes received from socket. More...
 
size_t appBytesWritten_
 Num of bytes written to socket. More...
 
std::unique_ptr< IOBufpreReceivedData_
 
std::chrono::steady_clock::time_point connectStartTime_
 
std::chrono::steady_clock::time_point connectEndTime_
 
std::chrono::milliseconds connectTimeout_ {0}
 
std::unique_ptr< EvbChangeCallbackevbChangeCb_ {nullptr}
 
BufferCallbackbufferCallback_ {nullptr}
 
bool tfoEnabled_ {false}
 
bool tfoAttempted_ {false}
 
bool tfoFinished_ {false}
 
bool noTransparentTls_ {false}
 
bool noTSocks_ {false}
 
bool trackEor_ {false}
 
bool zeroCopyEnabled_ {false}
 
bool zeroCopyVal_ {false}
 
size_t zeroCopyReenableThreshold_ {0}
 
size_t zeroCopyReenableCounter_ {0}
 
std::unique_ptr< const AsyncTransportCertificatepeerCertData_
 
std::unique_ptr< const AsyncTransportCertificateselfCertData_
 

Friends

std::ostream & operator<< (std::ostream &os, const StateEnum &state)
 

Detailed Description

A class for performing asynchronous I/O on a socket.

AsyncSocket allows users to asynchronously wait for data on a socket, and to asynchronously send data.

The APIs for reading and writing are intentionally asymmetric. Waiting for data to read is a persistent API: a callback is installed, and is notified whenever new data is available. It continues to be notified of new events until it is uninstalled.

AsyncSocket does not provide read timeout functionality, because it typically cannot determine when the timeout should be active. Generally, a timeout should only be enabled when processing is blocked waiting on data from the remote endpoint. For server sockets, the timeout should not be active if the server is currently processing one or more outstanding requests for this socket. For client sockets, the timeout should not be active if there are no requests pending on the socket. Additionally, if a client has multiple pending requests, it will ususally want a separate timeout for each request, rather than a single read timeout.

The write API is fairly intuitive: a user can request to send a block of data, and a callback will be informed once the entire block has been transferred to the kernel, or on error. AsyncSocket does provide a send timeout, since most callers want to give up if the remote end stops responding and no further progress can be made sending the data.

Definition at line 81 of file AsyncSocket.h.

Member Typedef Documentation

Definition at line 376 of file AsyncSocket.h.

Definition at line 83 of file AsyncSocket.h.

Member Enumeration Documentation

Enumerator
READ_EOF 
READ_ERROR 
READ_BLOCKING 
READ_NO_ERROR 

Definition at line 940 of file AsyncSocket.h.

Enumerator
SHUT_WRITE_PENDING 

shutdownWrite() called, but we are still waiting on writes to drain

SHUT_WRITE 

writes have been completely shut down

SHUT_READ 

Reads have been shutdown.

At the moment we don't distinguish between remote read shutdown (received EOF from the remote end) and local read shutdown. We can only receive EOF when a read callback is set, and we immediately inform it of the EOF. Therefore there doesn't seem to be any reason to have a separate state of "received EOF but the local side may still want to read".

We also don't currently provide any API for only shutting down the read side of a socket. (This is a no-op as far as TCP is concerned, anyway.)

Definition at line 962 of file AsyncSocket.h.

962  {
964  SHUT_WRITE_PENDING = 0x01,
966  SHUT_WRITE = 0x02,
980  SHUT_READ = 0x04,
981  };
shutdownWrite() called, but we are still waiting on writes to drain
Definition: AsyncSocket.h:964
writes have been completely shut down
Definition: AsyncSocket.h:966
Enumerator
UNINIT 
CONNECTING 
ESTABLISHED 
CLOSED 
ERROR 
FAST_OPEN 

Definition at line 797 of file AsyncSocket.h.

797  : uint8_t {
798  UNINIT,
799  CONNECTING,
800  ESTABLISHED,
801  CLOSED,
802  ERROR,
803  FAST_OPEN,
804  };
Enumerator
WRITE_ERROR 

Definition at line 947 of file AsyncSocket.h.

947  {
948  WRITE_ERROR = -1,
949  };

Constructor & Destructor Documentation

folly::AsyncSocket::AsyncSocket ( )
explicit

Definition at line 277 of file AsyncSocket.cpp.

References init().

Referenced by folly::AsyncSocket::SendMsgParamsCallback::getFlagsImpl(), and newSocket().

278  : eventBase_(nullptr),
279  writeTimeout_(this, nullptr),
280  ioHandler_(this, nullptr),
281  immediateReadHandler_(this) {
282  VLOG(5) << "new AsyncSocket()";
283  init();
284 }
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
ImmediateReadCB immediateReadHandler_
LoopCallback for checking read.
Definition: AsyncSocket.h:1243
IoHandler ioHandler_
A EventHandler to monitor the fd.
Definition: AsyncSocket.h:1242
WriteTimeout writeTimeout_
A timeout for connect and write.
Definition: AsyncSocket.h:1241
folly::AsyncSocket::AsyncSocket ( EventBase evb)
explicit

Create a new unconnected AsyncSocket.

connect() must later be called on this socket to establish a connection.

Definition at line 286 of file AsyncSocket.cpp.

References init().

287  : eventBase_(evb),
288  writeTimeout_(this, evb),
289  ioHandler_(this, evb),
290  immediateReadHandler_(this) {
291  VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
292  init();
293 }
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
ImmediateReadCB immediateReadHandler_
LoopCallback for checking read.
Definition: AsyncSocket.h:1243
IoHandler ioHandler_
A EventHandler to monitor the fd.
Definition: AsyncSocket.h:1242
WriteTimeout writeTimeout_
A timeout for connect and write.
Definition: AsyncSocket.h:1241
folly::AsyncSocket::AsyncSocket ( EventBase evb,
const folly::SocketAddress address,
uint32_t  connectTimeout = 0 
)

Create a new AsyncSocket and begin the connection process.

Parameters
evbEventBase that will manage this socket.
addressThe address to connect to.
connectTimeoutOptional timeout in milliseconds for the connection attempt.

Definition at line 295 of file AsyncSocket.cpp.

References connect().

299  : AsyncSocket(evb) {
300  connect(nullptr, address, connectTimeout);
301 }
virtual void connect(ConnectCallback *callback, const folly::SocketAddress &address, int timeout=0, const OptionMap &options=emptyOptionMap, const folly::SocketAddress &bindAddr=anyAddress()) noexcept
folly::AsyncSocket::AsyncSocket ( EventBase evb,
const std::string ip,
uint16_t  port,
uint32_t  connectTimeout = 0 
)

Create a new AsyncSocket and begin the connection process.

Parameters
evbEventBase that will manage this socket.
ipIP address to connect to (dotted-quad).
portDestination port in host byte order.
connectTimeoutOptional timeout in milliseconds for the connection attempt.

Definition at line 303 of file AsyncSocket.cpp.

References connect().

308  : AsyncSocket(evb) {
309  connect(nullptr, ip, port, connectTimeout);
310 }
virtual void connect(ConnectCallback *callback, const folly::SocketAddress &address, int timeout=0, const OptionMap &options=emptyOptionMap, const folly::SocketAddress &bindAddr=anyAddress()) noexcept
folly::AsyncSocket::AsyncSocket ( EventBase evb,
int  fd,
uint32_t  zeroCopyBufId = 0 
)

Create a AsyncSocket from an already connected socket file descriptor.

Note that while AsyncSocket enables TCP_NODELAY for sockets it creates when connecting, it does not change the socket options when given an existing file descriptor. If callers want TCP_NODELAY enabled when using this version of the constructor, they need to explicitly call setNoDelay(true) after the constructor returns.

Parameters
evbEventBase that will manage this socket.
fdFile descriptor to take over (should be a connected socket).
zeroCopyBufIdZerocopy buf id to start with.

Definition at line 312 of file AsyncSocket.cpp.

References ESTABLISHED, fd_, init(), noTransparentTls_, noTSocks_, setCloseOnExec(), and state_.

313  : zeroCopyBufId_(zeroCopyBufId),
314  eventBase_(evb),
315  writeTimeout_(this, evb),
316  ioHandler_(this, evb, fd),
317  immediateReadHandler_(this) {
318  VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ", fd=" << fd
319  << ", zeroCopyBufId=" << zeroCopyBufId << ")";
320  init();
321  fd_ = fd;
322  disableTransparentFunctions(fd_, noTransparentTls_, noTSocks_);
323  setCloseOnExec();
325 }
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
ImmediateReadCB immediateReadHandler_
LoopCallback for checking read.
Definition: AsyncSocket.h:1243
IoHandler ioHandler_
A EventHandler to monitor the fd.
Definition: AsyncSocket.h:1242
WriteTimeout writeTimeout_
A timeout for connect and write.
Definition: AsyncSocket.h:1241
uint32_t zeroCopyBufId_
Definition: AsyncSocket.h:1216
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
folly::AsyncSocket::AsyncSocket ( AsyncSocket::UniquePtr  oldAsyncSocket)
explicit

Create an AsyncSocket from a different, already connected AsyncSocket.

Similar to AsyncSocket(evb, fd) when fd was previously owned by an AsyncSocket.

Definition at line 327 of file AsyncSocket.cpp.

References folly::gen::move, and preReceivedData_.

328  : AsyncSocket(
329  oldAsyncSocket->getEventBase(),
330  oldAsyncSocket->detachFd(),
331  oldAsyncSocket->getZeroCopyBufId()) {
332  preReceivedData_ = std::move(oldAsyncSocket->preReceivedData_);
333 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::unique_ptr< IOBuf > preReceivedData_
Definition: AsyncSocket.h:1258
folly::AsyncSocket::~AsyncSocket ( )
overrideprotected

Protected destructor.

Users of AsyncSocket must never delete it directly. Instead, invoke destroy() instead. (See the documentation in DelayedDestruction.h for more details.)

Definition at line 358 of file AsyncSocket.cpp.

References eventBase_, fd_, and state_.

358  {
359  VLOG(7) << "actual destruction of AsyncSocket(this=" << this
360  << ", evb=" << eventBase_ << ", fd=" << fd_ << ", state=" << state_
361  << ")";
362 }
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229

Member Function Documentation

void folly::AsyncSocket::addZeroCopyBuf ( std::unique_ptr< folly::IOBuf > &&  buf)
protected

Definition at line 924 of file AsyncSocket.cpp.

References getNextZeroCopyBufId(), idZeroCopyBufInfoMap_, idZeroCopyBufPtrMap_, folly::gen::move, ptr, and uint32_t.

Referenced by getNextZeroCopyBufId(), folly::AsyncSocket::BytesWriteRequest::performWrite(), and writeImpl().

924  {
926  folly::IOBuf* ptr = buf.get();
927 
929  auto& p = idZeroCopyBufInfoMap_[ptr];
930  p.count_++;
931  CHECK(p.buf_.get() == nullptr);
932  p.buf_ = std::move(buf);
933 }
void * ptr
std::unordered_map< uint32_t, folly::IOBuf * > idZeroCopyBufPtrMap_
Definition: AsyncSocket.h:1223
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
uint32_t getNextZeroCopyBufId()
Definition: AsyncSocket.h:1202
std::unordered_map< folly::IOBuf *, IOBufInfo > idZeroCopyBufInfoMap_
Definition: AsyncSocket.h:1224
void folly::AsyncSocket::addZeroCopyBuf ( folly::IOBuf ptr)
protected

Definition at line 935 of file AsyncSocket.cpp.

References getNextZeroCopyBufId(), idZeroCopyBufInfoMap_, idZeroCopyBufPtrMap_, ptr, and uint32_t.

935  {
938 
939  idZeroCopyBufInfoMap_[ptr].count_++;
940 }
void * ptr
std::unordered_map< uint32_t, folly::IOBuf * > idZeroCopyBufPtrMap_
Definition: AsyncSocket.h:1223
uint32_t getNextZeroCopyBufId()
Definition: AsyncSocket.h:1202
std::unordered_map< folly::IOBuf *, IOBufInfo > idZeroCopyBufInfoMap_
Definition: AsyncSocket.h:1224
void folly::AsyncSocket::adjustZeroCopyFlags ( folly::WriteFlags flags)
protected

Definition at line 909 of file AsyncSocket.cpp.

References folly::unSet(), folly::WRITE_MSG_ZEROCOPY, zeroCopyEnabled_, and zeroCopyReenableCounter_.

Referenced by getNextZeroCopyBufId(), folly::AsyncSocket::BytesWriteRequest::performWrite(), and writeChain().

909  {
910  if (!zeroCopyEnabled_) {
911  // if the zeroCopyReenableCounter_ is > 0
912  // we try to dec and if we reach 0
913  // we set zeroCopyEnabled_ to true
915  if (0 == --zeroCopyReenableCounter_) {
916  zeroCopyEnabled_ = true;
917  return;
918  }
919  }
921  }
922 }
flags
Definition: http_parser.h:127
size_t zeroCopyReenableCounter_
Definition: AsyncSocket.h:1279
WriteFlags unSet(WriteFlags a, WriteFlags b)
const folly::SocketAddress & folly::AsyncSocket::anyAddress ( )
static

Definition at line 394 of file AsyncSocket.cpp.

Referenced by connect(), folly::AsyncSSLSocket::getSecurityProtocol(), main(), and proxygen::HTTPConnector::Callback::~Callback().

394  {
395  static const folly::SocketAddress anyAddress =
396  folly::SocketAddress("0.0.0.0", 0);
397  return anyAddress;
398 }
static const folly::SocketAddress & anyAddress()
void folly::AsyncSocket::attachEventBase ( EventBase eventBase)
overridevirtual

Attach the transport to a EventBase.

This may only be called if the transport is not currently attached to a EventBase (by an earlier call to detachEventBase()).

This method must be invoked in the EventBase's thread.

Implements folly::AsyncTransport.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 1500 of file AsyncSocket.cpp.

References folly::EventHandler::attachEventBase(), folly::AsyncTimeout::attachEventBase(), folly::EventBase::dcheckIsInEventBaseThread(), evbChangeCb_, eventBase_, eventFlags_, fd_, ioHandler_, state_, updateEventRegistration(), and writeTimeout_.

Referenced by folly::AsyncSSLSocket::attachEventBase(), and writeRequestReady().

1500  {
1501  VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1502  << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1503  << ", state=" << state_ << ", events=" << std::hex << eventFlags_
1504  << ")";
1505  assert(eventBase_ == nullptr);
1506  eventBase->dcheckIsInEventBaseThread();
1507 
1508  eventBase_ = eventBase;
1509  ioHandler_.attachEventBase(eventBase);
1510 
1512 
1513  writeTimeout_.attachEventBase(eventBase);
1514  if (evbChangeCb_) {
1515  evbChangeCb_->evbAttached(this);
1516  }
1517 }
std::unique_ptr< EvbChangeCallback > evbChangeCb_
Definition: AsyncSocket.h:1265
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
void attachEventBase(EventBase *eventBase)
bool updateEventRegistration()
IoHandler ioHandler_
A EventHandler to monitor the fd.
Definition: AsyncSocket.h:1242
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
WriteTimeout writeTimeout_
A timeout for connect and write.
Definition: AsyncSocket.h:1241
void attachEventBase(EventBase *eventBase, InternalEnum internal=InternalEnum::NORMAL)
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::cacheAddresses ( )

Attempt to cache the current local and peer addresses (if not already cached) so that they are available from getPeerAddress() and getLocalAddress() even after the socket is closed.

Definition at line 1544 of file AsyncSocket.cpp.

References cacheLocalAddress(), cachePeerAddress(), and fd_.

Referenced by setEvbChangedCallback(), folly::AsyncSSLSocket::sslAccept(), and folly::AsyncSSLSocket::sslConn().

1544  {
1545  if (fd_ >= 0) {
1546  try {
1548  cachePeerAddress();
1549  } catch (const std::system_error& e) {
1550  if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
1551  VLOG(2) << "Error caching addresses: " << e.code().value() << ", "
1552  << e.code().message();
1553  }
1554  }
1555  }
1556 }
void cacheLocalAddress() const
void cachePeerAddress() const
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::cacheLocalAddress ( ) const
protected

Definition at line 1558 of file AsyncSocket.cpp.

References fd_, folly::SocketAddress::isInitialized(), localAddr_, and folly::SocketAddress::setFromLocalAddress().

Referenced by cacheAddresses(), getLocalAddress(), scheduleInitialReadWrite(), and setErrMessageCB().

1558  {
1559  if (!localAddr_.isInitialized()) {
1561  }
1562 }
folly::SocketAddress localAddr_
The address we are connecting from.
Definition: AsyncSocket.h:1231
bool isInitialized() const
void setFromLocalAddress(int socket)
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::cachePeerAddress ( ) const
protected

Definition at line 1564 of file AsyncSocket.cpp.

References addr_, fd_, folly::SocketAddress::isInitialized(), and folly::SocketAddress::setFromPeerAddress().

Referenced by cacheAddresses(), getPeerAddress(), and scheduleInitialReadWrite().

1564  {
1565  if (!addr_.isInitialized()) {
1567  }
1568 }
void setFromPeerAddress(int socket)
folly::SocketAddress addr_
The address we tried to connect to.
Definition: AsyncSocket.h:1230
bool isInitialized() const
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::cancelConnect ( )

If a connect request is in-flight, cancels it and closes the socket immediately. Otherwise, this is a no-op.

This does not invoke any connection related callbacks. Call this to prevent any connect callback while cleaning up, etc.

Definition at line 659 of file AsyncSocket.cpp.

References closeNow(), connectCallback_, CONNECTING, FAST_OPEN, and state_.

659  {
660  connectCallback_ = nullptr;
662  closeNow();
663  }
664 }
void closeNow() override
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
ConnectCallback * connectCallback_
ConnectCallback.
Definition: AsyncSocket.h:1245
void folly::AsyncSocket::checkForImmediateRead ( )
protectedvirtualnoexcept

Reimplemented in AsyncSocketImmediateRead, and folly::AsyncSSLSocket.

Definition at line 2147 of file AsyncSocket.cpp.

References handleRead(), and preReceivedData_.

Referenced by folly::AsyncSSLSocket::checkForImmediateRead(), handleInitialReadWrite(), scheduleInitialReadWrite(), and setReadCB().

2147  {
2148  // We currently don't attempt to perform optimistic reads in AsyncSocket.
2149  // (However, note that some subclasses do override this method.)
2150  //
2151  // Simply calling handleRead() here would be bad, as this would call
2152  // readCallback_->getReadBuffer(), forcing the callback to allocate a read
2153  // buffer even though no data may be available. This would waste lots of
2154  // memory, since the buffer will sit around unused until the socket actually
2155  // becomes readable.
2156  //
2157  // Checking if the socket is readable now also seems like it would probably
2158  // be a pessimism. In most cases it probably wouldn't be readable, and we
2159  // would just waste an extra system call. Even if it is readable, waiting to
2160  // find out from libevent on the next event loop doesn't seem that bad.
2161  //
2162  // The exception to this is if we have pre-received data. In that case there
2163  // is definitely data available immediately.
2164  if (preReceivedData_ && !preReceivedData_->empty()) {
2165  handleRead();
2166  }
2167 }
virtual void handleRead() noexcept
std::unique_ptr< IOBuf > preReceivedData_
Definition: AsyncSocket.h:1258
void folly::AsyncSocket::close ( )
overridevirtual

Close the transport.

This gracefully closes the transport, waiting for all pending write requests to complete before actually closing the underlying transport.

If a read callback is set, readEOF() will be called immediately. If there are outstanding write requests, the close will be delayed until all remaining writes have completed. No new writes may be started after close() has been called.

Implements folly::AsyncTransport.

Definition at line 1198 of file AsyncSocket.cpp.

References closeNow(), CONNECTING, folly::EventBase::dcheckIsInEventBaseThread(), ERROR, ESTABLISHED, eventBase_, fd_, folly::EventHandler::READ, readCallback_, folly::AsyncReader::ReadCallback::readEOF(), SHUT_READ, SHUT_WRITE_PENDING, shutdownFlags_, state_, updateEventRegistration(), and writeReqHead_.

Referenced by doClose(), folly::AsyncSSLSocket::shutdownWrite(), TEST(), and writeRequestReady().

1198  {
1199  VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
1200  << ", state=" << state_ << ", shutdownFlags=" << std::hex
1201  << (int)shutdownFlags_;
1202 
1203  // close() is only different from closeNow() when there are pending writes
1204  // that need to drain before we can close. In all other cases, just call
1205  // closeNow().
1206  //
1207  // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
1208  // STATE_ERROR if close() is invoked while a previous closeNow() or failure
1209  // is still running. (e.g., If there are multiple pending writes, and we
1210  // call writeError() on the first one, it may call close(). In this case we
1211  // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
1212  // writes will still be in the queue.)
1213  //
1214  // We only need to drain pending writes if we are still in STATE_CONNECTING
1215  // or STATE_ESTABLISHED
1216  if ((writeReqHead_ == nullptr) ||
1218  closeNow();
1219  return;
1220  }
1221 
1222  // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
1223  // destroyed until close() returns.
1224  DestructorGuard dg(this);
1226 
1227  // Since there are write requests pending, we have to set the
1228  // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
1229  // connect finishes and we finish writing these requests.
1230  //
1231  // Set SHUT_READ to indicate that reads are shut down, and set the
1232  // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
1233  // pending writes complete.
1235 
1236  // If a read callback is set, invoke readEOF() immediately to inform it that
1237  // the socket has been closed and no more data can be read.
1238  if (readCallback_) {
1239  // Disable reads if they are enabled
1241  // We're now in the error state; callbacks have been cleaned up
1242  assert(state_ == StateEnum::ERROR);
1243  assert(readCallback_ == nullptr);
1244  } else {
1245  ReadCallback* callback = readCallback_;
1246  readCallback_ = nullptr;
1247  callback->readEOF();
1248  }
1249  }
1250 }
shutdownWrite() called, but we are still waiting on writes to drain
Definition: AsyncSocket.h:964
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
void closeNow() override
bool updateEventRegistration()
WriteRequest * writeReqHead_
Chain of WriteRequests.
Definition: AsyncSocket.h:1250
uint8_t shutdownFlags_
Shutdown state (ShutdownFlags)
Definition: AsyncSocket.h:1227
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
ReadCallback * readCallback_
ReadCallback.
Definition: AsyncSocket.h:1249
AsyncReader::ReadCallback ReadCallback
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
virtual void readEOF() noexcept=0
void folly::AsyncSocket::closeNow ( )
overridevirtual

Close the transport immediately.

This closes the transport immediately, dropping any outstanding data waiting to be written.

If a read callback is set, readEOF() will be called immediately. If there are outstanding write requests, these requests will be aborted and writeError() will be invoked immediately on all outstanding write callbacks.

Implements folly::AsyncTransport.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 1252 of file AsyncSocket.cpp.

References folly::EventBase::LoopCallback::cancelLoopCallback(), folly::AsyncTimeout::cancelTimeout(), folly::EventHandler::changeHandlerFD(), CLOSED, connectCallback_, CONNECTING, folly::EventBase::dcheckIsInEventBaseThread(), folly::DFATAL, doClose(), ERROR, ESTABLISHED, eventBase_, eventFlags_, failAllWrites(), FAST_OPEN, fd_, immediateReadHandler_, invokeConnectErr(), ioHandler_, folly::EventBase::LoopCallback::isLoopCallbackScheduled(), folly::EventHandler::NONE, readCallback_, folly::AsyncReader::ReadCallback::readEOF(), SHUT_READ, SHUT_WRITE, shutdownFlags_, folly::socketClosedLocallyEx, state_, UNINIT, updateEventRegistration(), writeReqHead_, and writeTimeout_.

Referenced by cancelConnect(), close(), folly::AsyncSSLSocket::closeNow(), closeWithReset(), folly::test::MockAsyncSocket::connect(), destroy(), detachFd(), shutdownWriteNow(), and writeRequestReady().

1252  {
1253  VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
1254  << ", state=" << state_ << ", shutdownFlags=" << std::hex
1255  << (int)shutdownFlags_;
1256  DestructorGuard dg(this);
1257  if (eventBase_) {
1259  }
1260 
1261  switch (state_) {
1263  case StateEnum::CONNECTING:
1264  case StateEnum::FAST_OPEN: {
1267 
1268  // If the write timeout was set, cancel it.
1270 
1271  // If we are registered for I/O events, unregister.
1274  if (!updateEventRegistration()) {
1275  // We will have been moved into the error state.
1276  assert(state_ == StateEnum::ERROR);
1277  return;
1278  }
1279  }
1280 
1283  }
1284 
1285  if (fd_ >= 0) {
1287  doClose();
1288  }
1289 
1291 
1293 
1294  if (readCallback_) {
1295  ReadCallback* callback = readCallback_;
1296  readCallback_ = nullptr;
1297  callback->readEOF();
1298  }
1299  return;
1300  }
1301  case StateEnum::CLOSED:
1302  // Do nothing. It's possible that we are being called recursively
1303  // from inside a callback that we invoked inside another call to close()
1304  // that is still running.
1305  return;
1306  case StateEnum::ERROR:
1307  // Do nothing. The error handling code has performed (or is performing)
1308  // cleanup.
1309  return;
1310  case StateEnum::UNINIT:
1311  assert(eventFlags_ == EventHandler::NONE);
1312  assert(connectCallback_ == nullptr);
1313  assert(readCallback_ == nullptr);
1314  assert(writeReqHead_ == nullptr);
1317  return;
1318  }
1319 
1320  LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
1321  << ") called in unknown state " << state_;
1322 }
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
bool updateEventRegistration()
WriteRequest * writeReqHead_
Chain of WriteRequests.
Definition: AsyncSocket.h:1250
void failAllWrites(const AsyncSocketException &ex)
uint8_t shutdownFlags_
Shutdown state (ShutdownFlags)
Definition: AsyncSocket.h:1227
bool isLoopCallbackScheduled() const
Definition: EventBase.h:160
ImmediateReadCB immediateReadHandler_
LoopCallback for checking read.
Definition: AsyncSocket.h:1243
IoHandler ioHandler_
A EventHandler to monitor the fd.
Definition: AsyncSocket.h:1242
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
WriteTimeout writeTimeout_
A timeout for connect and write.
Definition: AsyncSocket.h:1241
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
void changeHandlerFD(int fd)
Definition: EventHandler.h:143
ReadCallback * readCallback_
ReadCallback.
Definition: AsyncSocket.h:1249
AsyncReader::ReadCallback ReadCallback
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
writes have been completely shut down
Definition: AsyncSocket.h:966
const AsyncSocketException socketClosedLocallyEx(AsyncSocketException::END_OF_FILE,"socket closed locally")
virtual void readEOF() noexcept=0
virtual void invokeConnectErr(const AsyncSocketException &ex)
ConnectCallback * connectCallback_
ConnectCallback.
Definition: AsyncSocket.h:1245
void folly::AsyncSocket::closeWithReset ( )
overridevirtual

Reset the transport immediately.

This closes the transport immediately, sending a reset to the remote peer if possible to indicate abnormal shutdown.

Note that not all subclasses implement this reset functionality: some subclasses may treat reset() the same as closeNow(). Subclasses that use TCP transports should terminate the connection with a TCP reset.

Reimplemented from folly::AsyncTransport.

Definition at line 1324 of file AsyncSocket.cpp.

References closeNow(), fd_, and setSockOpt().

Referenced by writeRequestReady().

1324  {
1325  // Enable SO_LINGER, with the linger timeout set to 0.
1326  // This will trigger a TCP reset when we close the socket.
1327  if (fd_ >= 0) {
1328  struct linger optLinger = {1, 0};
1329  if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
1330  VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
1331  << "on " << fd_ << ": errno=" << errno;
1332  }
1333  }
1334 
1335  // Then let closeNow() take care of the rest
1336  closeNow();
1337 }
int setSockOpt(int level, int optname, const T *optval)
Definition: AsyncSocket.h:727
void closeNow() override
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::connect ( ConnectCallback callback,
const folly::SocketAddress address,
int  timeout = 0,
const OptionMap options = emptyOptionMap,
const folly::SocketAddress bindAddr = anyAddress() 
)
virtualnoexcept

Initiate a connection.

Parameters
callbackThe callback to inform when the connection attempt completes.
addressThe address to connect to.
timeoutA timeout value, in milliseconds. If the connection does not succeed within this period, callback->connectError() will be invoked.

Reimplemented in folly::AsyncSSLSocket, folly::test::MockAsyncSSLSocket, and folly::test::MockAsyncSocket.

Definition at line 431 of file AsyncSocket.cpp.

References folly::ShutdownSocketSet::add(), addr_, anyAddress(), folly::netops::bind(), folly::EventHandler::changeHandlerFD(), connectCallback_, connectEndTime_, CONNECTING, connectStartTime_, connectTimeout_, folly::EventBase::dcheckIsInEventBaseThread(), doClose(), errMessageCallback_, ESTABLISHED, eventBase_, failConnect(), FAST_OPEN, fd_, folly::SocketAddress::getActualSize(), folly::AsyncSocketException::INTERNAL_ERROR, invalidState(), invokeConnectSuccess(), ioHandler_, name, folly::AsyncSocketException::NOT_OPEN, noTransparentTls_, noTSocks_, now(), readCallback_, setCloseOnExec(), setNoDelay(), folly::netops::setsockopt(), setZeroCopy(), folly::test::shutdownSocketSet, folly::netops::socket(), socketConnect(), state_, tfoAttempted_, tfoEnabled_, folly::detail::timeout, UNINIT, withAddr(), writeReqHead_, wShutdownSocketSet_, and zeroCopyVal_.

Referenced by AsyncSocket(), folly::AsyncSSLSocket::connect(), connect(), folly::AsyncSSLSocket::getSecurityProtocol(), SSLCacheClient::start(), and TEST().

436  {
437  DestructorGuard dg(this);
439 
440  addr_ = address;
441 
442  // Make sure we're in the uninitialized state
443  if (state_ != StateEnum::UNINIT) {
444  return invalidState(callback);
445  }
446 
447  connectTimeout_ = std::chrono::milliseconds(timeout);
449  // Make connect end time at least >= connectStartTime.
451 
452  assert(fd_ == -1);
454  connectCallback_ = callback;
455 
456  sockaddr_storage addrStorage;
457  sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
458 
459  try {
460  // Create the socket
461  // Technically the first parameter should actually be a protocol family
462  // constant (PF_xxx) rather than an address family (AF_xxx), but the
463  // distinction is mainly just historical. In pretty much all
464  // implementations the PF_foo and AF_foo constants are identical.
465  fd_ = fsp::socket(address.getFamily(), SOCK_STREAM, 0);
466  if (fd_ < 0) {
467  auto errnoCopy = errno;
468  throw AsyncSocketException(
470  withAddr("failed to create socket"),
471  errnoCopy);
472  }
473  disableTransparentFunctions(fd_, noTransparentTls_, noTSocks_);
474  if (const auto shutdownSocketSet = wShutdownSocketSet_.lock()) {
476  }
478 
479  setCloseOnExec();
480 
481  // Put the socket in non-blocking mode
482  int flags = fcntl(fd_, F_GETFL, 0);
483  if (flags == -1) {
484  auto errnoCopy = errno;
485  throw AsyncSocketException(
487  withAddr("failed to get socket flags"),
488  errnoCopy);
489  }
490  int rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
491  if (rv == -1) {
492  auto errnoCopy = errno;
493  throw AsyncSocketException(
495  withAddr("failed to put socket in non-blocking mode"),
496  errnoCopy);
497  }
498 
499 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
500  // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
501  rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
502  if (rv == -1) {
503  auto errnoCopy = errno;
504  throw AsyncSocketException(
506  "failed to enable F_SETNOSIGPIPE on socket",
507  errnoCopy);
508  }
509 #endif
510 
511  // By default, turn on TCP_NODELAY
512  // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
513  // setNoDelay() will log an error message if it fails.
514  // Also set the cached zeroCopyVal_ since it cannot be set earlier if the fd
515  // is not created
516  if (address.getFamily() != AF_UNIX) {
517  (void)setNoDelay(true);
519  }
520 
521  VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
522  << ", fd=" << fd_ << ", host=" << address.describe().c_str();
523 
524  // bind the socket
525  if (bindAddr != anyAddress()) {
526  int one = 1;
527  if (setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
528  auto errnoCopy = errno;
529  doClose();
530  throw AsyncSocketException(
532  "failed to setsockopt prior to bind on " + bindAddr.describe(),
533  errnoCopy);
534  }
535 
536  bindAddr.getAddress(&addrStorage);
537 
538  if (bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
539  auto errnoCopy = errno;
540  doClose();
541  throw AsyncSocketException(
543  "failed to bind to async socket: " + bindAddr.describe(),
544  errnoCopy);
545  }
546  }
547 
548  // Apply the additional options if any.
549  for (const auto& opt : options) {
550  rv = opt.first.apply(fd_, opt.second);
551  if (rv != 0) {
552  auto errnoCopy = errno;
553  throw AsyncSocketException(
555  withAddr("failed to set socket option"),
556  errnoCopy);
557  }
558  }
559 
560  // Perform the connect()
561  address.getAddress(&addrStorage);
562 
563  if (tfoEnabled_) {
565  tfoAttempted_ = true;
566  } else {
567  if (socketConnect(saddr, addr_.getActualSize()) < 0) {
568  return;
569  }
570  }
571 
572  // If we're still here the connect() succeeded immediately.
573  // Fall through to call the callback outside of this try...catch block
574  } catch (const AsyncSocketException& ex) {
575  return failConnect(__func__, ex);
576  } catch (const std::exception& ex) {
577  // shouldn't happen, but handle it just in case
578  VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
579  << "): unexpected " << typeid(ex).name()
580  << " exception: " << ex.what();
581  AsyncSocketException tex(
583  withAddr(string("unexpected exception: ") + ex.what()));
584  return failConnect(__func__, tex);
585  }
586 
587  // The connection succeeded immediately
588  // The read callback may not have been set yet, and no writes may be pending
589  // yet, so we don't have to register for any events at the moment.
590  VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
591  assert(errMessageCallback_ == nullptr);
592  assert(readCallback_ == nullptr);
593  assert(writeReqHead_ == nullptr);
594  if (state_ != StateEnum::FAST_OPEN) {
596  }
598 }
flags
Definition: http_parser.h:127
std::string withAddr(const std::string &s)
int setsockopt(NetworkSocket s, int level, int optname, const void *optval, socklen_t optlen)
Definition: NetOps.cpp:384
std::chrono::steady_clock::time_point now()
socklen_t getActualSize() const
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
folly::SocketAddress addr_
The address we tried to connect to.
Definition: AsyncSocket.h:1230
std::string describe() const
std::chrono::steady_clock::time_point connectStartTime_
Definition: AsyncSocket.h:1260
WriteRequest * writeReqHead_
Chain of WriteRequests.
Definition: AsyncSocket.h:1250
std::chrono::milliseconds connectTimeout_
Definition: AsyncSocket.h:1263
std::weak_ptr< ShutdownSocketSet > wShutdownSocketSet_
Definition: AsyncSocket.h:1252
const char * name
Definition: http_parser.c:437
bool setZeroCopy(bool enable)
void invalidState(ConnectCallback *callback)
sa_family_t getFamily() const
static const folly::SocketAddress & anyAddress()
IoHandler ioHandler_
A EventHandler to monitor the fd.
Definition: AsyncSocket.h:1242
ErrMessageCallback * errMessageCallback_
TimestampCallback.
Definition: AsyncSocket.h:1246
ShutdownSocketSet shutdownSocketSet
void failConnect(const char *fn, const AsyncSocketException &ex)
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
socklen_t getAddress(sockaddr_storage *addr) const
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
std::chrono::steady_clock::time_point connectEndTime_
Definition: AsyncSocket.h:1261
void changeHandlerFD(int fd)
Definition: EventHandler.h:143
ReadCallback * readCallback_
ReadCallback.
Definition: AsyncSocket.h:1249
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int bind(NetworkSocket s, const sockaddr *name, socklen_t namelen)
Definition: NetOps.cpp:76
virtual void invokeConnectSuccess()
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
int socketConnect(const struct sockaddr *addr, socklen_t len)
int setNoDelay(bool noDelay)
ConnectCallback * connectCallback_
ConnectCallback.
Definition: AsyncSocket.h:1245
void folly::AsyncSocket::connect ( ConnectCallback callback,
const std::string ip,
uint16_t  port,
int  timeout = 0,
const OptionMap options = emptyOptionMap 
)
noexcept

Definition at line 643 of file AsyncSocket.cpp.

References connect(), connectCallback_, failConnect(), folly::AsyncSocketException::INTERNAL_ERROR, and folly::detail::timeout.

648  {
649  DestructorGuard dg(this);
650  try {
651  connectCallback_ = callback;
652  connect(callback, folly::SocketAddress(ip, port), timeout, options);
653  } catch (const std::exception& ex) {
654  AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR, ex.what());
655  return failConnect(__func__, tex);
656  }
657 }
virtual void connect(ConnectCallback *callback, const folly::SocketAddress &address, int timeout=0, const OptionMap &options=emptyOptionMap, const folly::SocketAddress &bindAddr=anyAddress()) noexcept
void failConnect(const char *fn, const AsyncSocketException &ex)
ConnectCallback * connectCallback_
ConnectCallback.
Definition: AsyncSocket.h:1245
bool folly::AsyncSocket::connecting ( ) const
inlineoverridevirtual

Determine if transport is connected to the endpoint

Returns
false iff the transport is connected, otherwise true

Implements folly::AsyncTransport.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 567 of file AsyncSocket.h.

References CONNECTING, and state_.

Referenced by folly::AsyncSSLSocket::connecting(), and writeImpl().

567  {
568  return (state_ == StateEnum::CONNECTING);
569  }
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
bool folly::AsyncSocket::containsZeroCopyBuf ( folly::IOBuf ptr)
protected

Definition at line 963 of file AsyncSocket.cpp.

References idZeroCopyBufInfoMap_.

Referenced by getNextZeroCopyBufId(), and folly::AsyncSocket::BytesWriteRequest::performWrite().

963  {
964  return (idZeroCopyBufInfoMap_.find(ptr) != idZeroCopyBufInfoMap_.end());
965 }
std::unordered_map< folly::IOBuf *, IOBufInfo > idZeroCopyBufInfoMap_
Definition: AsyncSocket.h:1224
void folly::AsyncSocket::destroy ( )
overridevirtual

Destroy the socket.

AsyncSocket::destroy() must be called to destroy the socket. The normal destructor is private, and should not be invoked directly. This prevents callers from deleting a AsyncSocket while it is invoking a callback.

Reimplemented from folly::DelayedDestruction.

Definition at line 364 of file AsyncSocket.cpp.

References closeNow(), folly::DelayedDestruction::destroy(), eventBase_, fd_, and state_.

Referenced by newSocket(), SSLCacheClient::start(), folly::AsyncSocket::WriteRequest::start(), and SSLCacheClient::~SSLCacheClient().

364  {
365  VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
366  << ", fd=" << fd_ << ", state=" << state_;
367  // When destroy is called, close the socket immediately
368  closeNow();
369 
370  // Then call DelayedDestruction::destroy() to take care of
371  // whether or not we need immediate or delayed destruction
373 }
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
void closeNow() override
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::detachEventBase ( )
overridevirtual

Detach the transport from its EventBase.

This may only be called when the transport is idle and has no reads or writes pending. Once detached, the transport may not be used again until it is re-attached to a EventBase by calling attachEventBase().

This method must be called from the current EventBase's thread.

Implements folly::AsyncTransport.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 1519 of file AsyncSocket.cpp.

References folly::EventBase::dcheckIsInEventBaseThread(), folly::EventHandler::detachEventBase(), folly::AsyncTimeout::detachEventBase(), evbChangeCb_, eventBase_, eventFlags_, fd_, ioHandler_, state_, folly::EventHandler::unregisterHandler(), and writeTimeout_.

Referenced by folly::AsyncSSLSocket::detachEventBase(), and writeRequestReady().

1519  {
1520  VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1521  << ", old evb=" << eventBase_ << ", state=" << state_
1522  << ", events=" << std::hex << eventFlags_ << ")";
1523  assert(eventBase_ != nullptr);
1525 
1526  eventBase_ = nullptr;
1527 
1529 
1532  if (evbChangeCb_) {
1533  evbChangeCb_->evbDetached(this);
1534  }
1535 }
std::unique_ptr< EvbChangeCallback > evbChangeCb_
Definition: AsyncSocket.h:1265
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
IoHandler ioHandler_
A EventHandler to monitor the fd.
Definition: AsyncSocket.h:1242
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
WriteTimeout writeTimeout_
A timeout for connect and write.
Definition: AsyncSocket.h:1241
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
int folly::AsyncSocket::detachFd ( )
virtual

Extract the file descriptor from the AsyncSocket.

This will immediately cause any installed callbacks to be invoked with an error. The AsyncSocket may no longer be used after the file descriptor has been extracted.

This method should be used with care as the resulting fd is not guaranteed to perfectly reflect the state of the AsyncSocket (security state, pre-received data, etc.).

Returns the file descriptor. The caller assumes ownership of the descriptor, and it will not be closed when the AsyncSocket is destroyed.

Definition at line 375 of file AsyncSocket.cpp.

References folly::EventHandler::changeHandlerFD(), closeNow(), eventBase_, eventFlags_, fd_, ioHandler_, state_, and wShutdownSocketSet_.

Referenced by folly::test::MockAsyncSocket::connect(), SSLCacheClient::connectSuccess(), and getFd().

375  {
376  VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
377  << ", evb=" << eventBase_ << ", state=" << state_
378  << ", events=" << std::hex << eventFlags_ << ")";
379  // Extract the fd, and set fd_ to -1 first, so closeNow() won't
380  // actually close the descriptor.
381  if (const auto socketSet = wShutdownSocketSet_.lock()) {
382  socketSet->remove(fd_);
383  }
384  int fd = fd_;
385  fd_ = -1;
386  // Call closeNow() to invoke all pending callbacks with an error.
387  closeNow();
388  // Update the EventHandler to stop using this fd.
389  // This can only be done after closeNow() unregisters the handler.
391  return fd;
392 }
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
void closeNow() override
std::weak_ptr< ShutdownSocketSet > wShutdownSocketSet_
Definition: AsyncSocket.h:1252
IoHandler ioHandler_
A EventHandler to monitor the fd.
Definition: AsyncSocket.h:1242
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
void changeHandlerFD(int fd)
Definition: EventHandler.h:143
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::disableTransparentTls ( )
inline

Definition at line 789 of file AsyncSocket.h.

References noTransparentTls_.

Referenced by fizz::client::AsyncFizzClientT< SM >::connect().

789  {
790  noTransparentTls_ = true;
791  }
void folly::AsyncSocket::disableTSocks ( )
inline

Definition at line 793 of file AsyncSocket.h.

References noTSocks_.

793  {
794  noTSocks_ = true;
795  }
void folly::AsyncSocket::doClose ( )
protected

Definition at line 2790 of file AsyncSocket.cpp.

References folly::ShutdownSocketSet::close(), close(), fd_, idZeroCopyBufInfoMap_, idZeroCopyBufPtrMap_, folly::test::shutdownSocketSet, and wShutdownSocketSet_.

Referenced by closeNow(), connect(), handleWrite(), scheduleInitialReadWrite(), and startFail().

2790  {
2791  if (fd_ == -1) {
2792  return;
2793  }
2794  if (const auto shutdownSocketSet = wShutdownSocketSet_.lock()) {
2796  } else {
2797  ::close(fd_);
2798  }
2799  fd_ = -1;
2800 
2801  // we also want to clear the zerocopy maps
2802  // if the fd has been closed
2803  idZeroCopyBufPtrMap_.clear();
2804  idZeroCopyBufInfoMap_.clear();
2805 }
std::unordered_map< uint32_t, folly::IOBuf * > idZeroCopyBufPtrMap_
Definition: AsyncSocket.h:1223
std::weak_ptr< ShutdownSocketSet > wShutdownSocketSet_
Definition: AsyncSocket.h:1252
ShutdownSocketSet shutdownSocketSet
std::unordered_map< folly::IOBuf *, IOBufInfo > idZeroCopyBufInfoMap_
Definition: AsyncSocket.h:1224
void close() override
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::enableTFO ( )
inline

Enables TFO behavior on the AsyncSocket if FOLLY_ALLOW_TFO is set.

Definition at line 782 of file AsyncSocket.h.

References tfoEnabled_.

782  {
783  // No-op if folly does not allow tfo
784 #if FOLLY_ALLOW_TFO
785  tfoEnabled_ = true;
786 #endif
787  }
bool folly::AsyncSocket::error ( ) const
overridevirtual

Determine if an error has occurred with this transport.

Returns
true iff an error has occurred (not EOF).

Implements folly::AsyncTransport.

Definition at line 1496 of file AsyncSocket.cpp.

References ERROR, and state_.

Referenced by handleConnect(), folly::AsyncSSLSocket::handleInitialReadWrite(), and writeRequestReady().

1496  {
1497  return (state_ == StateEnum::ERROR);
1498 }
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
void folly::AsyncSocket::fail ( const char *  fn,
const AsyncSocketException ex 
)
protected

Definition at line 2569 of file AsyncSocket.cpp.

References addr_, folly::SocketAddress::describe(), fd_, finishFail(), startFail(), and state_.

Referenced by gtest_xml_test_utils.GTestXMLTestCase::_GetChildren(), fatal_test.FatalTests::is_debug_build(), scheduleInitialReadWrite(), and updateEventRegistration().

2569  {
2570  VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2571  << ", state=" << state_ << " host=" << addr_.describe()
2572  << "): failed in " << fn << "(): " << ex.what();
2573  startFail();
2574  finishFail();
2575 }
folly::SocketAddress addr_
The address we tried to connect to.
Definition: AsyncSocket.h:1230
std::string describe() const
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::failAllWrites ( const AsyncSocketException ex)
protected

Definition at line 2661 of file AsyncSocket.cpp.

References folly::AsyncSocket::WriteRequest::destroy(), folly::AsyncSocket::WriteRequest::getCallback(), folly::AsyncSocket::WriteRequest::getNext(), folly::AsyncSocket::WriteRequest::getTotalBytesWritten(), folly::AsyncWriter::WriteCallback::writeErr(), and writeReqHead_.

Referenced by closeNow(), invokeAllErrors(), scheduleInitialReadWrite(), and shutdownWriteNow().

2661  {
2662  // Invoke writeError() on all write callbacks.
2663  // This is used when writes are forcibly shutdown with write requests
2664  // pending, or when an error occurs with writes pending.
2665  while (writeReqHead_ != nullptr) {
2666  WriteRequest* req = writeReqHead_;
2667  writeReqHead_ = req->getNext();
2668  WriteCallback* callback = req->getCallback();
2669  if (callback) {
2670  callback->writeErr(req->getTotalBytesWritten(), ex);
2671  }
2672  req->destroy();
2673  }
2674 }
WriteRequest * getNext() const
Definition: AsyncSocket.h:903
WriteRequest * writeReqHead_
Chain of WriteRequests.
Definition: AsyncSocket.h:1250
void writeErr(size_t nBytesWritten, const folly::AsyncSocketException &ex) noexceptoverride
void folly::AsyncSocket::failConnect ( const char *  fn,
const AsyncSocketException ex 
)
protected

Definition at line 2577 of file AsyncSocket.cpp.

References addr_, folly::SocketAddress::describe(), fd_, finishFail(), invokeConnectErr(), startFail(), and state_.

Referenced by connect(), handleConnect(), scheduleInitialReadWrite(), and timeoutExpired().

2577  {
2578  VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2579  << ", state=" << state_ << " host=" << addr_.describe()
2580  << "): failed while connecting in " << fn << "(): " << ex.what();
2581  startFail();
2582 
2583  invokeConnectErr(ex);
2584  finishFail(ex);
2585 }
folly::SocketAddress addr_
The address we tried to connect to.
Definition: AsyncSocket.h:1230
std::string describe() const
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
virtual void invokeConnectErr(const AsyncSocketException &ex)
void folly::AsyncSocket::failErrMessageRead ( const char *  fn,
const AsyncSocketException ex 
)
protected

Definition at line 2602 of file AsyncSocket.cpp.

References addr_, folly::SocketAddress::describe(), errMessageCallback_, folly::AsyncSocket::ErrMessageCallback::errMessageError(), fd_, finishFail(), startFail(), and state_.

Referenced by handleErrMessages(), and scheduleInitialReadWrite().

2604  {
2605  VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2606  << ", state=" << state_ << " host=" << addr_.describe()
2607  << "): failed while reading message in " << fn << "(): " << ex.what();
2608  startFail();
2609 
2610  if (errMessageCallback_ != nullptr) {
2611  ErrMessageCallback* callback = errMessageCallback_;
2612  errMessageCallback_ = nullptr;
2613  callback->errMessageError(ex);
2614  }
2615 
2616  finishFail();
2617 }
virtual void errMessageError(const AsyncSocketException &ex) noexcept=0
folly::SocketAddress addr_
The address we tried to connect to.
Definition: AsyncSocket.h:1230
std::string describe() const
ErrMessageCallback * errMessageCallback_
TimestampCallback.
Definition: AsyncSocket.h:1246
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::failRead ( const char *  fn,
const AsyncSocketException ex 
)
protected

Definition at line 2587 of file AsyncSocket.cpp.

References addr_, folly::SocketAddress::describe(), fd_, finishFail(), readCallback_, folly::AsyncReader::ReadCallback::readErr(), startFail(), and state_.

Referenced by handleRead(), and scheduleInitialReadWrite().

2587  {
2588  VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2589  << ", state=" << state_ << " host=" << addr_.describe()
2590  << "): failed while reading in " << fn << "(): " << ex.what();
2591  startFail();
2592 
2593  if (readCallback_ != nullptr) {
2594  ReadCallback* callback = readCallback_;
2595  readCallback_ = nullptr;
2596  callback->readErr(ex);
2597  }
2598 
2599  finishFail();
2600 }
folly::SocketAddress addr_
The address we tried to connect to.
Definition: AsyncSocket.h:1230
std::string describe() const
ReadCallback * readCallback_
ReadCallback.
Definition: AsyncSocket.h:1249
AsyncReader::ReadCallback ReadCallback
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
virtual void readErr(const AsyncSocketException &ex) noexcept=0
void folly::AsyncSocket::failWrite ( const char *  fn,
WriteCallback callback,
size_t  bytesWritten,
const AsyncSocketException ex 
)
protected

Definition at line 2642 of file AsyncSocket.cpp.

References addr_, folly::SocketAddress::describe(), fd_, finishFail(), startFail(), state_, and folly::AsyncWriter::WriteCallback::writeErr().

Referenced by handleWrite(), scheduleInitialReadWrite(), setSendTimeout(), timeoutExpired(), and writeImpl().

2646  {
2647  // This version of failWrite() is used when the failure occurs before
2648  // we've added the callback to writeReqHead_.
2649  VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2650  << ", state=" << state_ << " host=" << addr_.describe()
2651  << "): failed while writing in " << fn << "(): " << ex.what();
2652  startFail();
2653 
2654  if (callback != nullptr) {
2655  callback->writeErr(bytesWritten, ex);
2656  }
2657 
2658  finishFail();
2659 }
folly::SocketAddress addr_
The address we tried to connect to.
Definition: AsyncSocket.h:1230
std::string describe() const
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void writeErr(size_t nBytesWritten, const folly::AsyncSocketException &ex) noexceptoverride
void folly::AsyncSocket::failWrite ( const char *  fn,
const AsyncSocketException ex 
)
protected

Definition at line 2619 of file AsyncSocket.cpp.

References addr_, folly::SocketAddress::describe(), folly::AsyncSocket::WriteRequest::destroy(), fd_, finishFail(), folly::AsyncSocket::WriteRequest::getCallback(), folly::AsyncSocket::WriteRequest::getNext(), folly::AsyncSocket::WriteRequest::getTotalBytesWritten(), startFail(), state_, uint32_t, folly::AsyncWriter::WriteCallback::writeErr(), and writeReqHead_.

2619  {
2620  VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2621  << ", state=" << state_ << " host=" << addr_.describe()
2622  << "): failed while writing in " << fn << "(): " << ex.what();
2623  startFail();
2624 
2625  // Only invoke the first write callback, since the error occurred while
2626  // writing this request. Let any other pending write callbacks be invoked in
2627  // finishFail().
2628  if (writeReqHead_ != nullptr) {
2629  WriteRequest* req = writeReqHead_;
2630  writeReqHead_ = req->getNext();
2631  WriteCallback* callback = req->getCallback();
2632  uint32_t bytesWritten = req->getTotalBytesWritten();
2633  req->destroy();
2634  if (callback) {
2635  callback->writeErr(bytesWritten, ex);
2636  }
2637  }
2638 
2639  finishFail();
2640 }
folly::SocketAddress addr_
The address we tried to connect to.
Definition: AsyncSocket.h:1230
std::string describe() const
WriteRequest * getNext() const
Definition: AsyncSocket.h:903
WriteRequest * writeReqHead_
Chain of WriteRequests.
Definition: AsyncSocket.h:1250
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void writeErr(size_t nBytesWritten, const folly::AsyncSocketException &ex) noexceptoverride
void folly::AsyncSocket::finishFail ( )
protected

Definition at line 2553 of file AsyncSocket.cpp.

References ERROR, folly::DelayedDestructionBase::getDestructorGuardCount(), folly::AsyncSocketException::INTERNAL_ERROR, invokeAllErrors(), state_, and withAddr().

Referenced by fail(), failConnect(), failErrMessageRead(), folly::AsyncSSLSocket::failHandshake(), failRead(), failWrite(), invalidState(), and scheduleInitialReadWrite().

2553  {
2554  assert(state_ == StateEnum::ERROR);
2555  assert(getDestructorGuardCount() > 0);
2556 
2557  AsyncSocketException ex(
2559  withAddr("socket closing after error"));
2560  invokeAllErrors(ex);
2561 }
std::string withAddr(const std::string &s)
void invokeAllErrors(const AsyncSocketException &ex)
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
void folly::AsyncSocket::finishFail ( const AsyncSocketException ex)
protected

Definition at line 2563 of file AsyncSocket.cpp.

References ERROR, folly::DelayedDestructionBase::getDestructorGuardCount(), invokeAllErrors(), and state_.

2563  {
2564  assert(state_ == StateEnum::ERROR);
2565  assert(getDestructorGuardCount() > 0);
2566  invokeAllErrors(ex);
2567 }
void invokeAllErrors(const AsyncSocketException &ex)
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
size_t folly::AsyncSocket::getAppBytesReceived ( ) const
inlineoverridevirtual

Implements folly::AsyncTransport.

Definition at line 591 of file AsyncSocket.h.

References appBytesReceived_.

Referenced by getRawBytesReceived().

591  {
592  return appBytesReceived_;
593  }
size_t appBytesReceived_
Num of bytes received from socket.
Definition: AsyncSocket.h:1253
size_t folly::AsyncSocket::getAppBytesWritten ( ) const
inlineoverridevirtual

Implements folly::AsyncTransport.

Definition at line 583 of file AsyncSocket.h.

References appBytesWritten_.

Referenced by getRawBytesWritten().

583  {
584  return appBytesWritten_;
585  }
size_t appBytesWritten_
Num of bytes written to socket.
Definition: AsyncSocket.h:1254
std::chrono::steady_clock::time_point folly::AsyncSocket::getConnectEndTime ( ) const
inline

Definition at line 611 of file AsyncSocket.h.

References connectEndTime_.

611  {
612  return connectEndTime_;
613  }
std::chrono::steady_clock::time_point connectEndTime_
Definition: AsyncSocket.h:1261
std::chrono::steady_clock::time_point folly::AsyncSocket::getConnectStartTime ( ) const
inline

Definition at line 607 of file AsyncSocket.h.

References connectStartTime_.

607  {
608  return connectStartTime_;
609  }
std::chrono::steady_clock::time_point connectStartTime_
Definition: AsyncSocket.h:1260
std::chrono::nanoseconds folly::AsyncSocket::getConnectTime ( ) const
inline

Definition at line 599 of file AsyncSocket.h.

References connectEndTime_, and connectStartTime_.

599  {
601  }
std::chrono::steady_clock::time_point connectStartTime_
Definition: AsyncSocket.h:1260
std::chrono::steady_clock::time_point connectEndTime_
Definition: AsyncSocket.h:1261
std::chrono::milliseconds folly::AsyncSocket::getConnectTimeout ( ) const
inline

Definition at line 603 of file AsyncSocket.h.

References connectTimeout_.

603  {
604  return connectTimeout_;
605  }
std::chrono::milliseconds connectTimeout_
Definition: AsyncSocket.h:1263
AsyncSocket::ErrMessageCallback * folly::AsyncSocket::getErrMessageCallback ( ) const
virtual

Get a pointer to ErrMessageCallback implementation currently registered with this socket.

Definition at line 756 of file AsyncSocket.cpp.

References errMessageCallback_.

Referenced by getMaxReadsPerEvent().

756  {
757  return errMessageCallback_;
758 }
ErrMessageCallback * errMessageCallback_
TimestampCallback.
Definition: AsyncSocket.h:1246
EventBase* folly::AsyncSocket::getEventBase ( ) const
inlineoverridevirtual

Get the EventBase used by this socket.

Implements folly::AsyncSocketBase.

Definition at line 328 of file AsyncSocket.h.

References eventBase_.

Referenced by folly::HandshakeTimeoutCallback::connAccepted(), folly::TestSSLAsyncCacheServer::getSessionCallback(), and tmpDisableReads().

328  {
329  return eventBase_;
330  }
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
virtual int folly::AsyncSocket::getFd ( ) const
inlinevirtual

Get the file descriptor used by the AsyncSocket.

Definition at line 335 of file AsyncSocket.h.

References detachFd(), and fd_.

Referenced by folly::SSLServerAcceptCallbackDelay::connAccepted(), folly::test::MockAsyncSocket::connect(), wangle::SSLSessionCacheManager::getSession(), wangle::TransportInfo::readRTT(), and folly::AsyncSSLSocket::sslAccept().

335  {
336  return fd_;
337  }
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::getLocalAddress ( folly::SocketAddress address) const
overridevirtual

Get the address of the local endpoint of this transport.

This function may throw AsyncSocketException on error.

Parameters
addressThe local address will be stored in the specified SocketAddress.

Implements folly::AsyncTransport.

Definition at line 1575 of file AsyncSocket.cpp.

References cacheLocalAddress(), and localAddr_.

1575  {
1577  *address = localAddr_;
1578 }
void cacheLocalAddress() const
folly::SocketAddress localAddr_
The address we are connecting from.
Definition: AsyncSocket.h:1231
uint16_t folly::AsyncSocket::getMaxReadsPerEvent ( ) const
inline

Get the maximum number of reads this object will execute from the underlying socket each time the EventBase detects that new ingress data is available.

Returns
Maximum number of reads per data-available event; a value of zero means unlimited.

Definition at line 463 of file AsyncSocket.h.

References getErrMessageCallback(), getReadCallback(), getSendMsgParamsCB(), maxReadsPerEvent_, setErrMessageCB(), setReadCB(), setSendMsgParamCB(), and setZeroCopy().

463  {
464  return maxReadsPerEvent_;
465  }
uint16_t maxReadsPerEvent_
Max reads per event loop iteration.
Definition: AsyncSocket.h:1234
uint32_t folly::AsyncSocket::getNextZeroCopyBufId ( )
inlineprotected

Definition at line 1202 of file AsyncSocket.h.

References addZeroCopyBuf(), adjustZeroCopyFlags(), containsZeroCopyBuf(), ptr, releaseZeroCopyBuf(), setZeroCopyBuf(), uint32_t, and zeroCopyBufId_.

Referenced by addZeroCopyBuf().

1202  {
1203  return zeroCopyBufId_++;
1204  }
uint32_t zeroCopyBufId_
Definition: AsyncSocket.h:1216
void folly::AsyncSocket::getPeerAddress ( folly::SocketAddress address) const
overridevirtual

Get the address of the remote endpoint to which this transport is connected.

This function may throw AsyncSocketException on error.

Parameters
addressThe remote endpoint's address will be stored in the specified SocketAddress.

Implements folly::AsyncTransport.

Definition at line 1580 of file AsyncSocket.cpp.

References addr_, and cachePeerAddress().

1580  {
1581  cachePeerAddress();
1582  *address = addr_;
1583 }
void cachePeerAddress() const
folly::SocketAddress addr_
The address we tried to connect to.
Definition: AsyncSocket.h:1230
const AsyncTransportCertificate* folly::AsyncSocket::getPeerCertificate ( ) const
inlineoverridevirtual

Get the peer certificate information if any

Reimplemented from folly::AsyncTransport.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 837 of file AsyncSocket.h.

References peerCertData_.

837  {
838  return peerCertData_.get();
839  }
std::unique_ptr< const AsyncTransportCertificate > peerCertData_
Definition: AsyncSocket.h:1282
size_t folly::AsyncSocket::getRawBytesReceived ( ) const
inlineoverridevirtual

Implements folly::AsyncTransport.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 595 of file AsyncSocket.h.

References getAppBytesReceived().

595  {
596  return getAppBytesReceived();
597  }
size_t getAppBytesReceived() const override
Definition: AsyncSocket.h:591
size_t folly::AsyncSocket::getRawBytesWritten ( ) const
inlineoverridevirtual

Implements folly::AsyncTransport.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 587 of file AsyncSocket.h.

References getAppBytesWritten().

Referenced by folly::test::MockAsyncSocket::connect().

587  {
588  return getAppBytesWritten();
589  }
size_t getAppBytesWritten() const override
Definition: AsyncSocket.h:583
AsyncSocket::ReadCallback * folly::AsyncSocket::getReadCallback ( ) const
overridevirtual

Implements folly::AsyncTransportWrapper.

Definition at line 856 of file AsyncSocket.cpp.

References readCallback_.

Referenced by getMaxReadsPerEvent(), and wangle::SocketPeeker::~SocketPeeker().

856  {
857  return readCallback_;
858 }
ReadCallback * readCallback_
ReadCallback.
Definition: AsyncSocket.h:1249
const AsyncTransportCertificate* folly::AsyncSocket::getSelfCertificate ( ) const
inlineoverridevirtual

Get the certificate information of this transport, if any

Reimplemented from folly::AsyncTransport.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 846 of file AsyncSocket.h.

References selfCertData_.

846  {
847  return selfCertData_.get();
848  }
std::unique_ptr< const AsyncTransportCertificate > selfCertData_
Definition: AsyncSocket.h:1284
AsyncSocket::SendMsgParamsCallback * folly::AsyncSocket::getSendMsgParamsCB ( ) const
virtual

Get a pointer to SendMsgParamsCallback implementation currently registered with this socket.

Definition at line 764 of file AsyncSocket.cpp.

References sendMsgParamCallback_.

Referenced by getMaxReadsPerEvent().

764  {
765  return sendMsgParamCallback_;
766 }
SendMsgParamsCallback * sendMsgParamCallback_
< Callback for retrieving
Definition: AsyncSocket.h:1248
uint32_t folly::AsyncSocket::getSendTimeout ( ) const
inlineoverridevirtual

Get the send timeout.

Returns
Returns the current send timeout, in milliseconds. A return value of 0 indicates that no timeout is set.

Implements folly::AsyncTransport.

Definition at line 437 of file AsyncSocket.h.

References sendTimeout_.

437  {
438  return sendTimeout_;
439  }
uint32_t sendTimeout_
The send timeout, in milliseconds.
Definition: AsyncSocket.h:1233
template<typename T >
int folly::AsyncSocket::getSockOpt ( int  level,
int  optname,
T optval,
socklen_t *  optlen 
)
inline

Generic API for reading a socket option.

Parameters
levelsame as the "level" parameter in getsockopt().
optnamesame as the "optname" parameter in getsockopt().
optvalpointer to the variable in which the option value should be returned.
optlenvalue-result argument, initially containing the size of the buffer pointed to by optval, and modified on return to indicate the actual size of the value returned.
Returns
same as the return value of getsockopt().

Definition at line 714 of file AsyncSocket.h.

References fd_, and folly::netops::getsockopt().

714  {
715  return getsockopt(fd_, level, optname, (void*)optval, optlen);
716  }
int getsockopt(NetworkSocket s, int level, int optname, void *optval, socklen_t *optlen)
Definition: NetOps.cpp:112
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
virtual int folly::AsyncSocket::getSockOptVirtual ( int  level,
int  optname,
void *  optval,
socklen_t *  optlen 
)
inlinevirtual

Virtual method for reading a socket option returning integer value, which is the most typical case. Convenient for overriding and mocking.

Parameters
levelsame as the "level" parameter in getsockopt().
optnamesame as the "optname" parameter in getsockopt().
optvalsame as "optval" parameter in getsockopt().
optlensame as "optlen" parameter in getsockopt().
Returns
same as the return value of getsockopt().

Definition at line 743 of file AsyncSocket.h.

References fd_, and folly::netops::getsockopt().

743  {
744  return getsockopt(fd_, level, optname, optval, optlen);
745  }
int getsockopt(NetworkSocket s, int level, int optname, void *optval, socklen_t *optlen)
Definition: NetOps.cpp:112
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
bool folly::AsyncSocket::getTFOAttempted ( ) const
inline

Definition at line 615 of file AsyncSocket.h.

References tfoAttempted_.

615  {
616  return tfoAttempted_;
617  }
bool folly::AsyncSocket::getTFOFinished ( ) const
inline

Returns whether or not the attempt to use TFO finished successfully. This does not necessarily mean TFO worked, just that trying to use TFO succeeded.

Definition at line 625 of file AsyncSocket.h.

References getTFOSucceded(), setCloseOnExec(), setCongestionFlavor(), setNoDelay(), setQuickAck(), setRecvBufSize(), setSendBufSize(), string, and tfoFinished_.

625  {
626  return tfoFinished_;
627  }
bool folly::AsyncSocket::getTFOSucceded ( ) const

Returns whether or not TFO attempt succeded on this connection. For servers this is pretty straightforward API and can be invoked right after the connection is accepted. This API will perform one syscall. This API is a bit tricky to use for clients, since clients only know this for sure after the SYN-ACK is returned. So it's appropriate to call this only after the first application data is read from the socket when the caller knows that the SYN has been ACKed by the server.

Definition at line 1585 of file AsyncSocket.cpp.

References fd_, and folly::detail::tfo_succeeded().

Referenced by getTFOFinished().

1585  {
1586  return detail::tfo_succeeded(fd_);
1587 }
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
bool tfo_succeeded(int)
bool folly::AsyncSocket::getZeroCopy ( ) const
inline

Definition at line 504 of file AsyncSocket.h.

References zeroCopyEnabled_.

Referenced by folly::AsyncSocket::BytesWriteRequest::performWrite().

504  {
505  return zeroCopyEnabled_;
506  }
uint32_t folly::AsyncSocket::getZeroCopyBufId ( ) const
inline

Definition at line 508 of file AsyncSocket.h.

References zeroCopyBufId_.

508  {
509  return zeroCopyBufId_;
510  }
uint32_t zeroCopyBufId_
Definition: AsyncSocket.h:1216
size_t folly::AsyncSocket::getZeroCopyReenableThreshold ( ) const
inline
bool folly::AsyncSocket::good ( ) const
overridevirtual

Determine if transport is open and ready to read or write.

Note that this function returns false on EOF; you must also call error() to distinguish between an EOF and an error.

Returns
true iff the transport is open and ready, false otherwise.

Implements folly::AsyncTransport.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 1489 of file AsyncSocket.cpp.

References CONNECTING, ESTABLISHED, eventBase_, FAST_OPEN, shutdownFlags_, and state_.

Referenced by folly::test::MockAsyncSocket::connect(), folly::AsyncSSLSocket::connecting(), folly::AsyncSSLSocket::good(), scheduleImmediateRead(), scheduleInitialReadWrite(), and writeRequestReady().

1489  {
1490  return (
1493  (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1494 }
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
uint8_t shutdownFlags_
Shutdown state (ShutdownFlags)
Definition: AsyncSocket.h:1227
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
void folly::AsyncSocket::handleConnect ( )
protectedvirtualnoexcept

Reimplemented in folly::AsyncSSLSocket.

Definition at line 2206 of file AsyncSocket.cpp.

References addr_, folly::AsyncTimeout::cancelTimeout(), CONNECTING, folly::SocketAddress::describe(), error(), ESTABLISHED, eventBase_, eventFlags_, failConnect(), fd_, folly::netops::getsockopt(), handleInitialReadWrite(), folly::AsyncSocketException::INTERNAL_ERROR, invokeConnectSuccess(), folly::EventHandler::NONE, folly::AsyncSocketException::NOT_OPEN, SHUT_READ, SHUT_WRITE, SHUT_WRITE_PENDING, folly::shutdown(), shutdownFlags_, state_, withAddr(), folly::EventHandler::WRITE, writeReqHead_, and writeTimeout_.

Referenced by folly::AsyncSSLSocket::handleConnect(), handleWrite(), and scheduleInitialReadWrite().

2206  {
2207  VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
2208  << ", state=" << state_;
2209  assert(state_ == StateEnum::CONNECTING);
2210  // SHUT_WRITE can never be set while we are still connecting;
2211  // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
2212  // finishes
2213  assert((shutdownFlags_ & SHUT_WRITE) == 0);
2214 
2215  // In case we had a connect timeout, cancel the timeout
2217  // We don't use a persistent registration when waiting on a connect event,
2218  // so we have been automatically unregistered now. Update eventFlags_ to
2219  // reflect reality.
2220  assert(eventFlags_ == EventHandler::WRITE);
2222 
2223  // Call getsockopt() to check if the connect succeeded
2224  int error;
2225  socklen_t len = sizeof(error);
2226  int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
2227  if (rv != 0) {
2228  auto errnoCopy = errno;
2229  AsyncSocketException ex(
2231  withAddr("error calling getsockopt() after connect"),
2232  errnoCopy);
2233  VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd=" << fd_
2234  << " host=" << addr_.describe() << ") exception:" << ex.what();
2235  return failConnect(__func__, ex);
2236  }
2237 
2238  if (error != 0) {
2239  AsyncSocketException ex(
2240  AsyncSocketException::NOT_OPEN, "connect failed", error);
2241  VLOG(2) << "AsyncSocket::handleConnect(this=" << this << ", fd=" << fd_
2242  << " host=" << addr_.describe() << ") exception: " << ex.what();
2243  return failConnect(__func__, ex);
2244  }
2245 
2246  // Move into STATE_ESTABLISHED
2247  state_ = StateEnum::ESTABLISHED;
2248 
2249  // If SHUT_WRITE_PENDING is set and we don't have any write requests to
2250  // perform, immediately shutdown the write half of the socket.
2251  if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
2252  // SHUT_READ shouldn't be set. If close() is called on the socket while we
2253  // are still connecting we just abort the connect rather than waiting for
2254  // it to complete.
2255  assert((shutdownFlags_ & SHUT_READ) == 0);
2256  shutdown(fd_, SHUT_WR);
2258  }
2259 
2260  VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
2261  << "successfully connected; state=" << state_;
2262 
2263  // Remember the EventBase we are attached to, before we start invoking any
2264  // callbacks (since the callbacks may call detachEventBase()).
2265  EventBase* originalEventBase = eventBase_;
2266 
2268  // Note that the connect callback may have changed our state.
2269  // (set or unset the read callback, called write(), closed the socket, etc.)
2270  // The following code needs to handle these situations correctly.
2271  //
2272  // If the socket has been closed, readCallback_ and writeReqHead_ will
2273  // always be nullptr, so that will prevent us from trying to read or write.
2274  //
2275  // The main thing to check for is if eventBase_ is still originalEventBase.
2276  // If not, we have been detached from this event base, so we shouldn't
2277  // perform any more operations.
2278  if (eventBase_ != originalEventBase) {
2279  return;
2280  }
2281 
2283 }
std::string withAddr(const std::string &s)
shutdownWrite() called, but we are still waiting on writes to drain
Definition: AsyncSocket.h:964
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
folly::SocketAddress addr_
The address we tried to connect to.
Definition: AsyncSocket.h:1230
std::string describe() const
WriteRequest * writeReqHead_
Chain of WriteRequests.
Definition: AsyncSocket.h:1250
bool error() const override
uint8_t shutdownFlags_
Shutdown state (ShutdownFlags)
Definition: AsyncSocket.h:1227
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
int getsockopt(NetworkSocket s, int level, int optname, void *optval, socklen_t *optlen)
Definition: NetOps.cpp:112
void shutdown(Counter &)
WriteTimeout writeTimeout_
A timeout for connect and write.
Definition: AsyncSocket.h:1241
void failConnect(const char *fn, const AsyncSocketException &ex)
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
virtual void invokeConnectSuccess()
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
writes have been completely shut down
Definition: AsyncSocket.h:966
virtual void handleInitialReadWrite() noexcept
size_t folly::AsyncSocket::handleErrMessages ( )
protectedvirtualnoexcept

Definition at line 1804 of file AsyncSocket.cpp.

References folly::data(), folly::AsyncSocket::ErrMessageCallback::errMessage(), errMessageCallback_, failErrMessageRead(), fd_, idZeroCopyBufPtrMap_, folly::AsyncSocketException::INTERNAL_ERROR, isZeroCopyMsg(), processZeroCopyMsg(), folly::netops::recvmsg(), state_, uint8_t, and withAddr().

Referenced by ioReady(), processZeroCopyWriteInProgress(), and scheduleInitialReadWrite().

1804  {
1805  // This method has non-empty implementation only for platforms
1806  // supporting per-socket error queues.
1807  VLOG(5) << "AsyncSocket::handleErrMessages() this=" << this << ", fd=" << fd_
1808  << ", state=" << state_;
1809  if (errMessageCallback_ == nullptr && idZeroCopyBufPtrMap_.empty()) {
1810  VLOG(7) << "AsyncSocket::handleErrMessages(): "
1811  << "no callback installed - exiting.";
1812  return 0;
1813  }
1814 
1815 #ifdef FOLLY_HAVE_MSG_ERRQUEUE
1816  uint8_t ctrl[1024];
1817  unsigned char data;
1818  struct msghdr msg;
1819  iovec entry;
1820 
1821  entry.iov_base = &data;
1822  entry.iov_len = sizeof(data);
1823  msg.msg_iov = &entry;
1824  msg.msg_iovlen = 1;
1825  msg.msg_name = nullptr;
1826  msg.msg_namelen = 0;
1827  msg.msg_control = ctrl;
1828  msg.msg_controllen = sizeof(ctrl);
1829  msg.msg_flags = 0;
1830 
1831  int ret;
1832  size_t num = 0;
1833  while (true) {
1834  ret = recvmsg(fd_, &msg, MSG_ERRQUEUE);
1835  VLOG(5) << "AsyncSocket::handleErrMessages(): recvmsg returned " << ret;
1836 
1837  if (ret < 0) {
1838  if (errno != EAGAIN) {
1839  auto errnoCopy = errno;
1840  LOG(ERROR) << "::recvmsg exited with code " << ret
1841  << ", errno: " << errnoCopy;
1842  AsyncSocketException ex(
1844  withAddr("recvmsg() failed"),
1845  errnoCopy);
1846  failErrMessageRead(__func__, ex);
1847  }
1848 
1849  return num;
1850  }
1851 
1852  for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
1853  cmsg != nullptr && cmsg->cmsg_len != 0;
1854  cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1855  ++num;
1856  if (isZeroCopyMsg(*cmsg)) {
1857  processZeroCopyMsg(*cmsg);
1858  } else {
1859  if (errMessageCallback_) {
1861  }
1862  }
1863  }
1864  }
1865 #else
1866  return 0;
1867 #endif // FOLLY_HAVE_MSG_ERRQUEUE
1868 }
std::unordered_map< uint32_t, folly::IOBuf * > idZeroCopyBufPtrMap_
Definition: AsyncSocket.h:1223
std::string withAddr(const std::string &s)
bool isZeroCopyMsg(const cmsghdr &cmsg) const
void failErrMessageRead(const char *fn, const AsyncSocketException &ex)
void processZeroCopyMsg(const cmsghdr &cmsg)
constexpr auto data(C &c) -> decltype(c.data())
Definition: Access.h:71
ErrMessageCallback * errMessageCallback_
TimestampCallback.
Definition: AsyncSocket.h:1246
ssize_t recvmsg(NetworkSocket s, msghdr *message, int flags)
Definition: NetOps.cpp:268
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
virtual void errMessage(const cmsghdr &cmsg) noexcept=0
void folly::AsyncSocket::handleInitialReadWrite ( )
protectedvirtualnoexcept

Reimplemented in folly::AsyncSSLSocket.

Definition at line 2169 of file AsyncSocket.cpp.

References checkForImmediateRead(), ERROR, ESTABLISHED, eventFlags_, handleWrite(), folly::EventHandler::READ, readCallback_, SHUT_READ, shutdownFlags_, state_, updateEventRegistration(), folly::EventHandler::WRITE, and writeReqHead_.

Referenced by folly::AsyncSSLSocket::handleConnect(), handleConnect(), folly::AsyncSSLSocket::handleReturnFromSSLAccept(), and scheduleInitialReadWrite().

2169  {
2170  // Our callers should already be holding a DestructorGuard, but grab
2171  // one here just to make sure, in case one of our calling code paths ever
2172  // changes.
2173  DestructorGuard dg(this);
2174  // If we have a readCallback_, make sure we enable read events. We
2175  // may already be registered for reads if connectSuccess() set
2176  // the read calback.
2178  assert(state_ == StateEnum::ESTABLISHED);
2179  assert((shutdownFlags_ & SHUT_READ) == 0);
2180  if (!updateEventRegistration(EventHandler::READ, 0)) {
2181  assert(state_ == StateEnum::ERROR);
2182  return;
2183  }
2185  } else if (readCallback_ == nullptr) {
2186  // Unregister for read events.
2187  updateEventRegistration(0, EventHandler::READ);
2188  }
2189 
2190  // If we have write requests pending, try to send them immediately.
2191  // Since we just finished accepting, there is a very good chance that we can
2192  // write without blocking.
2193  //
2194  // However, we only process them if EventHandler::WRITE is not already set,
2195  // which means that we're already blocked on a write attempt. (This can
2196  // happen if connectSuccess() called write() before returning.)
2198  // Call handleWrite() to perform write processing.
2199  handleWrite();
2200  } else if (writeReqHead_ == nullptr) {
2201  // Unregister for write event.
2202  updateEventRegistration(0, EventHandler::WRITE);
2203  }
2204 }
bool updateEventRegistration()
WriteRequest * writeReqHead_
Chain of WriteRequests.
Definition: AsyncSocket.h:1250
uint8_t shutdownFlags_
Shutdown state (ShutdownFlags)
Definition: AsyncSocket.h:1227
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
virtual void handleWrite() noexcept
ReadCallback * readCallback_
ReadCallback.
Definition: AsyncSocket.h:1249
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
virtual void checkForImmediateRead() noexcept
void folly::AsyncSocket::handleRead ( )
protectedvirtualnoexcept

Reimplemented in folly::AsyncSSLSocket.

Definition at line 1881 of file AsyncSocket.cpp.

References folly::AsyncSocketException::BAD_ARGS, ERROR, ESTABLISHED, eventBase_, eventFlags_, failRead(), fd_, folly::AsyncSocketException::INTERNAL_ERROR, isBufferMovable_, kOpenSslModeMoveBufferOwnership, maxReadsPerEvent_, folly::gen::move, performRead(), prepareReadBuffer(), folly::EventHandler::READ, READ_BLOCKING, READ_EOF, READ_ERROR, fizz::detail::readBuf(), folly::AsyncReader::ReadCallback::readBufferAvailable(), readCallback_, folly::AsyncReader::ReadCallback::readDataAvailable(), folly::AsyncReader::ReadCallback::readEOF(), readErr_, scheduleImmediateRead(), SHUT_READ, shutdownFlags_, state_, folly::IOBuf::takeOwnership(), uint16_t, updateEventRegistration(), and withAddr().

Referenced by folly::AsyncSSLSocket::checkForImmediateRead(), checkForImmediateRead(), AsyncSocketImmediateRead::checkForImmediateRead(), folly::AsyncSSLSocket::handleRead(), ioReady(), and scheduleInitialReadWrite().

1881  {
1882  VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1883  << ", state=" << state_;
1884  assert(state_ == StateEnum::ESTABLISHED);
1885  assert((shutdownFlags_ & SHUT_READ) == 0);
1886  assert(readCallback_ != nullptr);
1887  assert(eventFlags_ & EventHandler::READ);
1888 
1889  // Loop until:
1890  // - a read attempt would block
1891  // - readCallback_ is uninstalled
1892  // - the number of loop iterations exceeds the optional maximum
1893  // - this AsyncSocket is moved to another EventBase
1894  //
1895  // When we invoke readDataAvailable() it may uninstall the readCallback_,
1896  // which is why need to check for it here.
1897  //
1898  // The last bullet point is slightly subtle. readDataAvailable() may also
1899  // detach this socket from this EventBase. However, before
1900  // readDataAvailable() returns another thread may pick it up, attach it to
1901  // a different EventBase, and install another readCallback_. We need to
1902  // exit immediately after readDataAvailable() returns if the eventBase_ has
1903  // changed. (The caller must perform some sort of locking to transfer the
1904  // AsyncSocket between threads properly. This will be sufficient to ensure
1905  // that this thread sees the updated eventBase_ variable after
1906  // readDataAvailable() returns.)
1907  uint16_t numReads = 0;
1908  EventBase* originalEventBase = eventBase_;
1909  while (readCallback_ && eventBase_ == originalEventBase) {
1910  // Get the buffer to read into.
1911  void* buf = nullptr;
1912  size_t buflen = 0, offset = 0;
1913  try {
1914  prepareReadBuffer(&buf, &buflen);
1915  VLOG(5) << "prepareReadBuffer() buf=" << buf << ", buflen=" << buflen;
1916  } catch (const AsyncSocketException& ex) {
1917  return failRead(__func__, ex);
1918  } catch (const std::exception& ex) {
1919  AsyncSocketException tex(
1921  string("ReadCallback::getReadBuffer() "
1922  "threw exception: ") +
1923  ex.what());
1924  return failRead(__func__, tex);
1925  } catch (...) {
1926  AsyncSocketException ex(
1928  "ReadCallback::getReadBuffer() threw "
1929  "non-exception type");
1930  return failRead(__func__, ex);
1931  }
1932  if (!isBufferMovable_ && (buf == nullptr || buflen == 0)) {
1933  AsyncSocketException ex(
1935  "ReadCallback::getReadBuffer() returned "
1936  "empty buffer");
1937  return failRead(__func__, ex);
1938  }
1939 
1940  // Perform the read
1941  auto readResult = performRead(&buf, &buflen, &offset);
1942  auto bytesRead = readResult.readReturn;
1943  VLOG(4) << "this=" << this << ", AsyncSocket::handleRead() got "
1944  << bytesRead << " bytes";
1945  if (bytesRead > 0) {
1946  if (!isBufferMovable_) {
1947  readCallback_->readDataAvailable(size_t(bytesRead));
1948  } else {
1950  VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
1951  << "buf=" << buf << ", " << bytesRead << "/" << buflen
1952  << ", offset=" << offset;
1953  auto readBuf = folly::IOBuf::takeOwnership(buf, buflen);
1954  readBuf->trimStart(offset);
1955  readBuf->trimEnd(buflen - offset - bytesRead);
1957  }
1958 
1959  // Fall through and continue around the loop if the read
1960  // completely filled the available buffer.
1961  // Note that readCallback_ may have been uninstalled or changed inside
1962  // readDataAvailable().
1963  if (size_t(bytesRead) < buflen) {
1964  return;
1965  }
1966  } else if (bytesRead == READ_BLOCKING) {
1967  // No more data to read right now.
1968  return;
1969  } else if (bytesRead == READ_ERROR) {
1970  readErr_ = READ_ERROR;
1971  if (readResult.exception) {
1972  return failRead(__func__, *readResult.exception);
1973  }
1974  auto errnoCopy = errno;
1975  AsyncSocketException ex(
1977  withAddr("recv() failed"),
1978  errnoCopy);
1979  return failRead(__func__, ex);
1980  } else {
1981  assert(bytesRead == READ_EOF);
1982  readErr_ = READ_EOF;
1983  // EOF
1986  // we've already been moved into STATE_ERROR
1987  assert(state_ == StateEnum::ERROR);
1988  assert(readCallback_ == nullptr);
1989  return;
1990  }
1991 
1992  ReadCallback* callback = readCallback_;
1993  readCallback_ = nullptr;
1994  callback->readEOF();
1995  return;
1996  }
1997  if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1998  if (readCallback_ != nullptr) {
1999  // We might still have data in the socket.
2000  // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
2002  }
2003  return;
2004  }
2005  }
2006 }
virtual void readBufferAvailable(std::unique_ptr< IOBuf >) noexcept
void scheduleImmediateRead() noexcept
Definition: AsyncSocket.h:1031
virtual void readDataAvailable(size_t len) noexcept=0
size_t readBuf(Buf &buf, folly::io::Cursor &cursor)
Definition: Types-inl.h:220
std::string withAddr(const std::string &s)
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
constexpr bool kOpenSslModeMoveBufferOwnership
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
int8_t readErr_
The read error encountered, if any.
Definition: AsyncSocket.h:1238
virtual void prepareReadBuffer(void **buf, size_t *buflen)
bool updateEventRegistration()
uint8_t shutdownFlags_
Shutdown state (ShutdownFlags)
Definition: AsyncSocket.h:1227
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
void failRead(const char *fn, const AsyncSocketException &ex)
virtual ReadResult performRead(void **buf, size_t *buflen, size_t *offset)
uint16_t maxReadsPerEvent_
Max reads per event loop iteration.
Definition: AsyncSocket.h:1234
ReadCallback * readCallback_
ReadCallback.
Definition: AsyncSocket.h:1249
AsyncReader::ReadCallback ReadCallback
static std::unique_ptr< IOBuf > takeOwnership(void *buf, std::size_t capacity, FreeFunction freeFn=nullptr, void *userData=nullptr, bool freeOnError=true)
Definition: IOBuf.h:304
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
virtual void readEOF() noexcept=0
void folly::AsyncSocket::handleWrite ( )
protectedvirtualnoexcept

This function attempts to write as much data as possible, until no more data can be written.

  • If it sends all available data, it unregisters for write events, and stops the writeTimeout_.
  • If not all of the data can be sent immediately, it reschedules writeTimeout_ (if a non-zero timeout is set), and ensures the handler is registered for write events.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 2019 of file AsyncSocket.cpp.

References bufferCallback_, folly::AsyncTimeout::cancelTimeout(), folly::EventHandler::changeHandlerFD(), CLOSED, connectCallback_, CONNECTING, folly::AsyncSocket::WriteRequest::consume(), folly::AsyncSocket::WriteRequest::destroy(), doClose(), ERROR, ESTABLISHED, eventBase_, eventFlags_, failWrite(), fd_, folly::AsyncSocket::WriteRequest::getCallback(), folly::AsyncSocket::WriteRequest::getNext(), handleConnect(), folly::AsyncSocketException::INTERNAL_ERROR, ioHandler_, folly::AsyncSocket::WriteRequest::isComplete(), folly::AsyncTimeout::isScheduled(), folly::AsyncTransport::BufferCallback::onEgressBufferCleared(), folly::AsyncTransport::BufferCallback::onEgressBuffered(), folly::AsyncSocket::WriteRequest::performWrite(), readCallback_, folly::AsyncTimeout::scheduleTimeout(), sendTimeout_, SHUT_READ, SHUT_WRITE, SHUT_WRITE_PENDING, folly::shutdown(), shutdownFlags_, state_, updateEventRegistration(), withAddr(), folly::EventHandler::WRITE, writeReqHead_, writeReqTail_, folly::AsyncWriter::WriteCallback::writeSuccess(), and writeTimeout_.

Referenced by handleInitialReadWrite(), folly::AsyncSSLSocket::handleWrite(), ioReady(), scheduleInitialReadWrite(), and writeRequestReady().

2019  {
2020  VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
2021  << ", state=" << state_;
2022  DestructorGuard dg(this);
2023 
2024  if (state_ == StateEnum::CONNECTING) {
2025  handleConnect();
2026  return;
2027  }
2028 
2029  // Normal write
2030  assert(state_ == StateEnum::ESTABLISHED);
2031  assert((shutdownFlags_ & SHUT_WRITE) == 0);
2032  assert(writeReqHead_ != nullptr);
2033 
2034  // Loop until we run out of write requests,
2035  // or until this socket is moved to another EventBase.
2036  // (See the comment in handleRead() explaining how this can happen.)
2037  EventBase* originalEventBase = eventBase_;
2038  while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
2039  auto writeResult = writeReqHead_->performWrite();
2040  if (writeResult.writeReturn < 0) {
2041  if (writeResult.exception) {
2042  return failWrite(__func__, *writeResult.exception);
2043  }
2044  auto errnoCopy = errno;
2045  AsyncSocketException ex(
2047  withAddr("writev() failed"),
2048  errnoCopy);
2049  return failWrite(__func__, ex);
2050  } else if (writeReqHead_->isComplete()) {
2051  // We finished this request
2052  WriteRequest* req = writeReqHead_;
2053  writeReqHead_ = req->getNext();
2054 
2055  if (writeReqHead_ == nullptr) {
2056  writeReqTail_ = nullptr;
2057  // This is the last write request.
2058  // Unregister for write events and cancel the send timer
2059  // before we invoke the callback. We have to update the state properly
2060  // before calling the callback, since it may want to detach us from
2061  // the EventBase.
2063  if (!updateEventRegistration(0, EventHandler::WRITE)) {
2064  assert(state_ == StateEnum::ERROR);
2065  return;
2066  }
2067  // Stop the send timeout
2069  }
2070  assert(!writeTimeout_.isScheduled());
2071 
2072  // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
2073  // we finish sending the last write request.
2074  //
2075  // We have to do this before invoking writeSuccess(), since
2076  // writeSuccess() may detach us from our EventBase.
2078  assert(connectCallback_ == nullptr);
2080 
2081  if (shutdownFlags_ & SHUT_READ) {
2082  // Reads have already been shutdown. Fully close the socket and
2083  // move to STATE_CLOSED.
2084  //
2085  // Note: This code currently moves us to STATE_CLOSED even if
2086  // close() hasn't ever been called. This can occur if we have
2087  // received EOF from the peer and shutdownWrite() has been called
2088  // locally. Should we bother staying in STATE_ESTABLISHED in this
2089  // case, until close() is actually called? I can't think of a
2090  // reason why we would need to do so. No other operations besides
2091  // calling close() or destroying the socket can be performed at
2092  // this point.
2093  assert(readCallback_ == nullptr);
2094  state_ = StateEnum::CLOSED;
2095  if (fd_ >= 0) {
2097  doClose();
2098  }
2099  } else {
2100  // Reads are still enabled, so we are only doing a half-shutdown
2101  shutdown(fd_, SHUT_WR);
2102  }
2103  }
2104  }
2105 
2106  // Invoke the callback
2107  WriteCallback* callback = req->getCallback();
2108  req->destroy();
2109  if (callback) {
2110  callback->writeSuccess();
2111  }
2112  // We'll continue around the loop, trying to write another request
2113  } else {
2114  // Partial write.
2115  if (bufferCallback_) {
2117  }
2119  // Stop after a partial write; it's highly likely that a subsequent write
2120  // attempt will just return EAGAIN.
2121  //
2122  // Ensure that we are registered for write events.
2123  if ((eventFlags_ & EventHandler::WRITE) == 0) {
2124  if (!updateEventRegistration(EventHandler::WRITE, 0)) {
2125  assert(state_ == StateEnum::ERROR);
2126  return;
2127  }
2128  }
2129 
2130  // Reschedule the send timeout, since we have made some write progress.
2131  if (sendTimeout_ > 0) {
2133  AsyncSocketException ex(
2135  withAddr("failed to reschedule write timeout"));
2136  return failWrite(__func__, ex);
2137  }
2138  }
2139  return;
2140  }
2141  }
2142  if (!writeReqHead_ && bufferCallback_) {
2144  }
2145 }
void writeSuccess() noexceptoverride
std::string withAddr(const std::string &s)
uint32_t sendTimeout_
The send timeout, in milliseconds.
Definition: AsyncSocket.h:1233
virtual void handleConnect() noexcept
shutdownWrite() called, but we are still waiting on writes to drain
Definition: AsyncSocket.h:964
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
WriteRequest * getNext() const
Definition: AsyncSocket.h:903
bool updateEventRegistration()
WriteRequest * writeReqTail_
End of WriteRequest chain.
Definition: AsyncSocket.h:1251
WriteRequest * writeReqHead_
Chain of WriteRequests.
Definition: AsyncSocket.h:1250
uint8_t shutdownFlags_
Shutdown state (ShutdownFlags)
Definition: AsyncSocket.h:1227
IoHandler ioHandler_
A EventHandler to monitor the fd.
Definition: AsyncSocket.h:1242
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
void shutdown(Counter &)
WriteTimeout writeTimeout_
A timeout for connect and write.
Definition: AsyncSocket.h:1241
virtual WriteResult performWrite()=0
void changeHandlerFD(int fd)
Definition: EventHandler.h:143
ReadCallback * readCallback_
ReadCallback.
Definition: AsyncSocket.h:1249
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
BufferCallback * bufferCallback_
Definition: AsyncSocket.h:1267
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
bool scheduleTimeout(uint32_t milliseconds)
bool isScheduled() const
void failWrite(const char *fn, WriteCallback *callback, size_t bytesWritten, const AsyncSocketException &ex)
writes have been completely shut down
Definition: AsyncSocket.h:966
ConnectCallback * connectCallback_
ConnectCallback.
Definition: AsyncSocket.h:1245
bool folly::AsyncSocket::hangup ( ) const
virtual

Definition at line 1471 of file AsyncSocket.cpp.

References fd_, and folly::netops::poll().

Referenced by folly::test::MockAsyncSocket::connect(), folly::test::MockAsyncSSLSocket::connect(), and writeRequestReady().

1471  {
1472  if (fd_ == -1) {
1473  // sanity check, no one should ask for hangup if we are not connected.
1474  assert(false);
1475  return false;
1476  }
1477 #ifdef POLLRDHUP // Linux-only
1478  struct pollfd fds[1];
1479  fds[0].fd = fd_;
1480  fds[0].events = POLLRDHUP | POLLHUP;
1481  fds[0].revents = 0;
1482  poll(fds, 1, 0);
1483  return (fds[0].revents & (POLLRDHUP | POLLHUP)) != 0;
1484 #else
1485  return false;
1486 #endif
1487 }
int poll(PollDescriptor fds[], nfds_t nfds, int timeout)
Definition: NetOps.cpp:141
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::init ( )
protected

Definition at line 337 of file AsyncSocket.cpp.

References appBytesReceived_, appBytesWritten_, connectCallback_, folly::EventBase::dcheckIsInEventBaseThread(), errMessageCallback_, eventBase_, eventFlags_, fd_, maxReadsPerEvent_, folly::EventHandler::NONE, readCallback_, sendMsgParamCallback_, sendTimeout_, shutdownFlags_, state_, UNINIT, writeReqHead_, writeReqTail_, and wShutdownSocketSet_.

Referenced by AsyncSocket().

337  {
338  if (eventBase_) {
340  }
341  shutdownFlags_ = 0;
344  fd_ = -1;
345  sendTimeout_ = 0;
346  maxReadsPerEvent_ = 16;
347  connectCallback_ = nullptr;
348  errMessageCallback_ = nullptr;
349  readCallback_ = nullptr;
350  writeReqHead_ = nullptr;
351  writeReqTail_ = nullptr;
352  wShutdownSocketSet_.reset();
353  appBytesWritten_ = 0;
354  appBytesReceived_ = 0;
355  sendMsgParamCallback_ = &defaultSendMsgParamsCallback;
356 }
uint32_t sendTimeout_
The send timeout, in milliseconds.
Definition: AsyncSocket.h:1233
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
WriteRequest * writeReqTail_
End of WriteRequest chain.
Definition: AsyncSocket.h:1251
WriteRequest * writeReqHead_
Chain of WriteRequests.
Definition: AsyncSocket.h:1250
uint8_t shutdownFlags_
Shutdown state (ShutdownFlags)
Definition: AsyncSocket.h:1227
SendMsgParamsCallback * sendMsgParamCallback_
< Callback for retrieving
Definition: AsyncSocket.h:1248
std::weak_ptr< ShutdownSocketSet > wShutdownSocketSet_
Definition: AsyncSocket.h:1252
size_t appBytesReceived_
Num of bytes received from socket.
Definition: AsyncSocket.h:1253
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
ErrMessageCallback * errMessageCallback_
TimestampCallback.
Definition: AsyncSocket.h:1246
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
uint16_t maxReadsPerEvent_
Max reads per event loop iteration.
Definition: AsyncSocket.h:1234
ReadCallback * readCallback_
ReadCallback.
Definition: AsyncSocket.h:1249
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
size_t appBytesWritten_
Num of bytes written to socket.
Definition: AsyncSocket.h:1254
ConnectCallback * connectCallback_
ConnectCallback.
Definition: AsyncSocket.h:1245
void folly::AsyncSocket::invalidState ( ConnectCallback callback)
protected

Definition at line 2676 of file AsyncSocket.cpp.

References folly::AsyncSocketException::ALREADY_OPEN, CLOSED, connectEndTime_, folly::AsyncSocket::ConnectCallback::connectErr(), ERROR, fd_, finishFail(), now(), startFail(), and state_.

Referenced by connect(), scheduleInitialReadWrite(), setErrMessageCB(), setReadCB(), and writeImpl().

2676  {
2677  VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2678  << "): connect() called in invalid state " << state_;
2679 
2680  /*
2681  * The invalidState() methods don't use the normal failure mechanisms,
2682  * since we don't know what state we are in. We don't want to call
2683  * startFail()/finishFail() recursively if we are already in the middle of
2684  * cleaning up.
2685  */
2686 
2687  AsyncSocketException ex(
2689  "connect() called with socket in invalid state");
2691  if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2692  if (callback) {
2693  callback->connectErr(ex);
2694  }
2695  } else {
2696  // We can't use failConnect() here since connectCallback_
2697  // may already be set to another callback. Invoke this ConnectCallback
2698  // here; any other connectCallback_ will be invoked in finishFail()
2699  startFail();
2700  if (callback) {
2701  callback->connectErr(ex);
2702  }
2703  finishFail();
2704  }
2705 }
std::chrono::steady_clock::time_point now()
std::chrono::steady_clock::time_point connectEndTime_
Definition: AsyncSocket.h:1261
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::invalidState ( ErrMessageCallback callback)
protected

Definition at line 2707 of file AsyncSocket.cpp.

References CLOSED, folly::AsyncSocket::ErrMessageCallback::errMessageError(), ERROR, fd_, finishFail(), folly::AsyncSocketException::NOT_OPEN, startFail(), and state_.

2707  {
2708  VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2709  << "): setErrMessageCB(" << callback << ") called in invalid state "
2710  << state_;
2711 
2712  AsyncSocketException ex(
2715  ? "setErrMessageCB() called with socket in invalid state"
2716  : "This platform does not support socket error message notifications");
2717  if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2718  if (callback) {
2719  callback->errMessageError(ex);
2720  }
2721  } else {
2722  startFail();
2723  if (callback) {
2724  callback->errMessageError(ex);
2725  }
2726  finishFail();
2727  }
2728 }
static constexpr bool msgErrQueueSupported
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::invalidState ( ReadCallback callback)
protected

Definition at line 2748 of file AsyncSocket.cpp.

References CLOSED, ERROR, fd_, finishFail(), folly::AsyncSocketException::NOT_OPEN, folly::AsyncReader::ReadCallback::readErr(), startFail(), and state_.

2748  {
2749  VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2750  << "): setReadCallback(" << callback << ") called in invalid state "
2751  << state_;
2752 
2753  AsyncSocketException ex(
2755  "setReadCallback() called with socket in "
2756  "invalid state");
2757  if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2758  if (callback) {
2759  callback->readErr(ex);
2760  }
2761  } else {
2762  startFail();
2763  if (callback) {
2764  callback->readErr(ex);
2765  }
2766  finishFail();
2767  }
2768 }
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::invalidState ( WriteCallback callback)
protected

Definition at line 2770 of file AsyncSocket.cpp.

References CLOSED, ERROR, fd_, finishFail(), folly::AsyncSocketException::NOT_OPEN, startFail(), state_, withAddr(), and folly::AsyncWriter::WriteCallback::writeErr().

2770  {
2771  VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2772  << "): write() called in invalid state " << state_;
2773 
2774  AsyncSocketException ex(
2776  withAddr("write() called with socket in invalid state"));
2777  if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2778  if (callback) {
2779  callback->writeErr(0, ex);
2780  }
2781  } else {
2782  startFail();
2783  if (callback) {
2784  callback->writeErr(0, ex);
2785  }
2786  finishFail();
2787  }
2788 }
std::string withAddr(const std::string &s)
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void writeErr(size_t nBytesWritten, const folly::AsyncSocketException &ex) noexceptoverride
void folly::AsyncSocket::invokeAllErrors ( const AsyncSocketException ex)
protected

Definition at line 2542 of file AsyncSocket.cpp.

References failAllWrites(), invokeConnectErr(), readCallback_, and folly::AsyncReader::ReadCallback::readErr().

Referenced by finishFail(), and scheduleInitialReadWrite().

2542  {
2543  invokeConnectErr(ex);
2544  failAllWrites(ex);
2545 
2546  if (readCallback_) {
2547  ReadCallback* callback = readCallback_;
2548  readCallback_ = nullptr;
2549  callback->readErr(ex);
2550  }
2551 }
void failAllWrites(const AsyncSocketException &ex)
ReadCallback * readCallback_
ReadCallback.
Definition: AsyncSocket.h:1249
AsyncReader::ReadCallback ReadCallback
virtual void invokeConnectErr(const AsyncSocketException &ex)
virtual void readErr(const AsyncSocketException &ex) noexcept=0
void folly::AsyncSocket::invokeConnectErr ( const AsyncSocketException ex)
protectedvirtual

Reimplemented in folly::AsyncSSLSocket.

Definition at line 2730 of file AsyncSocket.cpp.

References connectCallback_, connectEndTime_, folly::AsyncSocket::ConnectCallback::connectErr(), and now().

Referenced by closeNow(), failConnect(), invokeAllErrors(), folly::AsyncSSLSocket::invokeConnectErr(), and scheduleInitialReadWrite().

2730  {
2732  if (connectCallback_) {
2733  ConnectCallback* callback = connectCallback_;
2734  connectCallback_ = nullptr;
2735  callback->connectErr(ex);
2736  }
2737 }
std::chrono::steady_clock::time_point now()
virtual void connectErr(const AsyncSocketException &ex) noexcept=0
std::chrono::steady_clock::time_point connectEndTime_
Definition: AsyncSocket.h:1261
ConnectCallback * connectCallback_
ConnectCallback.
Definition: AsyncSocket.h:1245
void folly::AsyncSocket::invokeConnectSuccess ( )
protectedvirtual

Reimplemented in folly::AsyncSSLSocket.

Definition at line 2739 of file AsyncSocket.cpp.

References connectCallback_, connectEndTime_, folly::AsyncSocket::ConnectCallback::connectSuccess(), and now().

Referenced by connect(), handleConnect(), folly::AsyncSSLSocket::invokeConnectSuccess(), and scheduleInitialReadWrite().

2739  {
2741  if (connectCallback_) {
2742  ConnectCallback* callback = connectCallback_;
2743  connectCallback_ = nullptr;
2744  callback->connectSuccess();
2745  }
2746 }
virtual void connectSuccess() noexcept=0
std::chrono::steady_clock::time_point now()
std::chrono::steady_clock::time_point connectEndTime_
Definition: AsyncSocket.h:1261
ConnectCallback * connectCallback_
ConnectCallback.
Definition: AsyncSocket.h:1245
void folly::AsyncSocket::ioReady ( uint16_t  events)
protectednoexcept

Definition at line 1713 of file AsyncSocket.cpp.

References folly::EventBase::dcheckIsInEventBaseThread(), eventBase_, fd_, handleErrMessages(), handleRead(), handleWrite(), folly::EventHandler::READ, folly::EventHandler::READ_WRITE, readCallback_, state_, uint16_t, and folly::EventHandler::WRITE.

Referenced by scheduleInitialReadWrite().

1713  {
1714  VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd=" << fd_
1715  << ", events=" << std::hex << events << ", state=" << state_;
1716  DestructorGuard dg(this);
1717  assert(events & EventHandler::READ_WRITE);
1719 
1720  uint16_t relevantEvents = uint16_t(events & EventHandler::READ_WRITE);
1721  EventBase* originalEventBase = eventBase_;
1722  // If we got there it means that either EventHandler::READ or
1723  // EventHandler::WRITE is set. Any of these flags can
1724  // indicate that there are messages available in the socket
1725  // error message queue.
1726  // Return if we handle any error messages - this is to avoid
1727  // unnecessary read/write calls
1728  if (handleErrMessages()) {
1729  return;
1730  }
1731 
1732  // Return now if handleErrMessages() detached us from our EventBase
1733  if (eventBase_ != originalEventBase) {
1734  return;
1735  }
1736 
1737  if (relevantEvents == EventHandler::READ) {
1738  handleRead();
1739  } else if (relevantEvents == EventHandler::WRITE) {
1740  handleWrite();
1741  } else if (relevantEvents == EventHandler::READ_WRITE) {
1742  // If both read and write events are ready, process writes first.
1743  handleWrite();
1744 
1745  // Return now if handleWrite() detached us from our EventBase
1746  if (eventBase_ != originalEventBase) {
1747  return;
1748  }
1749 
1750  // Only call handleRead() if a read callback is still installed.
1751  // (It's possible that the read callback was uninstalled during
1752  // handleWrite().)
1753  if (readCallback_) {
1754  handleRead();
1755  }
1756  } else {
1757  VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1758  << std::hex << events << "(this=" << this << ")";
1759  abort();
1760  }
1761 }
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
virtual void handleRead() noexcept
virtual void handleWrite() noexcept
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
virtual size_t handleErrMessages() noexcept
ReadCallback * readCallback_
ReadCallback.
Definition: AsyncSocket.h:1249
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
virtual bool folly::AsyncSocket::isClosedByPeer ( ) const
inlinevirtual

Definition at line 571 of file AsyncSocket.h.

References CLOSED, READ_EOF, READ_ERROR, readErr_, and state_.

Referenced by proxygen::HTTPSession::connCloseByRemote(), and TEST().

571  {
572  return (
574  (readErr_ == READ_EOF || readErr_ == READ_ERROR));
575  }
int8_t readErr_
The read error encountered, if any.
Definition: AsyncSocket.h:1238
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
virtual bool folly::AsyncSocket::isClosedBySelf ( ) const
inlinevirtual

Definition at line 577 of file AsyncSocket.h.

References CLOSED, READ_EOF, READ_ERROR, readErr_, and state_.

Referenced by TEST().

577  {
578  return (
580  (readErr_ != READ_EOF && readErr_ != READ_ERROR));
581  }
int8_t readErr_
The read error encountered, if any.
Definition: AsyncSocket.h:1238
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
bool folly::AsyncSocket::isDetachable ( ) const
overridevirtual

Determine if the transport can be detached.

This method must be called from the current EventBase's thread.

Implements folly::AsyncTransport.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 1537 of file AsyncSocket.cpp.

References folly::EventBase::dcheckIsInEventBaseThread(), eventBase_, folly::AsyncTimeout::isScheduled(), and writeTimeout_.

Referenced by folly::AsyncSSLSocket::isDetachable(), and writeRequestReady().

1537  {
1538  DCHECK(eventBase_ != nullptr);
1540 
1541  return !writeTimeout_.isScheduled();
1542 }
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
WriteTimeout writeTimeout_
A timeout for connect and write.
Definition: AsyncSocket.h:1241
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
bool isScheduled() const
bool folly::AsyncSocket::isEorTrackingEnabled ( ) const
inlineoverridevirtual
Returns
True iff end of record tracking is enabled

Implements folly::AsyncTransport.

Definition at line 559 of file AsyncSocket.h.

References trackEor_.

Referenced by folly::AsyncSSLSocket::eorAwareSSLWrite(), and folly::AsyncSSLSocket::setEorTracking().

559  {
560  return trackEor_;
561  }
bool folly::AsyncSocket::isPending ( ) const
overridevirtual

Determine if the there is pending data on the transport.

Returns
true iff the if the there is pending data, false otherwise.

Reimplemented from folly::AsyncTransport.

Definition at line 1467 of file AsyncSocket.cpp.

References ioHandler_, and folly::EventHandler::isPending().

Referenced by writeRequestReady().

1467  {
1468  return ioHandler_.isPending();
1469 }
bool isPending() const
IoHandler ioHandler_
A EventHandler to monitor the fd.
Definition: AsyncSocket.h:1242
bool folly::AsyncSocket::isZeroCopyMsg ( const cmsghdr &  cmsg) const
protected

Definition at line 967 of file AsyncSocket.cpp.

References SO_EE_ORIGIN_ZEROCOPY.

Referenced by handleErrMessages(), and scheduleInitialReadWrite().

967  {
968 #ifdef FOLLY_HAVE_MSG_ERRQUEUE
969  if ((cmsg.cmsg_level == SOL_IP && cmsg.cmsg_type == IP_RECVERR) ||
970  (cmsg.cmsg_level == SOL_IPV6 && cmsg.cmsg_type == IPV6_RECVERR)) {
971  const struct sock_extended_err* serr =
972  reinterpret_cast<const struct sock_extended_err*>(CMSG_DATA(&cmsg));
973  return (
974  (serr->ee_errno == 0) && (serr->ee_origin == SO_EE_ORIGIN_ZEROCOPY));
975  }
976 #endif
977  (void)cmsg;
978  return false;
979 }
#define SO_EE_ORIGIN_ZEROCOPY
Definition: NetOps.h:43
bool folly::AsyncSocket::isZeroCopyRequest ( WriteFlags  flags)
protected
bool folly::AsyncSocket::isZeroCopyWriteInProgress ( ) const
noexcept

Returns true if there is any zero copy write in progress Needs to be called from within the socket's EVB thread

Definition at line 1570 of file AsyncSocket.cpp.

References folly::EventBase::dcheckIsInEventBaseThread(), eventBase_, and idZeroCopyBufPtrMap_.

Referenced by setEvbChangedCallback().

1570  {
1572  return (!idZeroCopyBufPtrMap_.empty());
1573 }
std::unordered_map< uint32_t, folly::IOBuf * > idZeroCopyBufPtrMap_
Definition: AsyncSocket.h:1223
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
static std::shared_ptr<AsyncSocket> folly::AsyncSocket::newSocket ( EventBase evb)
inlinestatic

Helper function to create a shared_ptr<AsyncSocket>.

This passes in the correct destructor object, since AsyncSocket's destructor is protected and cannot be invoked directly.

Definition at line 281 of file AsyncSocket.h.

References AsyncSocket().

Referenced by TestServer::acceptAsync(), wangle::ClientBootstrap< DefaultPipeline >::connect(), ProxyService::ProxyHandler::onRequest(), folly::TEST(), TEST(), TEST_P(), and testConnectOptWrite().

281  {
282  return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb), Destructor());
283  }
static std::shared_ptr<AsyncSocket> folly::AsyncSocket::newSocket ( EventBase evb,
const folly::SocketAddress address,
uint32_t  connectTimeout = 0 
)
inlinestatic

Helper function to create a shared_ptr<AsyncSocket>.

Definition at line 288 of file AsyncSocket.h.

References AsyncSocket().

291  {
292  return std::shared_ptr<AsyncSocket>(
293  new AsyncSocket(evb, address, connectTimeout), Destructor());
294  }
static std::shared_ptr<AsyncSocket> folly::AsyncSocket::newSocket ( EventBase evb,
const std::string ip,
uint16_t  port,
uint32_t  connectTimeout = 0 
)
inlinestatic

Helper function to create a shared_ptr<AsyncSocket>.

Definition at line 299 of file AsyncSocket.h.

References AsyncSocket().

303  {
304  return std::shared_ptr<AsyncSocket>(
305  new AsyncSocket(evb, ip, port, connectTimeout), Destructor());
306  }
static std::shared_ptr<AsyncSocket> folly::AsyncSocket::newSocket ( EventBase evb,
int  fd 
)
inlinestatic

Helper function to create a shared_ptr<AsyncSocket>.

Definition at line 311 of file AsyncSocket.h.

References AsyncSocket(), and destroy().

311  {
312  return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb, fd), Destructor());
313  }
AsyncSocket::ReadResult folly::AsyncSocket::performRead ( void **  buf,
size_t *  buflen,
size_t *  offset 
)
protectedvirtual

Attempt to read from the socket.

Parameters
bufThe buffer to read data into.
buflenThe length of the buffer.
Returns
Returns a read result. See read result for details.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 1764 of file AsyncSocket.cpp.

References appBytesReceived_, folly::IOBufQueue::append(), fd_, folly::IOBufQueue::move(), folly::gen::move, preReceivedData_, folly::io::detail::CursorBase< Derived, BufType >::pullAtMost(), READ_BLOCKING, READ_ERROR, folly::netops::recv(), and folly::IOBufQueue::trimStart().

Referenced by handleRead(), folly::AsyncSSLSocket::performRead(), and scheduleInitialReadWrite().

1764  {
1765  VLOG(5) << "AsyncSocket::performRead() this=" << this << ", buf=" << *buf
1766  << ", buflen=" << *buflen;
1767 
1768  if (preReceivedData_ && !preReceivedData_->empty()) {
1769  VLOG(5) << "AsyncSocket::performRead() this=" << this
1770  << ", reading pre-received data";
1771 
1772  io::Cursor cursor(preReceivedData_.get());
1773  auto len = cursor.pullAtMost(*buf, *buflen);
1774 
1775  IOBufQueue queue;
1776  queue.append(std::move(preReceivedData_));
1777  queue.trimStart(len);
1778  preReceivedData_ = queue.move();
1779 
1780  appBytesReceived_ += len;
1781  return ReadResult(len);
1782  }
1783 
1784  ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT);
1785  if (bytes < 0) {
1786  if (errno == EAGAIN || errno == EWOULDBLOCK) {
1787  // No more data to read right now.
1788  return ReadResult(READ_BLOCKING);
1789  } else {
1790  return ReadResult(READ_ERROR);
1791  }
1792  } else {
1793  appBytesReceived_ += bytes;
1794  return ReadResult(bytes);
1795  }
1796 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
size_t appBytesReceived_
Num of bytes received from socket.
Definition: AsyncSocket.h:1253
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
ssize_t recv(NetworkSocket s, void *buf, size_t len, int flags)
Definition: NetOps.cpp:180
std::unique_ptr< IOBuf > preReceivedData_
Definition: AsyncSocket.h:1258
AsyncSocket::WriteResult folly::AsyncSocket::performWrite ( const iovec *  vec,
uint32_t  count,
WriteFlags  flags,
uint32_t countWritten,
uint32_t partialWritten 
)
protectedvirtual

Attempt to write to the socket.

Parameters
vecThe iovec array pointing to the buffers to write.
countThe length of the iovec array.
flagsSet of write flags.
countWrittenOn return, the value pointed to by this parameter will contain the number of iovec entries that were fully written.
partialWrittenOn return, the value pointed to by this parameter will contain the number of bytes written in the partially written iovec entry.
Returns
Returns a WriteResult. See WriteResult for more details.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 2387 of file AsyncSocket.cpp.

References appBytesWritten_, count, fd_, folly::AsyncSocket::SendMsgParamsCallback::getAncillaryData(), folly::AsyncSocket::SendMsgParamsCallback::getAncillaryDataSize(), folly::AsyncSocket::SendMsgParamsCallback::getFlags(), folly::kIovMax, folly::AsyncSocket::SendMsgParamsCallback::maxAncillaryDataSize, sendMsgParamCallback_, sendSocketMessage(), uint32_t, zeroCopyEnabled_, zeroCopyReenableCounter_, and zeroCopyReenableThreshold_.

Referenced by folly::AsyncSocket::BytesWriteRequest::performWrite(), folly::AsyncSSLSocket::performWrite(), scheduleInitialReadWrite(), folly::AsyncSocket::WriteRequest::start(), and writeImpl().

2392  {
2393  // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
2394  // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
2395  // (since it may terminate the program if the main program doesn't explicitly
2396  // ignore it).
2397  struct msghdr msg;
2398  msg.msg_name = nullptr;
2399  msg.msg_namelen = 0;
2400  msg.msg_iov = const_cast<iovec*>(vec);
2401  msg.msg_iovlen = std::min<size_t>(count, kIovMax);
2402  msg.msg_flags = 0;
2403  msg.msg_controllen = sendMsgParamCallback_->getAncillaryDataSize(flags);
2404  CHECK_GE(
2406  msg.msg_controllen);
2407 
2408  if (msg.msg_controllen != 0) {
2409  msg.msg_control = reinterpret_cast<char*>(alloca(msg.msg_controllen));
2410  sendMsgParamCallback_->getAncillaryData(flags, msg.msg_control);
2411  } else {
2412  msg.msg_control = nullptr;
2413  }
2415 
2416  auto writeResult = sendSocketMessage(fd_, &msg, msg_flags);
2417  auto totalWritten = writeResult.writeReturn;
2418  if (totalWritten < 0 && zeroCopyEnabled_ && errno == ENOBUFS) {
2419  // workaround for running with zerocopy enabled but without a big enough
2420  // memlock value - see ulimit -l
2421  zeroCopyEnabled_ = false;
2424  writeResult = sendSocketMessage(fd_, &msg, msg_flags);
2425  totalWritten = writeResult.writeReturn;
2426  }
2427  if (totalWritten < 0) {
2428  bool tryAgain = (errno == EAGAIN);
2429 #ifdef __APPLE__
2430  // Apple has a bug where doing a second write on a socket which we
2431  // have opened with TFO causes an ENOTCONN to be thrown. However the
2432  // socket is really connected, so treat ENOTCONN as a EAGAIN until
2433  // this bug is fixed.
2434  tryAgain |= (errno == ENOTCONN);
2435 #endif
2436 
2437  if (!writeResult.exception && tryAgain) {
2438  // TCP buffer is full; we can't write any more data right now.
2439  *countWritten = 0;
2440  *partialWritten = 0;
2441  return WriteResult(0);
2442  }
2443  // error
2444  *countWritten = 0;
2445  *partialWritten = 0;
2446  return writeResult;
2447  }
2448 
2449  appBytesWritten_ += totalWritten;
2450 
2451  uint32_t bytesWritten;
2452  uint32_t n;
2453  for (bytesWritten = uint32_t(totalWritten), n = 0; n < count; ++n) {
2454  const iovec* v = vec + n;
2455  if (v->iov_len > bytesWritten) {
2456  // Partial write finished in the middle of this iovec
2457  *countWritten = n;
2458  *partialWritten = bytesWritten;
2459  return WriteResult(totalWritten);
2460  }
2461 
2462  bytesWritten -= uint32_t(v->iov_len);
2463  }
2464 
2465  assert(bytesWritten == 0);
2466  *countWritten = n;
2467  *partialWritten = 0;
2468  return WriteResult(totalWritten);
2469 }
flags
Definition: http_parser.h:127
constexpr size_t kIovMax
Definition: SysUio.h:39
SendMsgParamsCallback * sendMsgParamCallback_
< Callback for retrieving
Definition: AsyncSocket.h:1248
size_t zeroCopyReenableCounter_
Definition: AsyncSocket.h:1279
virtual void getAncillaryData(folly::WriteFlags, void *) noexcept
Definition: AsyncSocket.h:170
size_t zeroCopyReenableThreshold_
Definition: AsyncSocket.h:1278
Definition: Traits.h:588
int getFlags(folly::WriteFlags flags, bool zeroCopyEnabled) noexcept
Definition: AsyncSocket.h:156
int * count
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
vector< string > vec
Definition: StringTest.cpp:35
virtual uint32_t getAncillaryDataSize(folly::WriteFlags) noexcept
Definition: AsyncSocket.h:180
AsyncSocket::WriteResult sendSocketMessage(int fd, struct msghdr *msg, int msg_flags)
size_t appBytesWritten_
Num of bytes written to socket.
Definition: AsyncSocket.h:1254
void folly::AsyncSocket::prepareReadBuffer ( void **  buf,
size_t *  buflen 
)
protectedvirtual

Reimplemented in folly::AsyncSSLSocket.

Definition at line 1798 of file AsyncSocket.cpp.

References folly::AsyncReader::ReadCallback::getReadBuffer(), and readCallback_.

Referenced by handleRead(), and scheduleInitialReadWrite().

1798  {
1799  // no matter what, buffer should be preapared for non-ssl socket
1800  CHECK(readCallback_);
1801  readCallback_->getReadBuffer(buf, buflen);
1802 }
virtual void getReadBuffer(void **bufReturn, size_t *lenReturn)=0
ReadCallback * readCallback_
ReadCallback.
Definition: AsyncSocket.h:1249
void folly::AsyncSocket::processZeroCopyMsg ( const cmsghdr &  cmsg)
protected

Definition at line 981 of file AsyncSocket.cpp.

References fd_, i, releaseZeroCopyBuf(), SO_EE_CODE_ZEROCOPY_COPIED, uint32_t, and zeroCopyEnabled_.

Referenced by handleErrMessages(), and scheduleInitialReadWrite().

981  {
982 #ifdef FOLLY_HAVE_MSG_ERRQUEUE
983  const struct sock_extended_err* serr =
984  reinterpret_cast<const struct sock_extended_err*>(CMSG_DATA(&cmsg));
985  uint32_t hi = serr->ee_data;
986  uint32_t lo = serr->ee_info;
987  // disable zero copy if the buffer was actually copied
988  if ((serr->ee_code & SO_EE_CODE_ZEROCOPY_COPIED) && zeroCopyEnabled_) {
989  VLOG(2) << "AsyncSocket::processZeroCopyMsg(): setting "
990  << "zeroCopyEnabled_ = false due to SO_EE_CODE_ZEROCOPY_COPIED "
991  << "on " << fd_;
992  zeroCopyEnabled_ = false;
993  }
994 
995  for (uint32_t i = lo; i <= hi; i++) {
997  }
998 #else
999  (void)cmsg;
1000 #endif
1001 }
#define SO_EE_CODE_ZEROCOPY_COPIED
Definition: NetOps.h:47
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void releaseZeroCopyBuf(uint32_t id)
bool folly::AsyncSocket::processZeroCopyWriteInProgress ( )
noexcept

Tries to process the msg error queue And returns true if there are no more zero copy writes in progress

Definition at line 1870 of file AsyncSocket.cpp.

References folly::EventBase::dcheckIsInEventBaseThread(), eventBase_, handleErrMessages(), and idZeroCopyBufPtrMap_.

Referenced by setEvbChangedCallback().

1870  {
1872  if (idZeroCopyBufPtrMap_.empty()) {
1873  return true;
1874  }
1875 
1877 
1878  return idZeroCopyBufPtrMap_.empty();
1879 }
std::unordered_map< uint32_t, folly::IOBuf * > idZeroCopyBufPtrMap_
Definition: AsyncSocket.h:1223
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
virtual size_t handleErrMessages() noexcept
bool folly::AsyncSocket::readable ( ) const
overridevirtual

Determine if the transport is readable or not.

Returns
true iff the transport is readable, false otherwise.

Implements folly::AsyncTransport.

Definition at line 1443 of file AsyncSocket.cpp.

References fd_, and folly::netops::poll().

Referenced by folly::test::MockAsyncSocket::connect(), folly::test::MockAsyncSSLSocket::connect(), and writeRequestReady().

1443  {
1444  if (fd_ == -1) {
1445  return false;
1446  }
1447  struct pollfd fds[1];
1448  fds[0].fd = fd_;
1449  fds[0].events = POLLIN;
1450  fds[0].revents = 0;
1451  int rc = poll(fds, 1, 0);
1452  return rc == 1;
1453 }
int poll(PollDescriptor fds[], nfds_t nfds, int timeout)
Definition: NetOps.cpp:141
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::registerForConnectEvents ( )
protected

Definition at line 630 of file AsyncSocket.cpp.

References eventFlags_, folly::AsyncSocketException::INTERNAL_ERROR, ioHandler_, folly::EventHandler::NONE, folly::EventHandler::registerHandler(), withAddr(), and folly::EventHandler::WRITE.

Referenced by scheduleInitialReadWrite(), sendSocketMessage(), and socketConnect().

630  {
631  // Register for write events, so we'll
632  // be notified when the connection finishes/fails.
633  // Note that we don't register for a persistent event here.
634  assert(eventFlags_ == EventHandler::NONE);
637  throw AsyncSocketException(
639  withAddr("failed to register AsyncSocket connect handler"));
640  }
641 }
std::string withAddr(const std::string &s)
IoHandler ioHandler_
A EventHandler to monitor the fd.
Definition: AsyncSocket.h:1242
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
bool registerHandler(uint16_t events)
Definition: EventHandler.h:100
void folly::AsyncSocket::releaseZeroCopyBuf ( uint32_t  id)
protected

Definition at line 942 of file AsyncSocket.cpp.

References idZeroCopyBufInfoMap_, idZeroCopyBufPtrMap_, and ptr.

Referenced by getNextZeroCopyBufId(), and processZeroCopyMsg().

942  {
943  auto iter = idZeroCopyBufPtrMap_.find(id);
944  CHECK(iter != idZeroCopyBufPtrMap_.end());
945  auto ptr = iter->second;
946  auto iter1 = idZeroCopyBufInfoMap_.find(ptr);
947  CHECK(iter1 != idZeroCopyBufInfoMap_.end());
948  if (0 == --iter1->second.count_) {
949  idZeroCopyBufInfoMap_.erase(iter1);
950  }
951 
952  idZeroCopyBufPtrMap_.erase(iter);
953 }
void * ptr
std::unordered_map< uint32_t, folly::IOBuf * > idZeroCopyBufPtrMap_
Definition: AsyncSocket.h:1223
std::unordered_map< folly::IOBuf *, IOBufInfo > idZeroCopyBufInfoMap_
Definition: AsyncSocket.h:1224
void folly::AsyncSocket::scheduleConnectTimeout ( )
protectedvirtual

Reimplemented in folly::AsyncSSLSocket.

Definition at line 617 of file AsyncSocket.cpp.

References connectTimeout_, folly::AsyncSocketException::INTERNAL_ERROR, folly::AsyncTimeout::scheduleTimeout(), folly::detail::timeout, uint32_t, withAddr(), and writeTimeout_.

Referenced by folly::AsyncSSLSocket::scheduleConnectTimeout(), scheduleInitialReadWrite(), sendSocketMessage(), and socketConnect().

617  {
618  // Connection in progress.
619  auto timeout = connectTimeout_.count();
620  if (timeout > 0) {
621  // Start a timer in case the connection takes too long.
622  if (!writeTimeout_.scheduleTimeout(uint32_t(timeout))) {
623  throw AsyncSocketException(
625  withAddr("failed to schedule AsyncSocket connect timeout"));
626  }
627  }
628 }
std::string withAddr(const std::string &s)
std::chrono::milliseconds connectTimeout_
Definition: AsyncSocket.h:1263
WriteTimeout writeTimeout_
A timeout for connect and write.
Definition: AsyncSocket.h:1241
bool scheduleTimeout(uint32_t milliseconds)
void folly::AsyncSocket::scheduleImmediateRead ( )
inlineprotectednoexcept

Schedule checkForImmediateRead to be executed in the next loop iteration.

Definition at line 1031 of file AsyncSocket.h.

References eventBase_, good(), immediateReadHandler_, and folly::EventBase::runInLoop().

Referenced by handleRead().

1031  {
1032  if (good()) {
1034  }
1035  }
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
ImmediateReadCB immediateReadHandler_
LoopCallback for checking read.
Definition: AsyncSocket.h:1243
void runInLoop(LoopCallback *callback, bool thisIteration=false)
Definition: EventBase.cpp:520
bool good() const override
void folly::AsyncSocket::scheduleInitialReadWrite ( )
inlineprotectednoexcept

Schedule handleInitalReadWrite to run in the next iteration.

Definition at line 1040 of file AsyncSocket.h.

References addr, cacheLocalAddress(), cachePeerAddress(), checkForImmediateRead(), doClose(), eventBase_, fail(), failAllWrites(), failConnect(), failErrMessageRead(), failRead(), failWrite(), finishFail(), good(), handleConnect(), handleErrMessages(), handleInitialReadWrite(), handleRead(), handleWrite(), invalidState(), invokeAllErrors(), invokeConnectErr(), invokeConnectSuccess(), ioReady(), isZeroCopyMsg(), isZeroCopyRequest(), folly::pushmi::__adl::noexcept(), folly::NONE, performRead(), performWrite(), prepareReadBuffer(), processZeroCopyMsg(), registerForConnectEvents(), folly::EventBase::runInLoop(), s, scheduleConnectTimeout(), sendSocketMessage(), socketConnect(), startFail(), string, tfoSendMsg(), timeoutExpired(), uint16_t, uint32_t, updateEventRegistration(), withAddr(), writeChainImpl(), and writeImpl().

Referenced by sendSocketMessage().

1040  {
1041  if (good()) {
1042  DestructorGuard dg(this);
1043  eventBase_->runInLoop([this, dg] {
1044  if (good()) {
1046  }
1047  });
1048  }
1049  }
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
void runInLoop(LoopCallback *callback, bool thisIteration=false)
Definition: EventBase.cpp:520
bool good() const override
virtual void handleInitialReadWrite() noexcept
AsyncSocket::WriteResult folly::AsyncSocket::sendSocketMessage ( int  fd,
struct msghdr *  msg,
int  msg_flags 
)
protected

Sends the message over the socket using sendmsg

Parameters
msgMessage to send
msg_flagsFlags to pass to sendmsg

Definition at line 2321 of file AsyncSocket.cpp.

References addr, addr_, CONNECTING, ESTABLISHED, FAST_OPEN, fd_, folly::SocketAddress::getAddress(), registerForConnectEvents(), scheduleConnectTimeout(), scheduleInitialReadWrite(), folly::netops::sendmsg(), socketConnect(), state_, tfoFinished_, tfoSendMsg(), folly::AsyncSocketException::UNKNOWN, and WRITE_ERROR.

Referenced by performWrite(), and scheduleInitialReadWrite().

2321  {
2322  ssize_t totalWritten = 0;
2323  if (state_ == StateEnum::FAST_OPEN) {
2324  sockaddr_storage addr;
2325  auto len = addr_.getAddress(&addr);
2326  msg->msg_name = &addr;
2327  msg->msg_namelen = len;
2328  totalWritten = tfoSendMsg(fd_, msg, msg_flags);
2329  if (totalWritten >= 0) {
2330  tfoFinished_ = true;
2332  // We schedule this asynchrously so that we don't end up
2333  // invoking initial read or write while a write is in progress.
2335  } else if (errno == EINPROGRESS) {
2336  VLOG(4) << "TFO falling back to connecting";
2337  // A normal sendmsg doesn't return EINPROGRESS, however
2338  // TFO might fallback to connecting if there is no
2339  // cookie.
2341  try {
2344  } catch (const AsyncSocketException& ex) {
2345  return WriteResult(
2346  WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
2347  }
2348  // Let's fake it that no bytes were written and return an errno.
2349  errno = EAGAIN;
2350  totalWritten = -1;
2351  } else if (errno == EOPNOTSUPP) {
2352  // Try falling back to connecting.
2353  VLOG(4) << "TFO not supported";
2355  try {
2356  int ret = socketConnect((const sockaddr*)&addr, len);
2357  if (ret == 0) {
2358  // connect succeeded immediately
2359  // Treat this like no data was written.
2362  }
2363  // If there was no exception during connections,
2364  // we would return that no bytes were written.
2365  errno = EAGAIN;
2366  totalWritten = -1;
2367  } catch (const AsyncSocketException& ex) {
2368  return WriteResult(
2369  WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
2370  }
2371  } else if (errno == EAGAIN) {
2372  // Normally sendmsg would indicate that the write would block.
2373  // However in the fast open case, it would indicate that sendmsg
2374  // fell back to a connect. This is a return code from connect()
2375  // instead, and is an error condition indicating no fds available.
2376  return WriteResult(
2377  WRITE_ERROR,
2378  std::make_unique<AsyncSocketException>(
2379  AsyncSocketException::UNKNOWN, "No more free local ports"));
2380  }
2381  } else {
2382  totalWritten = ::sendmsg(fd, msg, msg_flags);
2383  }
2384  return WriteResult(totalWritten);
2385 }
virtual ssize_t tfoSendMsg(int fd, struct msghdr *msg, int msg_flags)
ssize_t sendmsg(NetworkSocket socket, const msghdr *message, int flags)
Definition: NetOps.cpp:328
folly::SocketAddress addr_
The address we tried to connect to.
Definition: AsyncSocket.h:1230
void scheduleInitialReadWrite() noexcept
Definition: AsyncSocket.h:1040
void registerForConnectEvents()
socklen_t getAddress(sockaddr_storage *addr) const
virtual void scheduleConnectTimeout()
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
int socketConnect(const struct sockaddr *addr, socklen_t len)
ThreadPoolListHook * addr
void folly::AsyncSocket::setBufferCallback ( BufferCallback cb)

Definition at line 2829 of file AsyncSocket.cpp.

References bufferCallback_.

Referenced by proxygen::HTTPSession::checkForShutdown(), and proxygen::HTTPUpstreamSession::HTTPUpstreamSession().

2829  {
2830  bufferCallback_ = cb;
2831 }
BufferCallback * bufferCallback_
Definition: AsyncSocket.h:1267
void folly::AsyncSocket::setCloseOnExec ( )

Set the FD_CLOEXEC flag so that the socket will be closed if the program later forks and execs.

Definition at line 420 of file AsyncSocket.cpp.

References fd_, folly::AsyncSocketException::INTERNAL_ERROR, and withAddr().

Referenced by AsyncSocket(), connect(), and getTFOFinished().

420  {
421  int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
422  if (rv != 0) {
423  auto errnoCopy = errno;
424  throw AsyncSocketException(
426  withAddr("failed to set close-on-exec flag"),
427  errnoCopy);
428  }
429 }
std::string withAddr(const std::string &s)
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
int folly::AsyncSocket::setCongestionFlavor ( const std::string cname)

Definition at line 1608 of file AsyncSocket.cpp.

References folly::errnoStr(), fd_, folly::netops::setsockopt(), state_, and TCP_CONGESTION.

Referenced by getTFOFinished().

1608  {
1609 #ifndef TCP_CONGESTION
1610 #define TCP_CONGESTION 13
1611 #endif
1612 
1613  if (fd_ < 0) {
1614  VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1615  << "socket " << this << "(state=" << state_ << ")";
1616  return EINVAL;
1617  }
1618 
1619  if (setsockopt(
1620  fd_,
1621  IPPROTO_TCP,
1623  cname.c_str(),
1624  socklen_t(cname.length() + 1)) != 0) {
1625  int errnoCopy = errno;
1626  VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket " << this
1627  << "(fd=" << fd_ << ", state=" << state_
1628  << "): " << errnoStr(errnoCopy);
1629  return errnoCopy;
1630  }
1631 
1632  return 0;
1633 }
int setsockopt(NetworkSocket s, int level, int optname, const void *optval, socklen_t optlen)
Definition: NetOps.cpp:384
#define TCP_CONGESTION
fbstring errnoStr(int err)
Definition: String.cpp:463
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::setEorTracking ( bool  track)
inlineoverridevirtual

Implements folly::AsyncTransport.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 563 of file AsyncSocket.h.

References trackEor_.

Referenced by folly::AsyncSSLSocket::setEorTracking().

563  {
564  trackEor_ = track;
565  }
void folly::AsyncSocket::setErrMessageCB ( ErrMessageCallback callback)
virtual

Set a pointer to ErrMessageCallback implementation which will be receiving notifications for messages posted to the error queue associated with the socket. ErrMessageCallback is implemented only for platforms with per-socket error message queus support (recvmsg() system call must )

Definition at line 691 of file AsyncSocket.cpp.

References cacheLocalAddress(), CLOSED, CONNECTING, folly::EventBase::dcheckIsInEventBaseThread(), errMessageCallback_, ERROR, ESTABLISHED, eventBase_, FAST_OPEN, fd_, folly::SocketAddress::getFamily(), invalidState(), localAddr_, state_, and UNINIT.

Referenced by folly::test::MockAsyncSocket::connect(), and getMaxReadsPerEvent().

691  {
692  VLOG(6) << "AsyncSocket::setErrMessageCB() this=" << this << ", fd=" << fd_
693  << ", callback=" << callback << ", state=" << state_;
694 
695  // In the latest stable kernel 4.14.3 as of 2017-12-04, unix domain
696  // socket does not support MSG_ERRQUEUE. So recvmsg(MSG_ERRQUEUE)
697  // will read application data from unix doamin socket as error
698  // message, which breaks the message flow in application. Feel free
699  // to remove the next code block if MSG_ERRQUEUE is added for unix
700  // domain socket in the future.
701  if (callback != nullptr) {
703  if (localAddr_.getFamily() == AF_UNIX) {
704  LOG(ERROR) << "Failed to set ErrMessageCallback=" << callback
705  << " for Unix Doamin Socket where MSG_ERRQUEUE is unsupported,"
706  << " fd=" << fd_;
707  return;
708  }
709  }
710 
711  // Short circuit if callback is the same as the existing errMessageCallback_.
712  if (callback == errMessageCallback_) {
713  return;
714  }
715 
716  if (!msgErrQueueSupported) {
717  // Per-socket error message queue is not supported on this platform.
718  return invalidState(callback);
719  }
720 
721  DestructorGuard dg(this);
723 
724  if (callback == nullptr) {
725  // We should be able to reset the callback regardless of the
726  // socket state. It's important to have a reliable callback
727  // cancellation mechanism.
728  errMessageCallback_ = callback;
729  return;
730  }
731 
732  switch ((StateEnum)state_) {
735  case StateEnum::ESTABLISHED: {
736  errMessageCallback_ = callback;
737  return;
738  }
739  case StateEnum::CLOSED:
740  case StateEnum::ERROR:
741  // We should never reach here. SHUT_READ should always be set
742  // if we are in STATE_CLOSED or STATE_ERROR.
743  assert(false);
744  return invalidState(callback);
745  case StateEnum::UNINIT:
746  // We do not allow setReadCallback() to be called before we start
747  // connecting.
748  return invalidState(callback);
749  }
750 
751  // We don't put a default case in the switch statement, so that the compiler
752  // will warn us to update the switch statement if a new state is added.
753  return invalidState(callback);
754 }
void cacheLocalAddress() const
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
folly::SocketAddress localAddr_
The address we are connecting from.
Definition: AsyncSocket.h:1231
void invalidState(ConnectCallback *callback)
sa_family_t getFamily() const
StateEnum
ErrMessageCallback * errMessageCallback_
TimestampCallback.
Definition: AsyncSocket.h:1246
static constexpr bool msgErrQueueSupported
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::setEvbChangedCallback ( std::unique_ptr< EvbChangeCallback cb)
inline

Definition at line 810 of file AsyncSocket.h.

References cacheAddresses(), evbChangeCb_, isZeroCopyWriteInProgress(), folly::gen::move, folly::pushmi::__adl::noexcept(), and processZeroCopyWriteInProgress().

810  {
811  evbChangeCb_ = std::move(cb);
812  }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::unique_ptr< EvbChangeCallback > evbChangeCb_
Definition: AsyncSocket.h:1265
void folly::AsyncSocket::setMaxReadsPerEvent ( uint16_t  maxReads)
inline

Set the maximum number of reads to execute from the underlying socket each time the EventBase detects that new ingress data is available. The default is unlimited, but callers can use this method to limit the amount of data read from the socket per event loop iteration.

Parameters
maxReadsMaximum number of reads per data-available event; a value of zero means unlimited.

Definition at line 451 of file AsyncSocket.h.

References maxReadsPerEvent_.

Referenced by wangle::Acceptor::connectionReady(), and TEST().

451  {
452  maxReadsPerEvent_ = maxReads;
453  }
uint16_t maxReadsPerEvent_
Max reads per event loop iteration.
Definition: AsyncSocket.h:1234
int folly::AsyncSocket::setNoDelay ( bool  noDelay)

Force writes to be transmitted immediately.

This controls the TCP_NODELAY socket option. When enabled, TCP segments are sent as soon as possible, even if it is not a full frame of data. When disabled, the data may be buffered briefly to try and wait for a full frame of data.

By default, TCP_NODELAY is enabled for AsyncSocket objects.

This method will fail if the socket is not currently open.

Returns
Returns 0 if the TCP_NODELAY flag was successfully updated, or a non-zero errno value on error.

Definition at line 1589 of file AsyncSocket.cpp.

References folly::errnoStr(), fd_, folly::netops::setsockopt(), state_, and folly::value().

Referenced by connect(), and getTFOFinished().

1589  {
1590  if (fd_ < 0) {
1591  VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket " << this
1592  << "(state=" << state_ << ")";
1593  return EINVAL;
1594  }
1595 
1596  int value = noDelay ? 1 : 0;
1597  if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1598  int errnoCopy = errno;
1599  VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket " << this
1600  << " (fd=" << fd_ << ", state=" << state_
1601  << "): " << errnoStr(errnoCopy);
1602  return errnoCopy;
1603  }
1604 
1605  return 0;
1606 }
int setsockopt(NetworkSocket s, int level, int optname, const void *optval, socklen_t optlen)
Definition: NetOps.cpp:384
fbstring errnoStr(int err)
Definition: String.cpp:463
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
uint64_t value(const typename LockFreeRingBuffer< T, Atom >::Cursor &rbcursor)
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::setPeerCertificate ( std::unique_ptr< const AsyncTransportCertificate cert)
inline

Definition at line 833 of file AsyncSocket.h.

References folly::gen::move, and peerCertData_.

834  {
835  peerCertData_ = std::move(cert);
836  }
std::unique_ptr< const AsyncTransportCertificate > peerCertData_
Definition: AsyncSocket.h:1282
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
virtual void folly::AsyncSocket::setPreReceivedData ( std::unique_ptr< IOBuf data)
inlinevirtual

Set pre-received data, to be returned to read callback before any data from the socket.

Reimplemented in folly::test::MockAsyncSocket.

Definition at line 770 of file AsyncSocket.h.

References folly::gen::move, and preReceivedData_.

Referenced by wangle::SocketPeeker::readDataAvailable().

770  {
771  if (preReceivedData_) {
772  preReceivedData_->prependChain(std::move(data));
773  } else {
774  preReceivedData_ = std::move(data);
775  }
776  }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::unique_ptr< IOBuf > preReceivedData_
Definition: AsyncSocket.h:1258
int folly::AsyncSocket::setQuickAck ( bool  quickack)

Definition at line 1635 of file AsyncSocket.cpp.

References folly::errnoStr(), fd_, folly::netops::setsockopt(), state_, and folly::value().

Referenced by getTFOFinished().

1635  {
1636  (void)quickack;
1637  if (fd_ < 0) {
1638  VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket " << this
1639  << "(state=" << state_ << ")";
1640  return EINVAL;
1641  }
1642 
1643 #ifdef TCP_QUICKACK // Linux-only
1644  int value = quickack ? 1 : 0;
1645  if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1646  int errnoCopy = errno;
1647  VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket" << this
1648  << "(fd=" << fd_ << ", state=" << state_
1649  << "): " << errnoStr(errnoCopy);
1650  return errnoCopy;
1651  }
1652 
1653  return 0;
1654 #else
1655  return ENOSYS;
1656 #endif
1657 }
int setsockopt(NetworkSocket s, int level, int optname, const void *optval, socklen_t optlen)
Definition: NetOps.cpp:384
fbstring errnoStr(int err)
Definition: String.cpp:463
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
uint64_t value(const typename LockFreeRingBuffer< T, Atom >::Cursor &rbcursor)
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::setReadCB ( ReadCallback callback)
overridevirtual

Implements folly::AsyncTransportWrapper.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 768 of file AsyncSocket.cpp.

References folly::EventBase::LoopCallback::cancelLoopCallback(), checkForImmediateRead(), CLOSED, CONNECTING, folly::EventBase::dcheckIsInEventBaseThread(), ERROR, ESTABLISHED, eventBase_, eventFlags_, FAST_OPEN, fd_, immediateReadHandler_, invalidState(), folly::EventBase::LoopCallback::isLoopCallbackScheduled(), folly::EventHandler::READ, readCallback_, SHUT_READ, shutdownFlags_, state_, uint16_t, UNINIT, and updateEventRegistration().

Referenced by folly::test::MockAsyncSocket::connect(), getMaxReadsPerEvent(), wangle::SocketPeeker::readDataAvailable(), wangle::SocketPeeker::readErr(), folly::AsyncSSLSocket::setReadCB(), wangle::SocketPeeker::start(), TEST(), testConnectOptWrite(), tmpDisableReads(), and wangle::SocketPeeker::~SocketPeeker().

768  {
769  VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
770  << ", callback=" << callback << ", state=" << state_;
771 
772  // Short circuit if callback is the same as the existing readCallback_.
773  //
774  // Note that this is needed for proper functioning during some cleanup cases.
775  // During cleanup we allow setReadCallback(nullptr) to be called even if the
776  // read callback is already unset and we have been detached from an event
777  // base. This check prevents us from asserting
778  // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
779  if (callback == readCallback_) {
780  return;
781  }
782 
783  /* We are removing a read callback */
784  if (callback == nullptr && immediateReadHandler_.isLoopCallbackScheduled()) {
786  }
787 
788  if (shutdownFlags_ & SHUT_READ) {
789  // Reads have already been shut down on this socket.
790  //
791  // Allow setReadCallback(nullptr) to be called in this case, but don't
792  // allow a new callback to be set.
793  //
794  // For example, setReadCallback(nullptr) can happen after an error if we
795  // invoke some other error callback before invoking readError(). The other
796  // error callback that is invoked first may go ahead and clear the read
797  // callback before we get a chance to invoke readError().
798  if (callback != nullptr) {
799  return invalidState(callback);
800  }
801  assert((eventFlags_ & EventHandler::READ) == 0);
802  readCallback_ = nullptr;
803  return;
804  }
805 
806  DestructorGuard dg(this);
808 
809  switch ((StateEnum)state_) {
812  // For convenience, we allow the read callback to be set while we are
813  // still connecting. We just store the callback for now. Once the
814  // connection completes we'll register for read events.
815  readCallback_ = callback;
816  return;
817  case StateEnum::ESTABLISHED: {
818  readCallback_ = callback;
819  uint16_t oldFlags = eventFlags_;
820  if (readCallback_) {
822  } else {
823  eventFlags_ &= ~EventHandler::READ;
824  }
825 
826  // Update our registration if our flags have changed
827  if (eventFlags_ != oldFlags) {
828  // We intentionally ignore the return value here.
829  // updateEventRegistration() will move us into the error state if it
830  // fails, and we don't need to do anything else here afterwards.
831  (void)updateEventRegistration();
832  }
833 
834  if (readCallback_) {
836  }
837  return;
838  }
839  case StateEnum::CLOSED:
840  case StateEnum::ERROR:
841  // We should never reach here. SHUT_READ should always be set
842  // if we are in STATE_CLOSED or STATE_ERROR.
843  assert(false);
844  return invalidState(callback);
845  case StateEnum::UNINIT:
846  // We do not allow setReadCallback() to be called before we start
847  // connecting.
848  return invalidState(callback);
849  }
850 
851  // We don't put a default case in the switch statement, so that the compiler
852  // will warn us to update the switch statement if a new state is added.
853  return invalidState(callback);
854 }
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
bool updateEventRegistration()
uint8_t shutdownFlags_
Shutdown state (ShutdownFlags)
Definition: AsyncSocket.h:1227
bool isLoopCallbackScheduled() const
Definition: EventBase.h:160
ImmediateReadCB immediateReadHandler_
LoopCallback for checking read.
Definition: AsyncSocket.h:1243
void invalidState(ConnectCallback *callback)
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
StateEnum
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
ReadCallback * readCallback_
ReadCallback.
Definition: AsyncSocket.h:1249
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
virtual void checkForImmediateRead() noexcept
int folly::AsyncSocket::setRecvBufSize ( size_t  bufsize)

Set the recv bufsize

Definition at line 1677 of file AsyncSocket.cpp.

References folly::errnoStr(), fd_, folly::netops::setsockopt(), and state_.

Referenced by getTFOFinished().

1677  {
1678  if (fd_ < 0) {
1679  VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1680  << this << "(state=" << state_ << ")";
1681  return EINVAL;
1682  }
1683 
1684  if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) != 0) {
1685  int errnoCopy = errno;
1686  VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket" << this
1687  << "(fd=" << fd_ << ", state=" << state_
1688  << "): " << errnoStr(errnoCopy);
1689  return errnoCopy;
1690  }
1691 
1692  return 0;
1693 }
int setsockopt(NetworkSocket s, int level, int optname, const void *optval, socklen_t optlen)
Definition: NetOps.cpp:384
fbstring errnoStr(int err)
Definition: String.cpp:463
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::setSelfCertificate ( std::unique_ptr< const AsyncTransportCertificate cert)
inline

Definition at line 841 of file AsyncSocket.h.

References folly::gen::move, and selfCertData_.

842  {
843  selfCertData_ = std::move(cert);
844  }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::unique_ptr< const AsyncTransportCertificate > selfCertData_
Definition: AsyncSocket.h:1284
int folly::AsyncSocket::setSendBufSize ( size_t  bufsize)

Set the send bufsize

Definition at line 1659 of file AsyncSocket.cpp.

References folly::errnoStr(), fd_, folly::netops::setsockopt(), and state_.

Referenced by getTFOFinished().

1659  {
1660  if (fd_ < 0) {
1661  VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1662  << this << "(state=" << state_ << ")";
1663  return EINVAL;
1664  }
1665 
1666  if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) != 0) {
1667  int errnoCopy = errno;
1668  VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket" << this
1669  << "(fd=" << fd_ << ", state=" << state_
1670  << "): " << errnoStr(errnoCopy);
1671  return errnoCopy;
1672  }
1673 
1674  return 0;
1675 }
int setsockopt(NetworkSocket s, int level, int optname, const void *optval, socklen_t optlen)
Definition: NetOps.cpp:384
fbstring errnoStr(int err)
Definition: String.cpp:463
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::setSendMsgParamCB ( SendMsgParamsCallback callback)
virtual

Set a pointer to SendMsgParamsCallback implementation which will be used to form sendmsg() system call parameters

Definition at line 760 of file AsyncSocket.cpp.

References sendMsgParamCallback_.

Referenced by folly::test::MockAsyncSocket::connect(), and getMaxReadsPerEvent().

760  {
761  sendMsgParamCallback_ = callback;
762 }
SendMsgParamsCallback * sendMsgParamCallback_
< Callback for retrieving
Definition: AsyncSocket.h:1248
void folly::AsyncSocket::setSendTimeout ( uint32_t  milliseconds)
overridevirtual

Set the send timeout.

If write requests do not make any progress for more than the specified number of milliseconds, fail all pending writes and close the socket.

If write requests are currently pending when setSendTimeout() is called, the timeout interval is immediately restarted using the new value.

(See the comments for AsyncSocket for an explanation of why AsyncSocket provides setSendTimeout() but not setRecvTimeout().)

Parameters
millisecondsThe timeout duration, in milliseconds. If 0, no timeout will be used.

Implements folly::AsyncTransport.

Definition at line 666 of file AsyncSocket.cpp.

References folly::AsyncTimeout::cancelTimeout(), CONNECTING, folly::EventBase::dcheckIsInEventBaseThread(), ESTABLISHED, eventBase_, eventFlags_, failWrite(), FAST_OPEN, folly::AsyncSocketException::INTERNAL_ERROR, folly::AsyncTimeout::scheduleTimeout(), sendTimeout_, SHUT_WRITE, shutdownFlags_, state_, withAddr(), folly::EventHandler::WRITE, and writeTimeout_.

666  {
667  sendTimeout_ = milliseconds;
668  if (eventBase_) {
670  }
671 
672  // If we are currently pending on write requests, immediately update
673  // writeTimeout_ with the new value.
676  assert(state_ == StateEnum::ESTABLISHED);
677  assert((shutdownFlags_ & SHUT_WRITE) == 0);
678  if (sendTimeout_ > 0) {
680  AsyncSocketException ex(
682  withAddr("failed to reschedule send timeout in setSendTimeout"));
683  return failWrite(__func__, ex);
684  }
685  } else {
687  }
688  }
689 }
std::string withAddr(const std::string &s)
uint32_t sendTimeout_
The send timeout, in milliseconds.
Definition: AsyncSocket.h:1233
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
uint8_t shutdownFlags_
Shutdown state (ShutdownFlags)
Definition: AsyncSocket.h:1227
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
WriteTimeout writeTimeout_
A timeout for connect and write.
Definition: AsyncSocket.h:1241
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
bool scheduleTimeout(uint32_t milliseconds)
void failWrite(const char *fn, WriteCallback *callback, size_t bytesWritten, const AsyncSocketException &ex)
writes have been completely shut down
Definition: AsyncSocket.h:966
void folly::AsyncSocket::setShutdownSocketSet ( const std::weak_ptr< ShutdownSocketSet > &  wSS)

Definition at line 400 of file AsyncSocket.cpp.

References fd_, folly::ShutdownSocketSet::remove(), folly::test::shutdownSocketSet, and wShutdownSocketSet_.

Referenced by folly::AsyncSocket::SendMsgParamsCallback::getFlagsImpl().

401  {
402  const auto newSS = wNewSS.lock();
403  const auto shutdownSocketSet = wShutdownSocketSet_.lock();
404 
405  if (newSS == shutdownSocketSet) {
406  return;
407  }
408 
409  if (shutdownSocketSet && fd_ != -1) {
411  }
412 
413  if (newSS && fd_ != -1) {
414  newSS->add(fd_);
415  }
416 
417  wShutdownSocketSet_ = wNewSS;
418 }
std::weak_ptr< ShutdownSocketSet > wShutdownSocketSet_
Definition: AsyncSocket.h:1252
ShutdownSocketSet shutdownSocketSet
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
template<typename T >
int folly::AsyncSocket::setSockOpt ( int  level,
int  optname,
const T optval 
)
inline

Generic API for setting a socket option.

Parameters
levelsame as the "level" parameter in getsockopt().
optnamesame as the "optname" parameter in getsockopt().
optvalthe option value to set.
Returns
same as the return value of setsockopt().

Definition at line 727 of file AsyncSocket.h.

References fd_, folly::netops::setsockopt(), and folly::T.

Referenced by closeWithReset().

727  {
728  return setsockopt(fd_, level, optname, optval, sizeof(T));
729  }
int setsockopt(NetworkSocket s, int level, int optname, const void *optval, socklen_t optlen)
Definition: NetOps.cpp:384
folly::std T
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
virtual int folly::AsyncSocket::setSockOptVirtual ( int  level,
int  optname,
void const *  optval,
socklen_t  optlen 
)
inlinevirtual

Virtual method for setting a socket option accepting integer value, which is the most typical case. Convenient for overriding and mocking.

Parameters
levelsame as the "level" parameter in setsockopt().
optnamesame as the "optname" parameter in setsockopt().
optvalsame as "optval" parameter in setsockopt().
optlensame as "optlen" parameter in setsockopt().
Returns
same as the return value of setsockopt().

Definition at line 758 of file AsyncSocket.h.

References fd_, and folly::netops::setsockopt().

Referenced by folly::test::MockAsyncSocket::connect().

762  {
763  return setsockopt(fd_, level, optname, optval, optlen);
764  }
int setsockopt(NetworkSocket s, int level, int optname, const void *optval, socklen_t optlen)
Definition: NetOps.cpp:384
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
int folly::AsyncSocket::setTCPProfile ( int  profd)

Definition at line 1695 of file AsyncSocket.cpp.

References folly::errnoStr(), fd_, folly::netops::setsockopt(), SO_SET_NAMESPACE, and state_.

1695  {
1696  if (fd_ < 0) {
1697  VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket " << this
1698  << "(state=" << state_ << ")";
1699  return EINVAL;
1700  }
1701 
1702  if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) != 0) {
1703  int errnoCopy = errno;
1704  VLOG(2) << "failed to set socket namespace option on AsyncSocket" << this
1705  << "(fd=" << fd_ << ", state=" << state_
1706  << "): " << errnoStr(errnoCopy);
1707  return errnoCopy;
1708  }
1709 
1710  return 0;
1711 }
int setsockopt(NetworkSocket s, int level, int optname, const void *optval, socklen_t optlen)
Definition: NetOps.cpp:384
#define SO_SET_NAMESPACE
Definition: AsyncSocket.h:698
fbstring errnoStr(int err)
Definition: String.cpp:463
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
bool folly::AsyncSocket::setZeroCopy ( bool  enable)

Definition at line 860 of file AsyncSocket.cpp.

References fd_, folly::netops::getsockopt(), folly::netops::setsockopt(), SO_ZEROCOPY, val, zeroCopyEnabled_, and zeroCopyVal_.

Referenced by connect(), and getMaxReadsPerEvent().

860  {
861  if (msgErrQueueSupported) {
862  zeroCopyVal_ = enable;
863 
864  if (fd_ < 0) {
865  return false;
866  }
867 
868  int val = enable ? 1 : 0;
869  int ret = setsockopt(fd_, SOL_SOCKET, SO_ZEROCOPY, &val, sizeof(val));
870 
871  // if enable == false, set zeroCopyEnabled_ = false regardless
872  // if SO_ZEROCOPY is set or not
873  if (!enable) {
874  zeroCopyEnabled_ = enable;
875  return true;
876  }
877 
878  /* if the setsockopt failed, try to see if the socket inherited the flag
879  * since we cannot set SO_ZEROCOPY on a socket s = accept
880  */
881  if (ret) {
882  val = 0;
883  socklen_t optlen = sizeof(val);
884  ret = getsockopt(fd_, SOL_SOCKET, SO_ZEROCOPY, &val, &optlen);
885 
886  if (!ret) {
887  enable = val ? true : false;
888  }
889  }
890 
891  if (!ret) {
892  zeroCopyEnabled_ = enable;
893 
894  return true;
895  }
896  }
897 
898  return false;
899 }
#define SO_ZEROCOPY
Definition: NetOps.h:51
int setsockopt(NetworkSocket s, int level, int optname, const void *optval, socklen_t optlen)
Definition: NetOps.cpp:384
double val
Definition: String.cpp:273
int getsockopt(NetworkSocket s, int level, int optname, void *optval, socklen_t *optlen)
Definition: NetOps.cpp:112
static constexpr bool msgErrQueueSupported
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::setZeroCopyBuf ( std::unique_ptr< folly::IOBuf > &&  buf)
protected

Definition at line 955 of file AsyncSocket.cpp.

References idZeroCopyBufInfoMap_, folly::gen::move, and ptr.

Referenced by getNextZeroCopyBufId(), and folly::AsyncSocket::BytesWriteRequest::performWrite().

955  {
956  folly::IOBuf* ptr = buf.get();
957  auto& p = idZeroCopyBufInfoMap_[ptr];
958  CHECK(p.buf_.get() == nullptr);
959 
960  p.buf_ = std::move(buf);
961 }
void * ptr
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::unordered_map< folly::IOBuf *, IOBufInfo > idZeroCopyBufInfoMap_
Definition: AsyncSocket.h:1224
void folly::AsyncSocket::setZeroCopyReenableThreshold ( size_t  threshold)

Definition at line 901 of file AsyncSocket.cpp.

References zeroCopyReenableThreshold_.

Referenced by getZeroCopyReenableThreshold().

901  {
902  zeroCopyReenableThreshold_ = threshold;
903 }
size_t zeroCopyReenableThreshold_
Definition: AsyncSocket.h:1278
void folly::AsyncSocket::shutdownWrite ( )
overridevirtual

Perform a half-shutdown of the write side of the transport.

The caller should not make any more calls to write() or writev() after shutdownWrite() is called. Any future write attempts will fail immediately.

Not all transport types support half-shutdown. If the underlying transport does not support half-shutdown, it will fully shutdown both the read and write sides of the transport. (Fully shutting down the socket is better than doing nothing at all, since the caller may rely on the shutdownWrite() call to notify the other end of the connection that no more data can be read.)

If there is pending data still waiting to be written on the transport, the actual shutdown will be delayed until the pending data has been written.

Note: There is no corresponding shutdownRead() equivalent. Simply uninstall the read callback if you wish to stop reading. (On TCP sockets at least, shutting down the read side of the socket is a no-op anyway.)

Implements folly::AsyncTransport.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 1339 of file AsyncSocket.cpp.

References folly::EventBase::dcheckIsInEventBaseThread(), eventBase_, fd_, SHUT_WRITE_PENDING, shutdownFlags_, shutdownWriteNow(), state_, and writeReqHead_.

Referenced by writeRequestReady().

1339  {
1340  VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
1341  << ", state=" << state_ << ", shutdownFlags=" << std::hex
1342  << (int)shutdownFlags_;
1343 
1344  // If there are no pending writes, shutdownWrite() is identical to
1345  // shutdownWriteNow().
1346  if (writeReqHead_ == nullptr) {
1347  shutdownWriteNow();
1348  return;
1349  }
1350 
1352 
1353  // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
1354  // shutdown will be performed once all writes complete.
1356 }
void shutdownWriteNow() override
shutdownWrite() called, but we are still waiting on writes to drain
Definition: AsyncSocket.h:964
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
WriteRequest * writeReqHead_
Chain of WriteRequests.
Definition: AsyncSocket.h:1250
uint8_t shutdownFlags_
Shutdown state (ShutdownFlags)
Definition: AsyncSocket.h:1227
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::shutdownWriteNow ( )
overridevirtual

Perform a half-shutdown of the write side of the transport.

shutdownWriteNow() is identical to shutdownWrite(), except that it immediately performs the shutdown, rather than waiting for pending writes to complete. Any pending write requests will be immediately failed when shutdownWriteNow() is called.

Implements folly::AsyncTransport.

Reimplemented in folly::AsyncSSLSocket.

Definition at line 1358 of file AsyncSocket.cpp.

References folly::AsyncTimeout::cancelTimeout(), CLOSED, closeNow(), CONNECTING, folly::EventBase::dcheckIsInEventBaseThread(), folly::DFATAL, ERROR, ESTABLISHED, eventBase_, failAllWrites(), FAST_OPEN, fd_, SHUT_READ, SHUT_WRITE, SHUT_WRITE_PENDING, folly::shutdown(), shutdownFlags_, folly::socketShutdownForWritesEx, state_, UNINIT, updateEventRegistration(), folly::EventHandler::WRITE, and writeTimeout_.

Referenced by shutdownWrite(), and writeRequestReady().

1358  {
1359  VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this << ", fd=" << fd_
1360  << ", state=" << state_ << ", shutdownFlags=" << std::hex
1361  << (int)shutdownFlags_;
1362 
1363  if (shutdownFlags_ & SHUT_WRITE) {
1364  // Writes are already shutdown; nothing else to do.
1365  return;
1366  }
1367 
1368  // If SHUT_READ is already set, just call closeNow() to completely
1369  // close the socket. This can happen if close() was called with writes
1370  // pending, and then shutdownWriteNow() is called before all pending writes
1371  // complete.
1372  if (shutdownFlags_ & SHUT_READ) {
1373  closeNow();
1374  return;
1375  }
1376 
1377  DestructorGuard dg(this);
1378  if (eventBase_) {
1380  }
1381 
1382  switch (static_cast<StateEnum>(state_)) {
1383  case StateEnum::ESTABLISHED: {
1385 
1386  // If the write timeout was set, cancel it.
1388 
1389  // If we are registered for write events, unregister.
1391  // We will have been moved into the error state.
1392  assert(state_ == StateEnum::ERROR);
1393  return;
1394  }
1395 
1396  // Shutdown writes on the file descriptor
1397  shutdown(fd_, SHUT_WR);
1398 
1399  // Immediately fail all write requests
1401  return;
1402  }
1403  case StateEnum::CONNECTING: {
1404  // Set the SHUT_WRITE_PENDING flag.
1405  // When the connection completes, it will check this flag,
1406  // shutdown the write half of the socket, and then set SHUT_WRITE.
1408 
1409  // Immediately fail all write requests
1411  return;
1412  }
1413  case StateEnum::UNINIT:
1414  // Callers normally shouldn't call shutdownWriteNow() before the socket
1415  // even starts connecting. Nonetheless, go ahead and set
1416  // SHUT_WRITE_PENDING. Once the socket eventually connects it will
1417  // immediately shut down the write side of the socket.
1419  return;
1420  case StateEnum::FAST_OPEN:
1421  // In fast open state we haven't call connected yet, and if we shutdown
1422  // the writes, we will never try to call connect, so shut everything down
1424  // Immediately fail all write requests
1426  return;
1427  case StateEnum::CLOSED:
1428  case StateEnum::ERROR:
1429  // We should never get here. SHUT_WRITE should always be set
1430  // in STATE_CLOSED and STATE_ERROR.
1431  VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
1432  << ", fd=" << fd_ << ") in unexpected state " << state_
1433  << " with SHUT_WRITE not set (" << std::hex << (int)shutdownFlags_
1434  << ")";
1435  assert(false);
1436  return;
1437  }
1438 
1439  LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this
1440  << ", fd=" << fd_ << ") called in unknown state " << state_;
1441 }
shutdownWrite() called, but we are still waiting on writes to drain
Definition: AsyncSocket.h:964
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
void closeNow() override
bool updateEventRegistration()
void failAllWrites(const AsyncSocketException &ex)
uint8_t shutdownFlags_
Shutdown state (ShutdownFlags)
Definition: AsyncSocket.h:1227
const AsyncSocketException socketShutdownForWritesEx(AsyncSocketException::END_OF_FILE,"socket shutdown for writes")
void shutdown(Counter &)
WriteTimeout writeTimeout_
A timeout for connect and write.
Definition: AsyncSocket.h:1241
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
writes have been completely shut down
Definition: AsyncSocket.h:966
int folly::AsyncSocket::socketConnect ( const struct sockaddr *  addr,
socklen_t  len 
)
protected

Definition at line 600 of file AsyncSocket.cpp.

References folly::netops::connect(), fd_, folly::AsyncSocketException::NOT_OPEN, registerForConnectEvents(), and scheduleConnectTimeout().

Referenced by connect(), scheduleInitialReadWrite(), and sendSocketMessage().

600  {
601  int rv = fsp::connect(fd_, saddr, len);
602  if (rv < 0) {
603  auto errnoCopy = errno;
604  if (errnoCopy == EINPROGRESS) {
607  } else {
608  throw AsyncSocketException(
610  "connect failed (immediately)",
611  errnoCopy);
612  }
613  }
614  return rv;
615 }
int connect(NetworkSocket s, const sockaddr *name, socklen_t namelen)
Definition: NetOps.cpp:94
void registerForConnectEvents()
virtual void scheduleConnectTimeout()
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::startFail ( )
protected

Definition at line 2516 of file AsyncSocket.cpp.

References folly::EventBase::LoopCallback::cancelLoopCallback(), folly::AsyncTimeout::cancelTimeout(), folly::EventHandler::changeHandlerFD(), doClose(), ERROR, eventFlags_, fd_, folly::DelayedDestructionBase::getDestructorGuardCount(), immediateReadHandler_, ioHandler_, folly::EventBase::LoopCallback::isLoopCallbackScheduled(), folly::EventHandler::NONE, SHUT_READ, SHUT_WRITE, shutdownFlags_, state_, folly::EventHandler::unregisterHandler(), and writeTimeout_.

Referenced by fail(), failConnect(), failErrMessageRead(), folly::AsyncSSLSocket::failHandshake(), failRead(), failWrite(), invalidState(), and scheduleInitialReadWrite().

2516  {
2517  // startFail() should only be called once
2518  assert(state_ != StateEnum::ERROR);
2519  assert(getDestructorGuardCount() > 0);
2521  // Ensure that SHUT_READ and SHUT_WRITE are set,
2522  // so all future attempts to read or write will be rejected
2524 
2525  // Cancel any scheduled immediate read.
2528  }
2529 
2533  }
2535 
2536  if (fd_ >= 0) {
2538  doClose();
2539  }
2540 }
uint8_t shutdownFlags_
Shutdown state (ShutdownFlags)
Definition: AsyncSocket.h:1227
bool isLoopCallbackScheduled() const
Definition: EventBase.h:160
ImmediateReadCB immediateReadHandler_
LoopCallback for checking read.
Definition: AsyncSocket.h:1243
IoHandler ioHandler_
A EventHandler to monitor the fd.
Definition: AsyncSocket.h:1242
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
WriteTimeout writeTimeout_
A timeout for connect and write.
Definition: AsyncSocket.h:1241
void changeHandlerFD(int fd)
Definition: EventHandler.h:143
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
writes have been completely shut down
Definition: AsyncSocket.h:966
ssize_t folly::AsyncSocket::tfoSendMsg ( int  fd,
struct msghdr *  msg,
int  msg_flags 
)
protectedvirtual

Definition at line 2316 of file AsyncSocket.cpp.

References folly::detail::tfo_sendmsg().

Referenced by scheduleInitialReadWrite(), and sendSocketMessage().

2316  {
2317  return detail::tfo_sendmsg(fd, msg, msg_flags);
2318 }
ssize_t tfo_sendmsg(int, const struct msghdr *, int)
void folly::AsyncSocket::timeoutExpired ( )
protectednoexcept

Definition at line 2285 of file AsyncSocket.cpp.

References connectCallback_, CONNECTING, connectTimeout_, folly::EventBase::dcheckIsInEventBaseThread(), eventBase_, eventFlags_, failConnect(), failWrite(), fd_, sendTimeout_, folly::sformat(), state_, and folly::AsyncSocketException::TIMED_OUT.

Referenced by folly::AsyncSSLSocket::getSSLContext(), and scheduleInitialReadWrite().

2285  {
2286  VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
2287  << "state=" << state_ << ", events=" << std::hex << eventFlags_;
2288  DestructorGuard dg(this);
2290 
2291  if (state_ == StateEnum::CONNECTING) {
2292  // connect() timed out
2293  // Unregister for I/O events.
2294  if (connectCallback_) {
2295  AsyncSocketException ex(
2298  "connect timed out after {}ms", connectTimeout_.count()));
2299  failConnect(__func__, ex);
2300  } else {
2301  // we faced a connect error without a connect callback, which could
2302  // happen due to TFO.
2303  AsyncSocketException ex(
2304  AsyncSocketException::TIMED_OUT, "write timed out during connection");
2305  failWrite(__func__, ex);
2306  }
2307  } else {
2308  // a normal write operation timed out
2309  AsyncSocketException ex(
2311  folly::sformat("write timed out after {}ms", sendTimeout_));
2312  failWrite(__func__, ex);
2313  }
2314 }
std::string sformat(StringPiece fmt, Args &&...args)
Definition: Format.h:280
uint32_t sendTimeout_
The send timeout, in milliseconds.
Definition: AsyncSocket.h:1233
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
std::chrono::milliseconds connectTimeout_
Definition: AsyncSocket.h:1263
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
void failConnect(const char *fn, const AsyncSocketException &ex)
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void failWrite(const char *fn, WriteCallback *callback, size_t bytesWritten, const AsyncSocketException &ex)
ConnectCallback * connectCallback_
ConnectCallback.
Definition: AsyncSocket.h:1245
bool folly::AsyncSocket::updateEventRegistration ( )
protected

Re-register the EventHandler after eventFlags_ has changed.

If an error occurs, fail() is called to move the socket into the error state and call all currently installed callbacks. After an error, the AsyncSocket is completely unregistered.

Returns
Returns true on success, or false on error.

Definition at line 2480 of file AsyncSocket.cpp.

References folly::EventBase::dcheckIsInEventBaseThread(), eventBase_, eventFlags_, fail(), fd_, folly::AsyncSocketException::INTERNAL_ERROR, ioHandler_, folly::EventHandler::NONE, folly::EventHandler::PERSIST, folly::EventHandler::registerHandler(), state_, uint16_t, folly::EventHandler::unregisterHandler(), and withAddr().

Referenced by attachEventBase(), close(), closeNow(), folly::AsyncSSLSocket::handleAccept(), folly::AsyncSSLSocket::handleConnect(), handleInitialReadWrite(), handleRead(), folly::AsyncSSLSocket::handleReturnFromSSLAccept(), handleWrite(), scheduleInitialReadWrite(), setReadCB(), shutdownWriteNow(), folly::AsyncSSLSocket::sslAccept(), updateEventRegistration(), folly::AsyncSSLSocket::willBlock(), and writeImpl().

2480  {
2481  VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
2482  << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
2483  << ", events=" << std::hex << eventFlags_;
2485  if (eventFlags_ == EventHandler::NONE) {
2487  return true;
2488  }
2489 
2490  // Always register for persistent events, so we don't have to re-register
2491  // after being called back.
2493  uint16_t(eventFlags_ | EventHandler::PERSIST))) {
2494  eventFlags_ = EventHandler::NONE; // we're not registered after error
2495  AsyncSocketException ex(
2497  withAddr("failed to update AsyncSocket event registration"));
2498  fail("updateEventRegistration", ex);
2499  return false;
2500  }
2501 
2502  return true;
2503 }
std::string withAddr(const std::string &s)
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
void fail(const char *fn, const AsyncSocketException &ex)
IoHandler ioHandler_
A EventHandler to monitor the fd.
Definition: AsyncSocket.h:1242
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
bool registerHandler(uint16_t events)
Definition: EventHandler.h:100
bool folly::AsyncSocket::updateEventRegistration ( uint16_t  enable,
uint16_t  disable 
)
protected

Update event registration.

Parameters
enableFlags of events to enable. Set it to 0 if no events need to be enabled in this call.
disableFlags of events to disable. Set it to 0 if no events need to be disabled in this call.
Returns
true iff the update is successful.

Definition at line 2505 of file AsyncSocket.cpp.

References eventFlags_, uint16_t, and updateEventRegistration().

2505  {
2506  uint16_t oldFlags = eventFlags_;
2507  eventFlags_ |= enable;
2508  eventFlags_ &= ~disable;
2509  if (eventFlags_ == oldFlags) {
2510  return true;
2511  } else {
2512  return updateEventRegistration();
2513  }
2514 }
bool updateEventRegistration()
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
std::string folly::AsyncSocket::withAddr ( const std::string s)
protected

Definition at line 2814 of file AsyncSocket.cpp.

References folly::SocketAddress::describe(), folly::AsyncTransport::getLocalAddress(), folly::AsyncTransport::getPeerAddress(), and folly::fibers::local().

Referenced by connect(), finishFail(), handleConnect(), handleErrMessages(), handleRead(), handleWrite(), invalidState(), registerForConnectEvents(), folly::AsyncSSLSocket::scheduleConnectTimeout(), scheduleConnectTimeout(), scheduleInitialReadWrite(), setCloseOnExec(), setSendTimeout(), updateEventRegistration(), and writeImpl().

2814  {
2815  // Don't use addr_ directly because it may not be initialized
2816  // e.g. if constructed from fd
2818  try {
2819  getPeerAddress(&peer);
2820  getLocalAddress(&local);
2821  } catch (const std::exception&) {
2822  // ignore
2823  } catch (...) {
2824  // ignore
2825  }
2826  return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";
2827 }
std::string describe() const
SocketAddress getPeerAddress() const
SocketAddress getLocalAddress() const
static set< string > s
bool folly::AsyncSocket::writable ( ) const
overridevirtual

Determine if the transport is writable or not.

Returns
true iff the transport is writable, false otherwise.

Reimplemented from folly::AsyncTransport.

Definition at line 1455 of file AsyncSocket.cpp.

References fd_, and folly::netops::poll().

Referenced by writeRequestReady().

1455  {
1456  if (fd_ == -1) {
1457  return false;
1458  }
1459  struct pollfd fds[1];
1460  fds[0].fd = fd_;
1461  fds[0].events = POLLOUT;
1462  fds[0].revents = 0;
1463  int rc = poll(fds, 1, 0);
1464  return rc == 1;
1465 }
int poll(PollDescriptor fds[], nfds_t nfds, int timeout)
Definition: NetOps.cpp:141
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
void folly::AsyncSocket::write ( WriteCallback callback,
const void *  buf,
size_t  bytes,
WriteFlags  flags = WriteFlags::NONE 
)
overridevirtual

If you supply a non-null WriteCallback, exactly one of writeSuccess() or writeErr() will be invoked when the write completes. If you supply the same WriteCallback object for multiple write() calls, it will be invoked exactly once per call. The only way to cancel outstanding write requests is to close the socket (e.g., with closeNow() or shutdownWriteNow()). When closing the socket this way, writeErr() will still be invoked once for each outstanding write operation.

Implements folly::AsyncTransportWrapper.

Definition at line 1003 of file AsyncSocket.cpp.

References writeImpl().

Referenced by getZeroCopyReenableThreshold(), and TEST().

1007  {
1008  iovec op;
1009  op.iov_base = const_cast<void*>(buf);
1010  op.iov_len = bytes;
1011  writeImpl(callback, &op, 1, unique_ptr<IOBuf>(), flags);
1012 }
flags
Definition: http_parser.h:127
void writeImpl(WriteCallback *callback, const iovec *vec, size_t count, std::unique_ptr< folly::IOBuf > &&buf, WriteFlags flags=WriteFlags::NONE)
void folly::AsyncSocket::writeChain ( WriteCallback callback,
std::unique_ptr< folly::IOBuf > &&  buf,
WriteFlags  flags = WriteFlags::NONE 
)
overridevirtual

If you supply a non-null WriteCallback, exactly one of writeSuccess() or writeErr() will be invoked when the write completes. If you supply the same WriteCallback object for multiple write() calls, it will be invoked exactly once per call. The only way to cancel outstanding write requests is to close the socket (e.g., with closeNow() or shutdownWriteNow()). When closing the socket this way, writeErr() will still be invoked once for each outstanding write operation.

Implements folly::AsyncTransportWrapper.

Definition at line 1022 of file AsyncSocket.cpp.

References adjustZeroCopyFlags(), count, FOLLY_GNU_DISABLE_WARNING, FOLLY_HAVE_VLA_01, FOLLY_POP_WARNING, FOLLY_PUSH_WARNING, folly::gen::move, and writeChainImpl().

Referenced by getZeroCopyReenableThreshold().

1025  {
1027 
1028  constexpr size_t kSmallSizeMax = 64;
1029  size_t count = buf->countChainElements();
1030  if (count <= kSmallSizeMax) {
1031  // suppress "warning: variable length array 'vec' is used [-Wvla]"
1033  FOLLY_GNU_DISABLE_WARNING("-Wvla")
1034  iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA_01, count, kSmallSizeMax)];
1036 
1037  writeChainImpl(callback, vec, count, std::move(buf), flags);
1038  } else {
1039  iovec* vec = new iovec[count];
1040  writeChainImpl(callback, vec, count, std::move(buf), flags);
1041  delete[] vec;
1042  }
1043 }
#define FOLLY_GNU_DISABLE_WARNING(warningName)
Definition: Portability.h:180
#define FOLLY_POP_WARNING
Definition: Portability.h:179
flags
Definition: http_parser.h:127
#define FOLLY_PUSH_WARNING
Definition: Portability.h:178
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
STL namespace.
size_t countChainElements() const
Definition: IOBuf.cpp:493
void writeChainImpl(WriteCallback *callback, iovec *vec, size_t count, std::unique_ptr< folly::IOBuf > &&buf, WriteFlags flags)
#define FOLLY_HAVE_VLA_01
Definition: AsyncSocket.cpp:40
Definition: Traits.h:588
int * count
vector< string > vec
Definition: StringTest.cpp:35
void adjustZeroCopyFlags(folly::WriteFlags &flags)
void folly::AsyncSocket::writeChainImpl ( WriteCallback callback,
iovec *  vec,
size_t  count,
std::unique_ptr< folly::IOBuf > &&  buf,
WriteFlags  flags 
)
protected

Populate an iovec array from an IOBuf and attempt to write it.

Parameters
callbackWrite completion/error callback.
vecTarget iovec array; caller retains ownership.
countNumber of IOBufs to write, beginning at start of buf.
bufChain of iovecs.
flagsset of flags for the underlying write calls, like cork

Definition at line 1045 of file AsyncSocket.cpp.

References folly::gen::move, and writeImpl().

Referenced by scheduleInitialReadWrite(), and writeChain().

1050  {
1051  size_t veclen = buf->fillIov(vec, count);
1052  writeImpl(callback, vec, veclen, std::move(buf), flags);
1053 }
flags
Definition: http_parser.h:127
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
size_t fillIov(struct iovec *iov, size_t len) const
Definition: IOBuf.cpp:1072
Definition: Traits.h:588
int * count
void writeImpl(WriteCallback *callback, const iovec *vec, size_t count, std::unique_ptr< folly::IOBuf > &&buf, WriteFlags flags=WriteFlags::NONE)
void folly::AsyncSocket::writeImpl ( WriteCallback callback,
const iovec *  vec,
size_t  count,
std::unique_ptr< folly::IOBuf > &&  buf,
WriteFlags  flags = WriteFlags::NONE 
)
protected

Write as much data as possible to the socket without blocking, and queue up any leftover data to send when the socket can handle writes again.

Parameters
callbackThe callback to invoke when the write is completed.
vecArray of buffers to write; this method will make a copy of the vector (but not the buffers themselves) if the write has to be completed asynchronously.
countNumber of elements in vec.
bufThe IOBuf that manages the buffers referenced by vec, or a pointer to nullptr if the buffers are not associated with an IOBuf. Note that ownership of the IOBuf is transferred here; upon completion of the write, the AsyncSocket deletes the IOBuf.
flagsSet of write flags.

Definition at line 1055 of file AsyncSocket.cpp.

References addZeroCopyBuf(), folly::AsyncSocket::WriteRequest::append(), bufferCallback_, connecting(), folly::AsyncSocket::WriteRequest::consume(), folly::EventBase::dcheckIsInEventBaseThread(), ERROR, ESTABLISHED, eventBase_, eventFlags_, failWrite(), FAST_OPEN, fd_, folly::AsyncSocketException::INTERNAL_ERROR, invalidState(), isZeroCopyRequest(), folly::gen::move, folly::AsyncSocket::BytesWriteRequest::newRequest(), folly::AsyncTransport::BufferCallback::onEgressBuffered(), performWrite(), folly::AsyncTimeout::scheduleTimeout(), sendTimeout_, SHUT_WRITE, SHUT_WRITE_PENDING, shutdownFlags_, state_, uint32_t, updateEventRegistration(), withAddr(), folly::EventHandler::WRITE, writeReqHead_, writeReqTail_, folly::AsyncWriter::WriteCallback::writeSuccess(), and writeTimeout_.

Referenced by scheduleInitialReadWrite(), write(), writeChainImpl(), and writev().

1060  {
1061  VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
1062  << ", callback=" << callback << ", count=" << count
1063  << ", state=" << state_;
1064  DestructorGuard dg(this);
1065  unique_ptr<IOBuf> ioBuf(std::move(buf));
1067 
1069  // No new writes may be performed after the write side of the socket has
1070  // been shutdown.
1071  //
1072  // We could just call callback->writeError() here to fail just this write.
1073  // However, fail hard and use invalidState() to fail all outstanding
1074  // callbacks and move the socket into the error state. There's most likely
1075  // a bug in the caller's code, so we abort everything rather than trying to
1076  // proceed as best we can.
1077  return invalidState(callback);
1078  }
1079 
1080  uint32_t countWritten = 0;
1081  uint32_t partialWritten = 0;
1082  ssize_t bytesWritten = 0;
1083  bool mustRegister = false;
1084  if ((state_ == StateEnum::ESTABLISHED || state_ == StateEnum::FAST_OPEN) &&
1085  !connecting()) {
1086  if (writeReqHead_ == nullptr) {
1087  // If we are established and there are no other writes pending,
1088  // we can attempt to perform the write immediately.
1089  assert(writeReqTail_ == nullptr);
1090  assert((eventFlags_ & EventHandler::WRITE) == 0);
1091 
1092  auto writeResult = performWrite(
1093  vec, uint32_t(count), flags, &countWritten, &partialWritten);
1094  bytesWritten = writeResult.writeReturn;
1095  if (bytesWritten < 0) {
1096  auto errnoCopy = errno;
1097  if (writeResult.exception) {
1098  return failWrite(__func__, callback, 0, *writeResult.exception);
1099  }
1100  AsyncSocketException ex(
1102  withAddr("writev failed"),
1103  errnoCopy);
1104  return failWrite(__func__, callback, 0, ex);
1105  } else if (countWritten == count) {
1106  // done, add the whole buffer
1107  if (countWritten && isZeroCopyRequest(flags)) {
1108  addZeroCopyBuf(std::move(ioBuf));
1109  }
1110  // We successfully wrote everything.
1111  // Invoke the callback and return.
1112  if (callback) {
1113  callback->writeSuccess();
1114  }
1115  return;
1116  } else { // continue writing the next writeReq
1117  // add just the ptr
1118  if (bytesWritten && isZeroCopyRequest(flags)) {
1119  addZeroCopyBuf(ioBuf.get());
1120  }
1121  if (bufferCallback_) {
1123  }
1124  }
1125  if (!connecting()) {
1126  // Writes might put the socket back into connecting state
1127  // if TFO is enabled, and using TFO fails.
1128  // This means that write timeouts would not be active, however
1129  // connect timeouts would affect this stage.
1130  mustRegister = true;
1131  }
1132  }
1133  } else if (!connecting()) {
1134  // Invalid state for writing
1135  return invalidState(callback);
1136  }
1137 
1138  // Create a new WriteRequest to add to the queue
1139  WriteRequest* req;
1140  try {
1142  this,
1143  callback,
1144  vec + countWritten,
1145  uint32_t(count - countWritten),
1146  partialWritten,
1147  uint32_t(bytesWritten),
1148  std::move(ioBuf),
1149  flags);
1150  } catch (const std::exception& ex) {
1151  // we mainly expect to catch std::bad_alloc here
1152  AsyncSocketException tex(
1154  withAddr(string("failed to append new WriteRequest: ") + ex.what()));
1155  return failWrite(__func__, callback, size_t(bytesWritten), tex);
1156  }
1157  req->consume();
1158  if (writeReqTail_ == nullptr) {
1159  assert(writeReqHead_ == nullptr);
1160  writeReqHead_ = writeReqTail_ = req;
1161  } else {
1162  writeReqTail_->append(req);
1163  writeReqTail_ = req;
1164  }
1165 
1166  // Register for write events if are established and not currently
1167  // waiting on write events
1168  if (mustRegister) {
1169  assert(state_ == StateEnum::ESTABLISHED);
1170  assert((eventFlags_ & EventHandler::WRITE) == 0);
1172  assert(state_ == StateEnum::ERROR);
1173  return;
1174  }
1175  if (sendTimeout_ > 0) {
1176  // Schedule a timeout to fire if the write takes too long.
1178  AsyncSocketException ex(
1180  withAddr("failed to schedule send timeout"));
1181  return failWrite(__func__, ex);
1182  }
1183  }
1184  }
1185 }
static BytesWriteRequest * newRequest(AsyncSocket *socket, WriteCallback *callback, const iovec *ops, uint32_t opCount, uint32_t partialWritten, uint32_t bytesWritten, unique_ptr< IOBuf > &&ioBuf, WriteFlags flags)
Definition: AsyncSocket.cpp:83
void writeSuccess() noexceptoverride
flags
Definition: http_parser.h:127
bool connecting() const override
Definition: AsyncSocket.h:567
std::string withAddr(const std::string &s)
folly::AsyncSocketException exception
bool isZeroCopyRequest(WriteFlags flags)
virtual WriteResult performWrite(const iovec *vec, uint32_t count, WriteFlags flags, uint32_t *countWritten, uint32_t *partialWritten)
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
uint32_t sendTimeout_
The send timeout, in milliseconds.
Definition: AsyncSocket.h:1233
shutdownWrite() called, but we are still waiting on writes to drain
Definition: AsyncSocket.h:964
EventBase * eventBase_
The EventBase.
Definition: AsyncSocket.h:1240
bool updateEventRegistration()
WriteRequest * writeReqTail_
End of WriteRequest chain.
Definition: AsyncSocket.h:1251
WriteRequest * writeReqHead_
Chain of WriteRequests.
Definition: AsyncSocket.h:1250
uint8_t shutdownFlags_
Shutdown state (ShutdownFlags)
Definition: AsyncSocket.h:1227
void invalidState(ConnectCallback *callback)
void append(WriteRequest *next)
Definition: AsyncSocket.h:915
uint16_t eventFlags_
EventBase::HandlerFlags settings.
Definition: AsyncSocket.h:1228
WriteTimeout writeTimeout_
A timeout for connect and write.
Definition: AsyncSocket.h:1241
Definition: Traits.h:588
void dcheckIsInEventBaseThread() const
Definition: EventBase.h:520
int * count
StateEnum state_
StateEnum describing current state.
Definition: AsyncSocket.h:1226
BufferCallback * bufferCallback_
Definition: AsyncSocket.h:1267
void addZeroCopyBuf(std::unique_ptr< folly::IOBuf > &&buf)
int fd_
The socket file descriptor.
Definition: AsyncSocket.h:1229
bool scheduleTimeout(uint32_t milliseconds)
void failWrite(const char *fn, WriteCallback *callback, size_t bytesWritten, const AsyncSocketException &ex)
writes have been completely shut down
Definition: AsyncSocket.h:966
void folly::AsyncSocket::writeRequest ( WriteRequest req)
virtual

Definition at line 1187 of file AsyncSocket.cpp.

References folly::AsyncSocket::WriteRequest::append(), folly::AsyncSocket::WriteRequest::start(), writeReqHead_, and writeReqTail_.

Referenced by getZeroCopyReenableThreshold().

1187  {
1188  if (writeReqTail_ == nullptr) {
1189  assert(writeReqHead_ == nullptr);
1190  writeReqHead_ = writeReqTail_ = req;
1191  req->start();
1192  } else {
1193  writeReqTail_->append(req);
1194  writeReqTail_ = req;
1195  }
1196 }
WriteRequest * writeReqTail_
End of WriteRequest chain.
Definition: AsyncSocket.h:1251
WriteRequest * writeReqHead_
Chain of WriteRequests.
Definition: AsyncSocket.h:1250
void append(WriteRequest *next)
Definition: AsyncSocket.h:915
void folly::AsyncSocket::writev ( WriteCallback callback,
const iovec *  vec,
size_t  count,
WriteFlags  flags = WriteFlags::NONE 
)
overridevirtual

If you supply a non-null WriteCallback, exactly one of writeSuccess() or writeErr() will be invoked when the write completes. If you supply the same WriteCallback object for multiple write() calls, it will be invoked exactly once per call. The only way to cancel outstanding write requests is to close the socket (e.g., with closeNow() or shutdownWriteNow()). When closing the socket this way, writeErr() will still be invoked once for each outstanding write operation.

Implements folly::AsyncTransportWrapper.

Definition at line 1014 of file AsyncSocket.cpp.

References writeImpl().

Referenced by getZeroCopyReenableThreshold().

1018  {
1019  writeImpl(callback, vec, count, unique_ptr<IOBuf>(), flags);
1020 }
flags
Definition: http_parser.h:127
Definition: Traits.h:588
int * count
void writeImpl(WriteCallback *callback, const iovec *vec, size_t count, std::unique_ptr< folly::IOBuf > &&buf, WriteFlags flags=WriteFlags::NONE)

Friends And Related Function Documentation

std::ostream& operator<< ( std::ostream &  os,
const StateEnum state 
)
friend

Definition at line 2807 of file AsyncSocket.cpp.

2809  {
2810  os << static_cast<int>(state);
2811  return os;
2812 }
state
Definition: http_parser.c:272

Member Data Documentation

folly::SocketAddress folly::AsyncSocket::addr_
mutableprotected

The address we tried to connect to.

Definition at line 1230 of file AsyncSocket.h.

Referenced by cachePeerAddress(), connect(), fail(), failConnect(), failErrMessageRead(), failRead(), failWrite(), getPeerAddress(), handleConnect(), and sendSocketMessage().

size_t folly::AsyncSocket::appBytesReceived_
protected

Num of bytes received from socket.

Definition at line 1253 of file AsyncSocket.h.

Referenced by getAppBytesReceived(), init(), folly::AsyncSSLSocket::performRead(), and performRead().

size_t folly::AsyncSocket::appBytesWritten_
protected

Num of bytes written to socket.

Definition at line 1254 of file AsyncSocket.h.

Referenced by folly::AsyncSSLSocket::eorAwareSSLWrite(), getAppBytesWritten(), init(), and performWrite().

BufferCallback* folly::AsyncSocket::bufferCallback_ {nullptr}
protected

Definition at line 1267 of file AsyncSocket.h.

Referenced by handleWrite(), setBufferCallback(), and writeImpl().

std::chrono::steady_clock::time_point folly::AsyncSocket::connectEndTime_
protected
std::chrono::steady_clock::time_point folly::AsyncSocket::connectStartTime_
protected

Definition at line 1260 of file AsyncSocket.h.

Referenced by connect(), getConnectStartTime(), and getConnectTime().

std::chrono::milliseconds folly::AsyncSocket::connectTimeout_ {0}
protected
const AsyncSocket::OptionMap folly::AsyncSocket::emptyOptionMap
static
ErrMessageCallback* folly::AsyncSocket::errMessageCallback_
protected

TimestampCallback.

Definition at line 1246 of file AsyncSocket.h.

Referenced by connect(), failErrMessageRead(), getErrMessageCallback(), handleErrMessages(), init(), and setErrMessageCB().

std::unique_ptr<EvbChangeCallback> folly::AsyncSocket::evbChangeCb_ {nullptr}
protected

Definition at line 1265 of file AsyncSocket.h.

Referenced by attachEventBase(), detachEventBase(), and setEvbChangedCallback().

int folly::AsyncSocket::fd_
protected

The socket file descriptor.

Definition at line 1229 of file AsyncSocket.h.

Referenced by AsyncSocket(), attachEventBase(), cacheAddresses(), cacheLocalAddress(), cachePeerAddress(), close(), folly::AsyncSSLSocket::closeNow(), closeNow(), closeWithReset(), connect(), destroy(), detachEventBase(), detachFd(), doClose(), fail(), failConnect(), failErrMessageRead(), failRead(), failWrite(), getFd(), getSockOpt(), getSockOptVirtual(), getTFOSucceded(), folly::AsyncSSLSocket::handleAccept(), folly::AsyncSSLSocket::handleConnect(), handleConnect(), handleErrMessages(), folly::AsyncSSLSocket::handleRead(), handleRead(), folly::AsyncSSLSocket::handleReturnFromSSLAccept(), folly::AsyncSSLSocket::handleWrite(), handleWrite(), hangup(), init(), folly::AsyncSSLSocket::interpretSSLError(), folly::AsyncSSLSocket::invalidState(), invalidState(), ioReady(), folly::AsyncSSLSocket::performRead(), performRead(), folly::AsyncSSLSocket::performWrite(), performWrite(), processZeroCopyMsg(), readable(), folly::AsyncSSLSocket::restartSSLAccept(), sendSocketMessage(), setCloseOnExec(), setCongestionFlavor(), setErrMessageCB(), setNoDelay(), setQuickAck(), setReadCB(), setRecvBufSize(), setSendBufSize(), setShutdownSocketSet(), setSockOpt(), setSockOptVirtual(), setTCPProfile(), folly::AsyncSSLSocket::setupSSLBio(), setZeroCopy(), shutdownWrite(), shutdownWriteNow(), socketConnect(), folly::AsyncSSLSocket::sslConn(), startFail(), timeoutExpired(), updateEventRegistration(), folly::AsyncSSLSocket::willBlock(), writable(), writeImpl(), ~AsyncSocket(), and folly::AsyncSSLSocket::~AsyncSSLSocket().

std::unordered_map<folly::IOBuf*, IOBufInfo> folly::AsyncSocket::idZeroCopyBufInfoMap_
protected
std::unordered_map<uint32_t, folly::IOBuf*> folly::AsyncSocket::idZeroCopyBufPtrMap_
protected
ImmediateReadCB folly::AsyncSocket::immediateReadHandler_
protected

LoopCallback for checking read.

Definition at line 1243 of file AsyncSocket.h.

Referenced by closeNow(), scheduleImmediateRead(), setReadCB(), and startFail().

IoHandler folly::AsyncSocket::ioHandler_
protected
bool folly::AsyncSocket::isBufferMovable_ {false}
protected
folly::SocketAddress folly::AsyncSocket::localAddr_
mutableprotected

The address we are connecting from.

Definition at line 1231 of file AsyncSocket.h.

Referenced by cacheLocalAddress(), getLocalAddress(), and setErrMessageCB().

uint16_t folly::AsyncSocket::maxReadsPerEvent_
protected

Max reads per event loop iteration.

Definition at line 1234 of file AsyncSocket.h.

Referenced by getMaxReadsPerEvent(), handleRead(), init(), and setMaxReadsPerEvent().

bool folly::AsyncSocket::noTransparentTls_ {false}
protected
bool folly::AsyncSocket::noTSocks_ {false}
protected

Definition at line 1272 of file AsyncSocket.h.

Referenced by AsyncSocket(), connect(), and disableTSocks().

std::unique_ptr<const AsyncTransportCertificate> folly::AsyncSocket::peerCertData_
mutableprotected
Initial value:
{
nullptr}

Definition at line 1282 of file AsyncSocket.h.

Referenced by folly::AsyncSSLSocket::getPeerCertificate(), getPeerCertificate(), and setPeerCertificate().

std::unique_ptr<IOBuf> folly::AsyncSocket::preReceivedData_
protected
int8_t folly::AsyncSocket::readErr_ {READ_NO_ERROR}
protected

The read error encountered, if any.

Definition at line 1238 of file AsyncSocket.h.

Referenced by handleRead(), isClosedByPeer(), and isClosedBySelf().

std::unique_ptr<const AsyncTransportCertificate> folly::AsyncSocket::selfCertData_
mutableprotected
Initial value:
{
nullptr}

Definition at line 1284 of file AsyncSocket.h.

Referenced by folly::AsyncSSLSocket::getSelfCertificate(), getSelfCertificate(), and setSelfCertificate().

SendMsgParamsCallback* folly::AsyncSocket::sendMsgParamCallback_
protected

< Callback for retrieving

sendmsg() parameters

Definition at line 1248 of file AsyncSocket.h.

Referenced by getSendMsgParamsCB(), init(), performWrite(), and setSendMsgParamCB().

uint32_t folly::AsyncSocket::sendTimeout_
protected

The send timeout, in milliseconds.

Definition at line 1233 of file AsyncSocket.h.

Referenced by getSendTimeout(), handleWrite(), init(), setSendTimeout(), timeoutExpired(), and writeImpl().

uint8_t folly::AsyncSocket::shutdownFlags_
protected
StateEnum folly::AsyncSocket::state_
protected
bool folly::AsyncSocket::tfoAttempted_ {false}
protected
bool folly::AsyncSocket::tfoEnabled_ {false}
protected

Definition at line 1268 of file AsyncSocket.h.

Referenced by connect(), and enableTFO().

bool folly::AsyncSocket::tfoFinished_ {false}
protected

Definition at line 1270 of file AsyncSocket.h.

Referenced by getTFOFinished(), and sendSocketMessage().

bool folly::AsyncSocket::trackEor_ {false}
protected

Definition at line 1274 of file AsyncSocket.h.

Referenced by isEorTrackingEnabled(), and setEorTracking().

WriteRequest* folly::AsyncSocket::writeReqHead_
protected
WriteRequest* folly::AsyncSocket::writeReqTail_
protected

End of WriteRequest chain.

Definition at line 1251 of file AsyncSocket.h.

Referenced by handleWrite(), init(), writeImpl(), and writeRequest().

WriteTimeout folly::AsyncSocket::writeTimeout_
protected
std::weak_ptr<ShutdownSocketSet> folly::AsyncSocket::wShutdownSocketSet_
protected

Definition at line 1252 of file AsyncSocket.h.

Referenced by connect(), detachFd(), doClose(), init(), and setShutdownSocketSet().

uint32_t folly::AsyncSocket::zeroCopyBufId_ {0}
protected

Definition at line 1216 of file AsyncSocket.h.

Referenced by getNextZeroCopyBufId(), and getZeroCopyBufId().

bool folly::AsyncSocket::zeroCopyEnabled_ {false}
protected
size_t folly::AsyncSocket::zeroCopyReenableCounter_ {0}
protected

Definition at line 1279 of file AsyncSocket.h.

Referenced by adjustZeroCopyFlags(), and performWrite().

size_t folly::AsyncSocket::zeroCopyReenableThreshold_ {0}
protected
bool folly::AsyncSocket::zeroCopyVal_ {false}
protected

Definition at line 1276 of file AsyncSocket.h.

Referenced by connect(), and setZeroCopy().


The documentation for this class was generated from the following files: