/*
- * Copyright 2016 Facebook, Inc.
+ * Copyright 2017 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <folly/io/async/AsyncSocket.h>
#include <folly/ExceptionWrapper.h>
+#include <folly/Portability.h>
#include <folly/SocketAddress.h>
+#include <folly/io/Cursor.h>
#include <folly/io/IOBuf.h>
-#include <folly/Portability.h>
+#include <folly/io/IOBufQueue.h>
#include <folly/portability/Fcntl.h>
#include <folly/portability/Sockets.h>
#include <folly/portability/SysUio.h>
#include <folly/portability/Unistd.h>
+#include <boost/preprocessor/control/if.hpp>
#include <errno.h>
#include <limits.h>
-#include <thread>
#include <sys/types.h>
-#include <boost/preprocessor/control/if.hpp>
+#include <thread>
using std::string;
using std::unique_ptr;
namespace folly {
+static constexpr bool msgErrQueueSupported =
+#ifdef MSG_ERRQUEUE
+ true;
+#else
+ false;
+#endif // MSG_ERRQUEUE
+
// static members initializers
const AsyncSocket::OptionMap AsyncSocket::emptyOptionMap;
WriteResult performWrite() override {
WriteFlags writeFlags = flags_;
if (getNext() != nullptr) {
- writeFlags = writeFlags | WriteFlags::CORK;
+ writeFlags |= WriteFlags::CORK;
}
auto writeResult = socket_->performWrite(
getOps(), getOpCount(), writeFlags, &opsWritten_, &partialBytes_);
currentOp->iov_len -= partialBytes_;
// Increment the totalBytesWritten_ count by bytesWritten_;
- totalBytesWritten_ += bytesWritten_;
+ assert(bytesWritten_ >= 0);
+ totalBytesWritten_ += uint32_t(bytesWritten_);
}
private:
struct iovec writeOps_[]; ///< write operation(s) list
};
+int AsyncSocket::SendMsgParamsCallback::getDefaultFlags(folly::WriteFlags flags)
+ noexcept {
+ int msg_flags = MSG_DONTWAIT;
+
+#ifdef MSG_NOSIGNAL // Linux-only
+ msg_flags |= MSG_NOSIGNAL;
+#ifdef MSG_MORE
+ if (isSet(flags, WriteFlags::CORK)) {
+ // MSG_MORE tells the kernel we have more data to send, so wait for us to
+ // give it the rest of the data rather than immediately sending a partial
+ // frame, even when TCP_NODELAY is enabled.
+ msg_flags |= MSG_MORE;
+ }
+#endif // MSG_MORE
+#endif // MSG_NOSIGNAL
+ if (isSet(flags, WriteFlags::EOR)) {
+ // marks that this is the last byte of a record (response)
+ msg_flags |= MSG_EOR;
+ }
+
+ return msg_flags;
+}
+
+namespace {
+static AsyncSocket::SendMsgParamsCallback defaultSendMsgParamsCallback;
+}
+
AsyncSocket::AsyncSocket()
: eventBase_(nullptr),
writeTimeout_(this, nullptr),
state_ = StateEnum::ESTABLISHED;
}
+AsyncSocket::AsyncSocket(AsyncSocket::UniquePtr oldAsyncSocket)
+ : AsyncSocket(oldAsyncSocket->getEventBase(), oldAsyncSocket->detachFd()) {
+ preReceivedData_ = std::move(oldAsyncSocket->preReceivedData_);
+}
+
// init() method, since constructor forwarding isn't supported in most
// compilers yet.
void AsyncSocket::init() {
- assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
+ if (eventBase_) {
+ eventBase_->dcheckIsInEventBaseThread();
+ }
shutdownFlags_ = 0;
state_ = StateEnum::UNINIT;
eventFlags_ = EventHandler::NONE;
sendTimeout_ = 0;
maxReadsPerEvent_ = 16;
connectCallback_ = nullptr;
+ errMessageCallback_ = nullptr;
readCallback_ = nullptr;
writeReqHead_ = nullptr;
writeReqTail_ = nullptr;
shutdownSocketSet_ = nullptr;
appBytesWritten_ = 0;
appBytesReceived_ = 0;
+ sendMsgParamCallback_ = &defaultSendMsgParamsCallback;
}
AsyncSocket::~AsyncSocket() {
const OptionMap &options,
const folly::SocketAddress& bindAddr) noexcept {
DestructorGuard dg(this);
- assert(eventBase_->isInEventBaseThread());
+ eventBase_->dcheckIsInEventBaseThread();
addr_ = address;
// The read callback may not have been set yet, and no writes may be pending
// yet, so we don't have to register for any events at the moment.
VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
+ assert(errMessageCallback_ == nullptr);
assert(readCallback_ == nullptr);
assert(writeReqHead_ == nullptr);
if (state_ != StateEnum::FAST_OPEN) {
}
int AsyncSocket::socketConnect(const struct sockaddr* saddr, socklen_t len) {
+#if __linux__
+ if (noTransparentTls_) {
+ // Ignore return value, errors are ok
+ setsockopt(fd_, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0);
+ }
+ if (noTSocks_) {
+ VLOG(4) << "Disabling TSOCKS for fd " << fd_;
+ // Ignore return value, errors are ok
+ setsockopt(fd_, SOL_SOCKET, SO_NO_TSOCKS, nullptr, 0);
+ }
+#endif
int rv = fsp::connect(fd_, saddr, len);
if (rv < 0) {
auto errnoCopy = errno;
void AsyncSocket::scheduleConnectTimeout() {
// Connection in progress.
- int timeout = connectTimeout_.count();
+ auto timeout = connectTimeout_.count();
if (timeout > 0) {
// Start a timer in case the connection takes too long.
- if (!writeTimeout_.scheduleTimeout(timeout)) {
+ if (!writeTimeout_.scheduleTimeout(uint32_t(timeout))) {
throw AsyncSocketException(
AsyncSocketException::INTERNAL_ERROR,
withAddr("failed to schedule AsyncSocket connect timeout"));
void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
sendTimeout_ = milliseconds;
- assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
+ if (eventBase_) {
+ eventBase_->dcheckIsInEventBaseThread();
+ }
// If we are currently pending on write requests, immediately update
// writeTimeout_ with the new value.
}
}
+void AsyncSocket::setErrMessageCB(ErrMessageCallback* callback) {
+ VLOG(6) << "AsyncSocket::setErrMessageCB() this=" << this
+ << ", fd=" << fd_ << ", callback=" << callback
+ << ", state=" << state_;
+
+ // Short circuit if callback is the same as the existing errMessageCallback_.
+ if (callback == errMessageCallback_) {
+ return;
+ }
+
+ if (!msgErrQueueSupported) {
+ // Per-socket error message queue is not supported on this platform.
+ return invalidState(callback);
+ }
+
+ DestructorGuard dg(this);
+ eventBase_->dcheckIsInEventBaseThread();
+
+ if (callback == nullptr) {
+ // We should be able to reset the callback regardless of the
+ // socket state. It's important to have a reliable callback
+ // cancellation mechanism.
+ errMessageCallback_ = callback;
+ return;
+ }
+
+ switch ((StateEnum)state_) {
+ case StateEnum::CONNECTING:
+ case StateEnum::FAST_OPEN:
+ case StateEnum::ESTABLISHED: {
+ errMessageCallback_ = callback;
+ return;
+ }
+ case StateEnum::CLOSED:
+ case StateEnum::ERROR:
+ // We should never reach here. SHUT_READ should always be set
+ // if we are in STATE_CLOSED or STATE_ERROR.
+ assert(false);
+ return invalidState(callback);
+ case StateEnum::UNINIT:
+ // We do not allow setReadCallback() to be called before we start
+ // connecting.
+ return invalidState(callback);
+ }
+
+ // We don't put a default case in the switch statement, so that the compiler
+ // will warn us to update the switch statement if a new state is added.
+ return invalidState(callback);
+}
+
+AsyncSocket::ErrMessageCallback* AsyncSocket::getErrMessageCallback() const {
+ return errMessageCallback_;
+}
+
+void AsyncSocket::setSendMsgParamCB(SendMsgParamsCallback* callback) {
+ sendMsgParamCallback_ = callback;
+}
+
+AsyncSocket::SendMsgParamsCallback* AsyncSocket::getSendMsgParamsCB() const {
+ return sendMsgParamCallback_;
+}
+
void AsyncSocket::setReadCB(ReadCallback *callback) {
VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
<< ", callback=" << callback << ", state=" << state_;
}
DestructorGuard dg(this);
- assert(eventBase_->isInEventBaseThread());
+ eventBase_->dcheckIsInEventBaseThread();
switch ((StateEnum)state_) {
case StateEnum::CONNECTING:
size_t count = buf->countChainElements();
if (count <= kSmallSizeMax) {
// suppress "warning: variable length array 'vec' is used [-Wvla]"
- FOLLY_PUSH_WARNING;
- FOLLY_GCC_DISABLE_WARNING(vla);
+ FOLLY_PUSH_WARNING
+ FOLLY_GCC_DISABLE_WARNING("-Wvla")
iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA, count, kSmallSizeMax)];
- FOLLY_POP_WARNING;
+ FOLLY_POP_WARNING
writeChainImpl(callback, vec, count, std::move(buf), flags);
} else {
<< ", state=" << state_;
DestructorGuard dg(this);
unique_ptr<IOBuf>ioBuf(std::move(buf));
- assert(eventBase_->isInEventBaseThread());
+ eventBase_->dcheckIsInEventBaseThread();
if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
// No new writes may be performed after the write side of the socket has
uint32_t countWritten = 0;
uint32_t partialWritten = 0;
- int bytesWritten = 0;
+ ssize_t bytesWritten = 0;
bool mustRegister = false;
if ((state_ == StateEnum::ESTABLISHED || state_ == StateEnum::FAST_OPEN) &&
!connecting()) {
assert(writeReqTail_ == nullptr);
assert((eventFlags_ & EventHandler::WRITE) == 0);
- auto writeResult =
- performWrite(vec, count, flags, &countWritten, &partialWritten);
+ auto writeResult = performWrite(
+ vec, uint32_t(count), flags, &countWritten, &partialWritten);
bytesWritten = writeResult.writeReturn;
if (bytesWritten < 0) {
auto errnoCopy = errno;
// Create a new WriteRequest to add to the queue
WriteRequest* req;
try {
- req = BytesWriteRequest::newRequest(this, callback, vec + countWritten,
- count - countWritten, partialWritten,
- bytesWritten, std::move(ioBuf), flags);
+ req = BytesWriteRequest::newRequest(
+ this,
+ callback,
+ vec + countWritten,
+ uint32_t(count - countWritten),
+ partialWritten,
+ uint32_t(bytesWritten),
+ std::move(ioBuf),
+ flags);
} catch (const std::exception& ex) {
// we mainly expect to catch std::bad_alloc here
AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
withAddr(string("failed to append new WriteRequest: ") + ex.what()));
- return failWrite(__func__, callback, bytesWritten, tex);
+ return failWrite(__func__, callback, size_t(bytesWritten), tex);
}
req->consume();
if (writeReqTail_ == nullptr) {
// Declare a DestructorGuard to ensure that the AsyncSocket cannot be
// destroyed until close() returns.
DestructorGuard dg(this);
- assert(eventBase_->isInEventBaseThread());
+ eventBase_->dcheckIsInEventBaseThread();
// Since there are write requests pending, we have to set the
// SHUT_WRITE_PENDING flag, and wait to perform the real close until the
<< ", state=" << state_ << ", shutdownFlags="
<< std::hex << (int) shutdownFlags_;
DestructorGuard dg(this);
- assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
+ if (eventBase_) {
+ eventBase_->dcheckIsInEventBaseThread();
+ }
switch (state_) {
case StateEnum::ESTABLISHED:
return;
}
- assert(eventBase_->isInEventBaseThread());
+ eventBase_->dcheckIsInEventBaseThread();
// There are pending writes. Set SHUT_WRITE_PENDING so that the actual
// shutdown will be performed once all writes complete.
}
DestructorGuard dg(this);
- assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
+ if (eventBase_) {
+ eventBase_->dcheckIsInEventBaseThread();
+ }
switch (static_cast<StateEnum>(state_)) {
case StateEnum::ESTABLISHED:
return rc == 1;
}
+bool AsyncSocket::writable() const {
+ if (fd_ == -1) {
+ return false;
+ }
+ struct pollfd fds[1];
+ fds[0].fd = fd_;
+ fds[0].events = POLLOUT;
+ fds[0].revents = 0;
+ int rc = poll(fds, 1, 0);
+ return rc == 1;
+}
+
bool AsyncSocket::isPending() const {
return ioHandler_.isPending();
}
<< ", state=" << state_ << ", events="
<< std::hex << eventFlags_ << ")";
assert(eventBase_ == nullptr);
- assert(eventBase->isInEventBaseThread());
+ eventBase->dcheckIsInEventBaseThread();
eventBase_ = eventBase;
ioHandler_.attachEventBase(eventBase);
writeTimeout_.attachEventBase(eventBase);
+ if (evbChangeCb_) {
+ evbChangeCb_->evbAttached(this);
+ }
}
void AsyncSocket::detachEventBase() {
<< ", old evb=" << eventBase_ << ", state=" << state_
<< ", events=" << std::hex << eventFlags_ << ")";
assert(eventBase_ != nullptr);
- assert(eventBase_->isInEventBaseThread());
+ eventBase_->dcheckIsInEventBaseThread();
eventBase_ = nullptr;
ioHandler_.detachEventBase();
writeTimeout_.detachEventBase();
+ if (evbChangeCb_) {
+ evbChangeCb_->evbDetached(this);
+ }
}
bool AsyncSocket::isDetachable() const {
DCHECK(eventBase_ != nullptr);
- DCHECK(eventBase_->isInEventBaseThread());
+ eventBase_->dcheckIsInEventBaseThread();
return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
}
-void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
+void AsyncSocket::cacheAddresses() {
+ if (fd_ >= 0) {
+ try {
+ cacheLocalAddress();
+ cachePeerAddress();
+ } catch (const std::system_error& e) {
+ if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
+ VLOG(1) << "Error caching addresses: " << e.code().value() << ", "
+ << e.code().message();
+ }
+ }
+ }
+}
+
+void AsyncSocket::cacheLocalAddress() const {
if (!localAddr_.isInitialized()) {
localAddr_.setFromLocalAddress(fd_);
}
- *address = localAddr_;
}
-void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
+void AsyncSocket::cachePeerAddress() const {
if (!addr_.isInitialized()) {
addr_.setFromPeerAddress(fd_);
}
+}
+
+void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
+ cacheLocalAddress();
+ *address = localAddr_;
+}
+
+void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
+ cachePeerAddress();
*address = addr_;
}
}
- if (setsockopt(fd_, IPPROTO_TCP, TCP_CONGESTION, cname.c_str(),
- cname.length() + 1) != 0) {
+ if (setsockopt(
+ fd_,
+ IPPROTO_TCP,
+ TCP_CONGESTION,
+ cname.c_str(),
+ socklen_t(cname.length() + 1)) != 0) {
int errnoCopy = errno;
VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
<< this << "(fd=" << fd_ << ", state=" << state_ << "): "
}
int AsyncSocket::setQuickAck(bool quickack) {
+ (void)quickack;
if (fd_ < 0) {
VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
<< this << "(state=" << state_ << ")";
}
void AsyncSocket::ioReady(uint16_t events) noexcept {
- VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd" << fd_
+ VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd=" << fd_
<< ", events=" << std::hex << events << ", state=" << state_;
DestructorGuard dg(this);
assert(events & EventHandler::READ_WRITE);
- assert(eventBase_->isInEventBaseThread());
+ eventBase_->dcheckIsInEventBaseThread();
+
+ uint16_t relevantEvents = uint16_t(events & EventHandler::READ_WRITE);
+ EventBase* originalEventBase = eventBase_;
+ // If we got there it means that either EventHandler::READ or
+ // EventHandler::WRITE is set. Any of these flags can
+ // indicate that there are messages available in the socket
+ // error message queue.
+ handleErrMessages();
+
+ // Return now if handleErrMessages() detached us from our EventBase
+ if (eventBase_ != originalEventBase) {
+ return;
+ }
- uint16_t relevantEvents = events & EventHandler::READ_WRITE;
if (relevantEvents == EventHandler::READ) {
handleRead();
} else if (relevantEvents == EventHandler::WRITE) {
handleWrite();
} else if (relevantEvents == EventHandler::READ_WRITE) {
- EventBase* originalEventBase = eventBase_;
// If both read and write events are ready, process writes first.
handleWrite();
VLOG(5) << "AsyncSocket::performRead() this=" << this << ", buf=" << *buf
<< ", buflen=" << *buflen;
- int recvFlags = 0;
- if (peek_) {
- recvFlags |= MSG_PEEK;
+ if (preReceivedData_ && !preReceivedData_->empty()) {
+ VLOG(5) << "AsyncSocket::performRead() this=" << this
+ << ", reading pre-received data";
+
+ io::Cursor cursor(preReceivedData_.get());
+ auto len = cursor.pullAtMost(*buf, *buflen);
+
+ IOBufQueue queue;
+ queue.append(std::move(preReceivedData_));
+ queue.trimStart(len);
+ preReceivedData_ = queue.move();
+
+ appBytesReceived_ += len;
+ return ReadResult(len);
}
- ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT | recvFlags);
+ ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT);
if (bytes < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// No more data to read right now.
readCallback_->getReadBuffer(buf, buflen);
}
+void AsyncSocket::handleErrMessages() noexcept {
+ // This method has non-empty implementation only for platforms
+ // supporting per-socket error queues.
+ VLOG(5) << "AsyncSocket::handleErrMessages() this=" << this << ", fd=" << fd_
+ << ", state=" << state_;
+ if (errMessageCallback_ == nullptr) {
+ VLOG(7) << "AsyncSocket::handleErrMessages(): "
+ << "no callback installed - exiting.";
+ return;
+ }
+
+#ifdef MSG_ERRQUEUE
+ uint8_t ctrl[1024];
+ unsigned char data;
+ struct msghdr msg;
+ iovec entry;
+
+ entry.iov_base = &data;
+ entry.iov_len = sizeof(data);
+ msg.msg_iov = &entry;
+ msg.msg_iovlen = 1;
+ msg.msg_name = nullptr;
+ msg.msg_namelen = 0;
+ msg.msg_control = ctrl;
+ msg.msg_controllen = sizeof(ctrl);
+ msg.msg_flags = 0;
+
+ int ret;
+ while (true) {
+ ret = recvmsg(fd_, &msg, MSG_ERRQUEUE);
+ VLOG(5) << "AsyncSocket::handleErrMessages(): recvmsg returned " << ret;
+
+ if (ret < 0) {
+ if (errno != EAGAIN) {
+ auto errnoCopy = errno;
+ LOG(ERROR) << "::recvmsg exited with code " << ret
+ << ", errno: " << errnoCopy;
+ AsyncSocketException ex(
+ AsyncSocketException::INTERNAL_ERROR,
+ withAddr("recvmsg() failed"),
+ errnoCopy);
+ failErrMessageRead(__func__, ex);
+ }
+ return;
+ }
+
+ for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
+ cmsg != nullptr &&
+ cmsg->cmsg_len != 0 &&
+ errMessageCallback_ != nullptr;
+ cmsg = CMSG_NXTHDR(&msg, cmsg)) {
+ errMessageCallback_->errMessage(*cmsg);
+ }
+ }
+#endif //MSG_ERRQUEUE
+}
+
void AsyncSocket::handleRead() noexcept {
VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
<< ", state=" << state_;
<< bytesRead << " bytes";
if (bytesRead > 0) {
if (!isBufferMovable_) {
- readCallback_->readDataAvailable(bytesRead);
+ readCallback_->readDataAvailable(size_t(bytesRead));
} else {
CHECK(kOpenSslModeMoveBufferOwnership);
VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
// be a pessimism. In most cases it probably wouldn't be readable, and we
// would just waste an extra system call. Even if it is readable, waiting to
// find out from libevent on the next event loop doesn't seem that bad.
+ //
+ // The exception to this is if we have pre-received data. In that case there
+ // is definitely data available immediately.
+ if (preReceivedData_ && !preReceivedData_->empty()) {
+ handleRead();
+ }
}
void AsyncSocket::handleInitialReadWrite() noexcept {
VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
<< "state=" << state_ << ", events=" << std::hex << eventFlags_;
DestructorGuard dg(this);
- assert(eventBase_->isInEventBaseThread());
+ eventBase_->dcheckIsInEventBaseThread();
if (state_ == StateEnum::CONNECTING) {
// connect() timed out
// Unregister for I/O events.
if (connectCallback_) {
AsyncSocketException ex(
- AsyncSocketException::TIMED_OUT, "connect timed out");
+ AsyncSocketException::TIMED_OUT,
+ folly::sformat(
+ "connect timed out after {}ms", connectTimeout_.count()));
failConnect(__func__, ex);
} else {
// we faced a connect error without a connect callback, which could
}
} else {
// a normal write operation timed out
- AsyncSocketException ex(AsyncSocketException::TIMED_OUT, "write timed out");
+ AsyncSocketException ex(
+ AsyncSocketException::TIMED_OUT,
+ folly::sformat("write timed out after {}ms", sendTimeout_));
failWrite(__func__, ex);
}
}
registerForConnectEvents();
} catch (const AsyncSocketException& ex) {
return WriteResult(
- WRITE_ERROR, folly::make_unique<AsyncSocketException>(ex));
+ WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
}
// Let's fake it that no bytes were written and return an errno.
errno = EAGAIN;
totalWritten = -1;
} catch (const AsyncSocketException& ex) {
return WriteResult(
- WRITE_ERROR, folly::make_unique<AsyncSocketException>(ex));
+ WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
}
} else if (errno == EAGAIN) {
// Normally sendmsg would indicate that the write would block.
// instead, and is an error condition indicating no fds available.
return WriteResult(
WRITE_ERROR,
- folly::make_unique<AsyncSocketException>(
+ std::make_unique<AsyncSocketException>(
AsyncSocketException::UNKNOWN, "No more free local ports"));
}
} else {
msg.msg_namelen = 0;
msg.msg_iov = const_cast<iovec *>(vec);
msg.msg_iovlen = std::min<size_t>(count, kIovMax);
- msg.msg_control = nullptr;
- msg.msg_controllen = 0;
msg.msg_flags = 0;
+ msg.msg_controllen = sendMsgParamCallback_->getAncillaryDataSize(flags);
+ CHECK_GE(AsyncSocket::SendMsgParamsCallback::maxAncillaryDataSize,
+ msg.msg_controllen);
- int msg_flags = MSG_DONTWAIT;
-
-#ifdef MSG_NOSIGNAL // Linux-only
- msg_flags |= MSG_NOSIGNAL;
- if (isSet(flags, WriteFlags::CORK)) {
- // MSG_MORE tells the kernel we have more data to send, so wait for us to
- // give it the rest of the data rather than immediately sending a partial
- // frame, even when TCP_NODELAY is enabled.
- msg_flags |= MSG_MORE;
- }
-#endif
- if (isSet(flags, WriteFlags::EOR)) {
- // marks that this is the last byte of a record (response)
- msg_flags |= MSG_EOR;
+ if (msg.msg_controllen != 0) {
+ msg.msg_control = reinterpret_cast<char*>(alloca(msg.msg_controllen));
+ sendMsgParamCallback_->getAncillaryData(flags, msg.msg_control);
+ } else {
+ msg.msg_control = nullptr;
}
+ int msg_flags = sendMsgParamCallback_->getFlags(flags);
+
auto writeResult = sendSocketMessage(fd_, &msg, msg_flags);
auto totalWritten = writeResult.writeReturn;
if (totalWritten < 0) {
uint32_t bytesWritten;
uint32_t n;
- for (bytesWritten = totalWritten, n = 0; n < count; ++n) {
+ for (bytesWritten = uint32_t(totalWritten), n = 0; n < count; ++n) {
const iovec* v = vec + n;
if (v->iov_len > bytesWritten) {
// Partial write finished in the middle of this iovec
return WriteResult(totalWritten);
}
- bytesWritten -= v->iov_len;
+ bytesWritten -= uint32_t(v->iov_len);
}
assert(bytesWritten == 0);
* and call all currently installed callbacks. After an error, the
* AsyncSocket is completely unregistered.
*
- * @return Returns true on succcess, or false on error.
+ * @return Returns true on success, or false on error.
*/
bool AsyncSocket::updateEventRegistration() {
VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
<< ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
<< ", events=" << std::hex << eventFlags_;
- assert(eventBase_->isInEventBaseThread());
+ eventBase_->dcheckIsInEventBaseThread();
if (eventFlags_ == EventHandler::NONE) {
ioHandler_.unregisterHandler();
return true;
// Always register for persistent events, so we don't have to re-register
// after being called back.
- if (!ioHandler_.registerHandler(eventFlags_ | EventHandler::PERSIST)) {
+ if (!ioHandler_.registerHandler(
+ uint16_t(eventFlags_ | EventHandler::PERSIST))) {
eventFlags_ = EventHandler::NONE; // we're not registered after error
AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
withAddr("failed to update AsyncSocket event registration"));
finishFail();
}
+void AsyncSocket::failErrMessageRead(const char* fn,
+ const AsyncSocketException& ex) {
+ VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
+ << state_ << " host=" << addr_.describe()
+ << "): failed while reading message in " << fn << "(): "
+ << ex.what();
+ startFail();
+
+ if (errMessageCallback_ != nullptr) {
+ ErrMessageCallback* callback = errMessageCallback_;
+ errMessageCallback_ = nullptr;
+ callback->errMessageError(ex);
+ }
+
+ finishFail();
+}
+
void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
<< state_ << " host=" << addr_.describe()
void AsyncSocket::invalidState(ConnectCallback* callback) {
VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
- << "): connect() called in invalid state " << state_;
+ << "): connect() called in invalid state " << state_;
/*
* The invalidState() methods don't use the normal failure mechanisms,
}
}
+void AsyncSocket::invalidState(ErrMessageCallback* callback) {
+ VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
+ << "): setErrMessageCB(" << callback
+ << ") called in invalid state " << state_;
+
+ AsyncSocketException ex(
+ AsyncSocketException::NOT_OPEN,
+ msgErrQueueSupported
+ ? "setErrMessageCB() called with socket in invalid state"
+ : "This platform does not support socket error message notifications");
+ if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
+ if (callback) {
+ callback->errMessageError(ex);
+ }
+ } else {
+ startFail();
+ if (callback) {
+ callback->errMessageError(ex);
+ }
+ finishFail();
+ }
+}
+
void AsyncSocket::invokeConnectErr(const AsyncSocketException& ex) {
connectEndTime_ = std::chrono::steady_clock::now();
if (connectCallback_) {
bufferCallback_ = cb;
}
-} // folly
+} // namespace folly