2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/io/async/AsyncSocket.h>
19 #include <folly/ExceptionWrapper.h>
20 #include <folly/Format.h>
21 #include <folly/Portability.h>
22 #include <folly/SocketAddress.h>
23 #include <folly/io/Cursor.h>
24 #include <folly/io/IOBuf.h>
25 #include <folly/io/IOBufQueue.h>
26 #include <folly/portability/Fcntl.h>
27 #include <folly/portability/Sockets.h>
28 #include <folly/portability/SysUio.h>
29 #include <folly/portability/Unistd.h>
31 #include <boost/preprocessor/control/if.hpp>
34 #include <sys/types.h>
38 using std::unique_ptr;
40 namespace fsp = folly::portability::sockets;
44 static constexpr bool msgErrQueueSupported =
49 #endif // MSG_ERRQUEUE
51 // static members initializers
52 const AsyncSocket::OptionMap AsyncSocket::emptyOptionMap;
54 const AsyncSocketException socketClosedLocallyEx(
55 AsyncSocketException::END_OF_FILE, "socket closed locally");
56 const AsyncSocketException socketShutdownForWritesEx(
57 AsyncSocketException::END_OF_FILE, "socket shutdown for writes");
59 // TODO: It might help performance to provide a version of BytesWriteRequest that
60 // users could derive from, so we can avoid the extra allocation for each call
61 // to write()/writev(). We could templatize TFramedAsyncChannel just like the
62 // protocols are currently templatized for transports.
64 // We would need the version for external users where they provide the iovec
65 // storage space, and only our internal version would allocate it at the end of
68 /* The default WriteRequest implementation, used for write(), writev() and
71 * A new BytesWriteRequest operation is allocated on the heap for all write
72 * operations that cannot be completed immediately.
74 class AsyncSocket::BytesWriteRequest : public AsyncSocket::WriteRequest {
76 static BytesWriteRequest* newRequest(AsyncSocket* socket,
77 WriteCallback* callback,
80 uint32_t partialWritten,
81 uint32_t bytesWritten,
82 unique_ptr<IOBuf>&& ioBuf,
85 // Since we put a variable size iovec array at the end
86 // of each BytesWriteRequest, we have to manually allocate the memory.
87 void* buf = malloc(sizeof(BytesWriteRequest) +
88 (opCount * sizeof(struct iovec)));
90 throw std::bad_alloc();
93 return new(buf) BytesWriteRequest(socket, callback, ops, opCount,
94 partialWritten, bytesWritten,
95 std::move(ioBuf), flags);
98 void destroy() override {
99 this->~BytesWriteRequest();
103 WriteResult performWrite() override {
104 WriteFlags writeFlags = flags_;
105 if (getNext() != nullptr) {
106 writeFlags |= WriteFlags::CORK;
109 socket_->adjustZeroCopyFlags(getOps(), getOpCount(), writeFlags);
111 auto writeResult = socket_->performWrite(
112 getOps(), getOpCount(), writeFlags, &opsWritten_, &partialBytes_);
113 bytesWritten_ = writeResult.writeReturn > 0 ? writeResult.writeReturn : 0;
115 if (socket_->isZeroCopyRequest(writeFlags)) {
117 socket_->addZeroCopyBuf(std::move(ioBuf_));
119 socket_->addZeroCopyBuf(ioBuf_.get());
122 // this happens if at least one of the prev requests were sent
123 // with zero copy but not the last one
124 if (isComplete() && socket_->getZeroCopy() &&
125 socket_->containsZeroCopyBuf(ioBuf_.get())) {
126 socket_->setZeroCopyBuf(std::move(ioBuf_));
133 bool isComplete() override {
134 return opsWritten_ == getOpCount();
137 void consume() override {
138 // Advance opIndex_ forward by opsWritten_
139 opIndex_ += opsWritten_;
140 assert(opIndex_ < opCount_);
142 if (!socket_->isZeroCopyRequest(flags_)) {
143 // If we've finished writing any IOBufs, release them
145 for (uint32_t i = opsWritten_; i != 0; --i) {
147 ioBuf_ = ioBuf_->pop();
152 // Move partialBytes_ forward into the current iovec buffer
153 struct iovec* currentOp = writeOps_ + opIndex_;
154 assert((partialBytes_ < currentOp->iov_len) || (currentOp->iov_len == 0));
155 currentOp->iov_base =
156 reinterpret_cast<uint8_t*>(currentOp->iov_base) + partialBytes_;
157 currentOp->iov_len -= partialBytes_;
159 // Increment the totalBytesWritten_ count by bytesWritten_;
160 assert(bytesWritten_ >= 0);
161 totalBytesWritten_ += uint32_t(bytesWritten_);
165 BytesWriteRequest(AsyncSocket* socket,
166 WriteCallback* callback,
167 const struct iovec* ops,
169 uint32_t partialBytes,
170 uint32_t bytesWritten,
171 unique_ptr<IOBuf>&& ioBuf,
173 : AsyncSocket::WriteRequest(socket, callback)
177 , ioBuf_(std::move(ioBuf))
179 , partialBytes_(partialBytes)
180 , bytesWritten_(bytesWritten) {
181 memcpy(writeOps_, ops, sizeof(*ops) * opCount_);
184 // private destructor, to ensure callers use destroy()
185 ~BytesWriteRequest() override = default;
187 const struct iovec* getOps() const {
188 assert(opCount_ > opIndex_);
189 return writeOps_ + opIndex_;
192 uint32_t getOpCount() const {
193 assert(opCount_ > opIndex_);
194 return opCount_ - opIndex_;
197 uint32_t opCount_; ///< number of entries in writeOps_
198 uint32_t opIndex_; ///< current index into writeOps_
199 WriteFlags flags_; ///< set for WriteFlags
200 unique_ptr<IOBuf> ioBuf_; ///< underlying IOBuf, or nullptr if N/A
202 // for consume(), how much we wrote on the last write
203 uint32_t opsWritten_; ///< complete ops written
204 uint32_t partialBytes_; ///< partial bytes of incomplete op written
205 ssize_t bytesWritten_; ///< bytes written altogether
207 struct iovec writeOps_[]; ///< write operation(s) list
210 int AsyncSocket::SendMsgParamsCallback::getDefaultFlags(
211 folly::WriteFlags flags,
212 bool zeroCopyEnabled) noexcept {
213 int msg_flags = MSG_DONTWAIT;
215 #ifdef MSG_NOSIGNAL // Linux-only
216 msg_flags |= MSG_NOSIGNAL;
218 if (isSet(flags, WriteFlags::CORK)) {
219 // MSG_MORE tells the kernel we have more data to send, so wait for us to
220 // give it the rest of the data rather than immediately sending a partial
221 // frame, even when TCP_NODELAY is enabled.
222 msg_flags |= MSG_MORE;
225 #endif // MSG_NOSIGNAL
226 if (isSet(flags, WriteFlags::EOR)) {
227 // marks that this is the last byte of a record (response)
228 msg_flags |= MSG_EOR;
231 if (zeroCopyEnabled && isSet(flags, WriteFlags::WRITE_MSG_ZEROCOPY)) {
232 msg_flags |= MSG_ZEROCOPY;
239 static AsyncSocket::SendMsgParamsCallback defaultSendMsgParamsCallback;
242 AsyncSocket::AsyncSocket()
243 : eventBase_(nullptr),
244 writeTimeout_(this, nullptr),
245 ioHandler_(this, nullptr),
246 immediateReadHandler_(this) {
247 VLOG(5) << "new AsyncSocket()";
251 AsyncSocket::AsyncSocket(EventBase* evb)
253 writeTimeout_(this, evb),
254 ioHandler_(this, evb),
255 immediateReadHandler_(this) {
256 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
260 AsyncSocket::AsyncSocket(EventBase* evb,
261 const folly::SocketAddress& address,
262 uint32_t connectTimeout)
264 connect(nullptr, address, connectTimeout);
267 AsyncSocket::AsyncSocket(EventBase* evb,
268 const std::string& ip,
270 uint32_t connectTimeout)
272 connect(nullptr, ip, port, connectTimeout);
275 AsyncSocket::AsyncSocket(EventBase* evb, int fd)
277 writeTimeout_(this, evb),
278 ioHandler_(this, evb, fd),
279 immediateReadHandler_(this) {
280 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ", fd="
285 state_ = StateEnum::ESTABLISHED;
288 AsyncSocket::AsyncSocket(AsyncSocket::UniquePtr oldAsyncSocket)
289 : AsyncSocket(oldAsyncSocket->getEventBase(), oldAsyncSocket->detachFd()) {
290 preReceivedData_ = std::move(oldAsyncSocket->preReceivedData_);
293 // init() method, since constructor forwarding isn't supported in most
295 void AsyncSocket::init() {
297 eventBase_->dcheckIsInEventBaseThread();
300 state_ = StateEnum::UNINIT;
301 eventFlags_ = EventHandler::NONE;
304 maxReadsPerEvent_ = 16;
305 connectCallback_ = nullptr;
306 errMessageCallback_ = nullptr;
307 readCallback_ = nullptr;
308 writeReqHead_ = nullptr;
309 writeReqTail_ = nullptr;
310 wShutdownSocketSet_.reset();
311 appBytesWritten_ = 0;
312 appBytesReceived_ = 0;
313 sendMsgParamCallback_ = &defaultSendMsgParamsCallback;
316 AsyncSocket::~AsyncSocket() {
317 VLOG(7) << "actual destruction of AsyncSocket(this=" << this
318 << ", evb=" << eventBase_ << ", fd=" << fd_
319 << ", state=" << state_ << ")";
322 void AsyncSocket::destroy() {
323 VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
324 << ", fd=" << fd_ << ", state=" << state_;
325 // When destroy is called, close the socket immediately
328 // Then call DelayedDestruction::destroy() to take care of
329 // whether or not we need immediate or delayed destruction
330 DelayedDestruction::destroy();
333 int AsyncSocket::detachFd() {
334 VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
335 << ", evb=" << eventBase_ << ", state=" << state_
336 << ", events=" << std::hex << eventFlags_ << ")";
337 // Extract the fd, and set fd_ to -1 first, so closeNow() won't
338 // actually close the descriptor.
339 if (const auto socketSet = wShutdownSocketSet_.lock()) {
340 socketSet->remove(fd_);
344 // Call closeNow() to invoke all pending callbacks with an error.
346 // Update the EventHandler to stop using this fd.
347 // This can only be done after closeNow() unregisters the handler.
348 ioHandler_.changeHandlerFD(-1);
352 const folly::SocketAddress& AsyncSocket::anyAddress() {
353 static const folly::SocketAddress anyAddress =
354 folly::SocketAddress("0.0.0.0", 0);
358 void AsyncSocket::setShutdownSocketSet(
359 const std::weak_ptr<ShutdownSocketSet>& wNewSS) {
360 const auto newSS = wNewSS.lock();
361 const auto shutdownSocketSet = wShutdownSocketSet_.lock();
363 if (newSS == shutdownSocketSet) {
367 if (shutdownSocketSet && fd_ != -1) {
368 shutdownSocketSet->remove(fd_);
371 if (newSS && fd_ != -1) {
375 wShutdownSocketSet_ = wNewSS;
378 void AsyncSocket::setCloseOnExec() {
379 int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
381 auto errnoCopy = errno;
382 throw AsyncSocketException(
383 AsyncSocketException::INTERNAL_ERROR,
384 withAddr("failed to set close-on-exec flag"),
389 void AsyncSocket::connect(ConnectCallback* callback,
390 const folly::SocketAddress& address,
392 const OptionMap &options,
393 const folly::SocketAddress& bindAddr) noexcept {
394 DestructorGuard dg(this);
395 eventBase_->dcheckIsInEventBaseThread();
399 // Make sure we're in the uninitialized state
400 if (state_ != StateEnum::UNINIT) {
401 return invalidState(callback);
404 connectTimeout_ = std::chrono::milliseconds(timeout);
405 connectStartTime_ = std::chrono::steady_clock::now();
406 // Make connect end time at least >= connectStartTime.
407 connectEndTime_ = connectStartTime_;
410 state_ = StateEnum::CONNECTING;
411 connectCallback_ = callback;
413 sockaddr_storage addrStorage;
414 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
418 // Technically the first parameter should actually be a protocol family
419 // constant (PF_xxx) rather than an address family (AF_xxx), but the
420 // distinction is mainly just historical. In pretty much all
421 // implementations the PF_foo and AF_foo constants are identical.
422 fd_ = fsp::socket(address.getFamily(), SOCK_STREAM, 0);
424 auto errnoCopy = errno;
425 throw AsyncSocketException(
426 AsyncSocketException::INTERNAL_ERROR,
427 withAddr("failed to create socket"),
430 if (const auto shutdownSocketSet = wShutdownSocketSet_.lock()) {
431 shutdownSocketSet->add(fd_);
433 ioHandler_.changeHandlerFD(fd_);
437 // Put the socket in non-blocking mode
438 int flags = fcntl(fd_, F_GETFL, 0);
440 auto errnoCopy = errno;
441 throw AsyncSocketException(
442 AsyncSocketException::INTERNAL_ERROR,
443 withAddr("failed to get socket flags"),
446 int rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
448 auto errnoCopy = errno;
449 throw AsyncSocketException(
450 AsyncSocketException::INTERNAL_ERROR,
451 withAddr("failed to put socket in non-blocking mode"),
455 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
456 // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
457 rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
459 auto errnoCopy = errno;
460 throw AsyncSocketException(
461 AsyncSocketException::INTERNAL_ERROR,
462 "failed to enable F_SETNOSIGPIPE on socket",
467 // By default, turn on TCP_NODELAY
468 // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
469 // setNoDelay() will log an error message if it fails.
470 // Also set the cached zeroCopyVal_ since it cannot be set earlier if the fd
472 if (address.getFamily() != AF_UNIX) {
473 (void)setNoDelay(true);
474 setZeroCopy(zeroCopyVal_);
477 VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
478 << ", fd=" << fd_ << ", host=" << address.describe().c_str();
481 if (bindAddr != anyAddress()) {
483 if (setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
484 auto errnoCopy = errno;
486 throw AsyncSocketException(
487 AsyncSocketException::NOT_OPEN,
488 "failed to setsockopt prior to bind on " + bindAddr.describe(),
492 bindAddr.getAddress(&addrStorage);
494 if (bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
495 auto errnoCopy = errno;
497 throw AsyncSocketException(
498 AsyncSocketException::NOT_OPEN,
499 "failed to bind to async socket: " + bindAddr.describe(),
504 // Apply the additional options if any.
505 for (const auto& opt: options) {
506 rv = opt.first.apply(fd_, opt.second);
508 auto errnoCopy = errno;
509 throw AsyncSocketException(
510 AsyncSocketException::INTERNAL_ERROR,
511 withAddr("failed to set socket option"),
516 // Perform the connect()
517 address.getAddress(&addrStorage);
520 state_ = StateEnum::FAST_OPEN;
521 tfoAttempted_ = true;
523 if (socketConnect(saddr, addr_.getActualSize()) < 0) {
528 // If we're still here the connect() succeeded immediately.
529 // Fall through to call the callback outside of this try...catch block
530 } catch (const AsyncSocketException& ex) {
531 return failConnect(__func__, ex);
532 } catch (const std::exception& ex) {
533 // shouldn't happen, but handle it just in case
534 VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
535 << "): unexpected " << typeid(ex).name() << " exception: "
537 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
538 withAddr(string("unexpected exception: ") +
540 return failConnect(__func__, tex);
543 // The connection succeeded immediately
544 // The read callback may not have been set yet, and no writes may be pending
545 // yet, so we don't have to register for any events at the moment.
546 VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
547 assert(errMessageCallback_ == nullptr);
548 assert(readCallback_ == nullptr);
549 assert(writeReqHead_ == nullptr);
550 if (state_ != StateEnum::FAST_OPEN) {
551 state_ = StateEnum::ESTABLISHED;
553 invokeConnectSuccess();
556 int AsyncSocket::socketConnect(const struct sockaddr* saddr, socklen_t len) {
558 if (noTransparentTls_) {
559 // Ignore return value, errors are ok
560 setsockopt(fd_, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0);
563 VLOG(4) << "Disabling TSOCKS for fd " << fd_;
564 // Ignore return value, errors are ok
565 setsockopt(fd_, SOL_SOCKET, SO_NO_TSOCKS, nullptr, 0);
568 int rv = fsp::connect(fd_, saddr, len);
570 auto errnoCopy = errno;
571 if (errnoCopy == EINPROGRESS) {
572 scheduleConnectTimeout();
573 registerForConnectEvents();
575 throw AsyncSocketException(
576 AsyncSocketException::NOT_OPEN,
577 "connect failed (immediately)",
584 void AsyncSocket::scheduleConnectTimeout() {
585 // Connection in progress.
586 auto timeout = connectTimeout_.count();
588 // Start a timer in case the connection takes too long.
589 if (!writeTimeout_.scheduleTimeout(uint32_t(timeout))) {
590 throw AsyncSocketException(
591 AsyncSocketException::INTERNAL_ERROR,
592 withAddr("failed to schedule AsyncSocket connect timeout"));
597 void AsyncSocket::registerForConnectEvents() {
598 // Register for write events, so we'll
599 // be notified when the connection finishes/fails.
600 // Note that we don't register for a persistent event here.
601 assert(eventFlags_ == EventHandler::NONE);
602 eventFlags_ = EventHandler::WRITE;
603 if (!ioHandler_.registerHandler(eventFlags_)) {
604 throw AsyncSocketException(
605 AsyncSocketException::INTERNAL_ERROR,
606 withAddr("failed to register AsyncSocket connect handler"));
610 void AsyncSocket::connect(ConnectCallback* callback,
611 const string& ip, uint16_t port,
613 const OptionMap &options) noexcept {
614 DestructorGuard dg(this);
616 connectCallback_ = callback;
617 connect(callback, folly::SocketAddress(ip, port), timeout, options);
618 } catch (const std::exception& ex) {
619 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
621 return failConnect(__func__, tex);
625 void AsyncSocket::cancelConnect() {
626 connectCallback_ = nullptr;
627 if (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN) {
632 void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
633 sendTimeout_ = milliseconds;
635 eventBase_->dcheckIsInEventBaseThread();
638 // If we are currently pending on write requests, immediately update
639 // writeTimeout_ with the new value.
640 if ((eventFlags_ & EventHandler::WRITE) &&
641 (state_ != StateEnum::CONNECTING && state_ != StateEnum::FAST_OPEN)) {
642 assert(state_ == StateEnum::ESTABLISHED);
643 assert((shutdownFlags_ & SHUT_WRITE) == 0);
644 if (sendTimeout_ > 0) {
645 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
646 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
647 withAddr("failed to reschedule send timeout in setSendTimeout"));
648 return failWrite(__func__, ex);
651 writeTimeout_.cancelTimeout();
656 void AsyncSocket::setErrMessageCB(ErrMessageCallback* callback) {
657 VLOG(6) << "AsyncSocket::setErrMessageCB() this=" << this
658 << ", fd=" << fd_ << ", callback=" << callback
659 << ", state=" << state_;
661 // Short circuit if callback is the same as the existing errMessageCallback_.
662 if (callback == errMessageCallback_) {
666 if (!msgErrQueueSupported) {
667 // Per-socket error message queue is not supported on this platform.
668 return invalidState(callback);
671 DestructorGuard dg(this);
672 eventBase_->dcheckIsInEventBaseThread();
674 if (callback == nullptr) {
675 // We should be able to reset the callback regardless of the
676 // socket state. It's important to have a reliable callback
677 // cancellation mechanism.
678 errMessageCallback_ = callback;
682 switch ((StateEnum)state_) {
683 case StateEnum::CONNECTING:
684 case StateEnum::FAST_OPEN:
685 case StateEnum::ESTABLISHED: {
686 errMessageCallback_ = callback;
689 case StateEnum::CLOSED:
690 case StateEnum::ERROR:
691 // We should never reach here. SHUT_READ should always be set
692 // if we are in STATE_CLOSED or STATE_ERROR.
694 return invalidState(callback);
695 case StateEnum::UNINIT:
696 // We do not allow setReadCallback() to be called before we start
698 return invalidState(callback);
701 // We don't put a default case in the switch statement, so that the compiler
702 // will warn us to update the switch statement if a new state is added.
703 return invalidState(callback);
706 AsyncSocket::ErrMessageCallback* AsyncSocket::getErrMessageCallback() const {
707 return errMessageCallback_;
710 void AsyncSocket::setSendMsgParamCB(SendMsgParamsCallback* callback) {
711 sendMsgParamCallback_ = callback;
714 AsyncSocket::SendMsgParamsCallback* AsyncSocket::getSendMsgParamsCB() const {
715 return sendMsgParamCallback_;
718 void AsyncSocket::setReadCB(ReadCallback *callback) {
719 VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
720 << ", callback=" << callback << ", state=" << state_;
722 // Short circuit if callback is the same as the existing readCallback_.
724 // Note that this is needed for proper functioning during some cleanup cases.
725 // During cleanup we allow setReadCallback(nullptr) to be called even if the
726 // read callback is already unset and we have been detached from an event
727 // base. This check prevents us from asserting
728 // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
729 if (callback == readCallback_) {
733 /* We are removing a read callback */
734 if (callback == nullptr &&
735 immediateReadHandler_.isLoopCallbackScheduled()) {
736 immediateReadHandler_.cancelLoopCallback();
739 if (shutdownFlags_ & SHUT_READ) {
740 // Reads have already been shut down on this socket.
742 // Allow setReadCallback(nullptr) to be called in this case, but don't
743 // allow a new callback to be set.
745 // For example, setReadCallback(nullptr) can happen after an error if we
746 // invoke some other error callback before invoking readError(). The other
747 // error callback that is invoked first may go ahead and clear the read
748 // callback before we get a chance to invoke readError().
749 if (callback != nullptr) {
750 return invalidState(callback);
752 assert((eventFlags_ & EventHandler::READ) == 0);
753 readCallback_ = nullptr;
757 DestructorGuard dg(this);
758 eventBase_->dcheckIsInEventBaseThread();
760 switch ((StateEnum)state_) {
761 case StateEnum::CONNECTING:
762 case StateEnum::FAST_OPEN:
763 // For convenience, we allow the read callback to be set while we are
764 // still connecting. We just store the callback for now. Once the
765 // connection completes we'll register for read events.
766 readCallback_ = callback;
768 case StateEnum::ESTABLISHED:
770 readCallback_ = callback;
771 uint16_t oldFlags = eventFlags_;
773 eventFlags_ |= EventHandler::READ;
775 eventFlags_ &= ~EventHandler::READ;
778 // Update our registration if our flags have changed
779 if (eventFlags_ != oldFlags) {
780 // We intentionally ignore the return value here.
781 // updateEventRegistration() will move us into the error state if it
782 // fails, and we don't need to do anything else here afterwards.
783 (void)updateEventRegistration();
787 checkForImmediateRead();
791 case StateEnum::CLOSED:
792 case StateEnum::ERROR:
793 // We should never reach here. SHUT_READ should always be set
794 // if we are in STATE_CLOSED or STATE_ERROR.
796 return invalidState(callback);
797 case StateEnum::UNINIT:
798 // We do not allow setReadCallback() to be called before we start
800 return invalidState(callback);
803 // We don't put a default case in the switch statement, so that the compiler
804 // will warn us to update the switch statement if a new state is added.
805 return invalidState(callback);
808 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
809 return readCallback_;
812 bool AsyncSocket::setZeroCopy(bool enable) {
813 if (msgErrQueueSupported) {
814 zeroCopyVal_ = enable;
820 int val = enable ? 1 : 0;
821 int ret = setsockopt(fd_, SOL_SOCKET, SO_ZEROCOPY, &val, sizeof(val));
823 // if enable == false, set zeroCopyEnabled_ = false regardless
824 // if SO_ZEROCOPY is set or not
826 zeroCopyEnabled_ = enable;
830 /* if the setsockopt failed, try to see if the socket inherited the flag
831 * since we cannot set SO_ZEROCOPY on a socket s = accept
835 socklen_t optlen = sizeof(val);
836 ret = getsockopt(fd_, SOL_SOCKET, SO_ZEROCOPY, &val, &optlen);
839 enable = val ? true : false;
844 zeroCopyEnabled_ = enable;
853 void AsyncSocket::setZeroCopyWriteChainThreshold(size_t threshold) {
854 zeroCopyWriteChainThreshold_ = threshold;
857 bool AsyncSocket::isZeroCopyRequest(WriteFlags flags) {
858 return (zeroCopyEnabled_ && isSet(flags, WriteFlags::WRITE_MSG_ZEROCOPY));
861 void AsyncSocket::adjustZeroCopyFlags(
863 folly::WriteFlags& flags) {
864 if (zeroCopyEnabled_ && zeroCopyWriteChainThreshold_ && buf &&
866 if (buf->computeChainDataLength() >= zeroCopyWriteChainThreshold_) {
867 flags |= folly::WriteFlags::WRITE_MSG_ZEROCOPY;
869 flags = unSet(flags, folly::WriteFlags::WRITE_MSG_ZEROCOPY);
874 void AsyncSocket::adjustZeroCopyFlags(
877 folly::WriteFlags& flags) {
878 if (zeroCopyEnabled_ && zeroCopyWriteChainThreshold_) {
879 count = std::min<uint32_t>(count, kIovMax);
881 for (uint32_t i = 0; i < count; ++i) {
882 const iovec* v = vec + i;
886 if (sum >= zeroCopyWriteChainThreshold_) {
887 flags |= folly::WriteFlags::WRITE_MSG_ZEROCOPY;
889 flags = unSet(flags, folly::WriteFlags::WRITE_MSG_ZEROCOPY);
894 void AsyncSocket::addZeroCopyBuf(std::unique_ptr<folly::IOBuf>&& buf) {
895 uint32_t id = getNextZeroCopyBuffId();
896 folly::IOBuf* ptr = buf.get();
898 idZeroCopyBufPtrMap_[id] = ptr;
899 auto& p = idZeroCopyBufInfoMap_[ptr];
901 CHECK(p.buf_.get() == nullptr);
902 p.buf_ = std::move(buf);
905 void AsyncSocket::addZeroCopyBuf(folly::IOBuf* ptr) {
906 uint32_t id = getNextZeroCopyBuffId();
907 idZeroCopyBufPtrMap_[id] = ptr;
909 idZeroCopyBufInfoMap_[ptr].count_++;
912 void AsyncSocket::releaseZeroCopyBuf(uint32_t id) {
913 auto iter = idZeroCopyBufPtrMap_.find(id);
914 CHECK(iter != idZeroCopyBufPtrMap_.end());
915 auto ptr = iter->second;
916 auto iter1 = idZeroCopyBufInfoMap_.find(ptr);
917 CHECK(iter1 != idZeroCopyBufInfoMap_.end());
918 if (0 == --iter1->second.count_) {
919 idZeroCopyBufInfoMap_.erase(iter1);
923 void AsyncSocket::setZeroCopyBuf(std::unique_ptr<folly::IOBuf>&& buf) {
924 folly::IOBuf* ptr = buf.get();
925 auto& p = idZeroCopyBufInfoMap_[ptr];
926 CHECK(p.buf_.get() == nullptr);
928 p.buf_ = std::move(buf);
931 bool AsyncSocket::containsZeroCopyBuf(folly::IOBuf* ptr) {
932 return (idZeroCopyBufInfoMap_.find(ptr) != idZeroCopyBufInfoMap_.end());
935 bool AsyncSocket::isZeroCopyMsg(const cmsghdr& cmsg) const {
937 if (zeroCopyEnabled_ &&
938 ((cmsg.cmsg_level == SOL_IP && cmsg.cmsg_type == IP_RECVERR) ||
939 (cmsg.cmsg_level == SOL_IPV6 && cmsg.cmsg_type == IPV6_RECVERR))) {
940 const struct sock_extended_err* serr =
941 reinterpret_cast<const struct sock_extended_err*>(CMSG_DATA(&cmsg));
943 (serr->ee_errno == 0) && (serr->ee_origin == SO_EE_ORIGIN_ZEROCOPY));
949 void AsyncSocket::processZeroCopyMsg(const cmsghdr& cmsg) {
951 const struct sock_extended_err* serr =
952 reinterpret_cast<const struct sock_extended_err*>(CMSG_DATA(&cmsg));
953 uint32_t hi = serr->ee_data;
954 uint32_t lo = serr->ee_info;
955 // disable zero copy if the buffer was actually copied
956 if ((serr->ee_code & SO_EE_CODE_ZEROCOPY_COPIED) && zeroCopyEnabled_) {
957 VLOG(2) << "AsyncSocket::processZeroCopyMsg(): setting "
958 << "zeroCopyEnabled_ = false due to SO_EE_CODE_ZEROCOPY_COPIED "
960 zeroCopyEnabled_ = false;
963 for (uint32_t i = lo; i <= hi; i++) {
964 releaseZeroCopyBuf(i);
969 void AsyncSocket::write(WriteCallback* callback,
970 const void* buf, size_t bytes, WriteFlags flags) {
972 op.iov_base = const_cast<void*>(buf);
974 writeImpl(callback, &op, 1, unique_ptr<IOBuf>(), flags);
977 void AsyncSocket::writev(WriteCallback* callback,
981 writeImpl(callback, vec, count, unique_ptr<IOBuf>(), flags);
984 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
986 adjustZeroCopyFlags(buf.get(), flags);
988 constexpr size_t kSmallSizeMax = 64;
989 size_t count = buf->countChainElements();
990 if (count <= kSmallSizeMax) {
991 // suppress "warning: variable length array 'vec' is used [-Wvla]"
993 FOLLY_GCC_DISABLE_WARNING("-Wvla")
994 iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA, count, kSmallSizeMax)];
997 writeChainImpl(callback, vec, count, std::move(buf), flags);
999 iovec* vec = new iovec[count];
1000 writeChainImpl(callback, vec, count, std::move(buf), flags);
1005 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
1006 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
1007 size_t veclen = buf->fillIov(vec, count);
1008 writeImpl(callback, vec, veclen, std::move(buf), flags);
1011 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
1012 size_t count, unique_ptr<IOBuf>&& buf,
1014 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
1015 << ", callback=" << callback << ", count=" << count
1016 << ", state=" << state_;
1017 DestructorGuard dg(this);
1018 unique_ptr<IOBuf>ioBuf(std::move(buf));
1019 eventBase_->dcheckIsInEventBaseThread();
1021 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
1022 // No new writes may be performed after the write side of the socket has
1025 // We could just call callback->writeError() here to fail just this write.
1026 // However, fail hard and use invalidState() to fail all outstanding
1027 // callbacks and move the socket into the error state. There's most likely
1028 // a bug in the caller's code, so we abort everything rather than trying to
1029 // proceed as best we can.
1030 return invalidState(callback);
1033 uint32_t countWritten = 0;
1034 uint32_t partialWritten = 0;
1035 ssize_t bytesWritten = 0;
1036 bool mustRegister = false;
1037 if ((state_ == StateEnum::ESTABLISHED || state_ == StateEnum::FAST_OPEN) &&
1039 if (writeReqHead_ == nullptr) {
1040 // If we are established and there are no other writes pending,
1041 // we can attempt to perform the write immediately.
1042 assert(writeReqTail_ == nullptr);
1043 assert((eventFlags_ & EventHandler::WRITE) == 0);
1045 auto writeResult = performWrite(
1046 vec, uint32_t(count), flags, &countWritten, &partialWritten);
1047 bytesWritten = writeResult.writeReturn;
1048 if (bytesWritten < 0) {
1049 auto errnoCopy = errno;
1050 if (writeResult.exception) {
1051 return failWrite(__func__, callback, 0, *writeResult.exception);
1053 AsyncSocketException ex(
1054 AsyncSocketException::INTERNAL_ERROR,
1055 withAddr("writev failed"),
1057 return failWrite(__func__, callback, 0, ex);
1058 } else if (countWritten == count) {
1059 // done, add the whole buffer
1060 if (isZeroCopyRequest(flags)) {
1061 addZeroCopyBuf(std::move(ioBuf));
1063 // We successfully wrote everything.
1064 // Invoke the callback and return.
1066 callback->writeSuccess();
1069 } else { // continue writing the next writeReq
1071 if (isZeroCopyRequest(flags)) {
1072 addZeroCopyBuf(ioBuf.get());
1074 if (bufferCallback_) {
1075 bufferCallback_->onEgressBuffered();
1078 if (!connecting()) {
1079 // Writes might put the socket back into connecting state
1080 // if TFO is enabled, and using TFO fails.
1081 // This means that write timeouts would not be active, however
1082 // connect timeouts would affect this stage.
1083 mustRegister = true;
1086 } else if (!connecting()) {
1087 // Invalid state for writing
1088 return invalidState(callback);
1091 // Create a new WriteRequest to add to the queue
1094 req = BytesWriteRequest::newRequest(
1098 uint32_t(count - countWritten),
1100 uint32_t(bytesWritten),
1103 } catch (const std::exception& ex) {
1104 // we mainly expect to catch std::bad_alloc here
1105 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
1106 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
1107 return failWrite(__func__, callback, size_t(bytesWritten), tex);
1110 if (writeReqTail_ == nullptr) {
1111 assert(writeReqHead_ == nullptr);
1112 writeReqHead_ = writeReqTail_ = req;
1114 writeReqTail_->append(req);
1115 writeReqTail_ = req;
1118 // Register for write events if are established and not currently
1119 // waiting on write events
1121 assert(state_ == StateEnum::ESTABLISHED);
1122 assert((eventFlags_ & EventHandler::WRITE) == 0);
1123 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1124 assert(state_ == StateEnum::ERROR);
1127 if (sendTimeout_ > 0) {
1128 // Schedule a timeout to fire if the write takes too long.
1129 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1130 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1131 withAddr("failed to schedule send timeout"));
1132 return failWrite(__func__, ex);
1138 void AsyncSocket::writeRequest(WriteRequest* req) {
1139 if (writeReqTail_ == nullptr) {
1140 assert(writeReqHead_ == nullptr);
1141 writeReqHead_ = writeReqTail_ = req;
1144 writeReqTail_->append(req);
1145 writeReqTail_ = req;
1149 void AsyncSocket::close() {
1150 VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
1151 << ", state=" << state_ << ", shutdownFlags="
1152 << std::hex << (int) shutdownFlags_;
1154 // close() is only different from closeNow() when there are pending writes
1155 // that need to drain before we can close. In all other cases, just call
1158 // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
1159 // STATE_ERROR if close() is invoked while a previous closeNow() or failure
1160 // is still running. (e.g., If there are multiple pending writes, and we
1161 // call writeError() on the first one, it may call close(). In this case we
1162 // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
1163 // writes will still be in the queue.)
1165 // We only need to drain pending writes if we are still in STATE_CONNECTING
1166 // or STATE_ESTABLISHED
1167 if ((writeReqHead_ == nullptr) ||
1168 !(state_ == StateEnum::CONNECTING ||
1169 state_ == StateEnum::ESTABLISHED)) {
1174 // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
1175 // destroyed until close() returns.
1176 DestructorGuard dg(this);
1177 eventBase_->dcheckIsInEventBaseThread();
1179 // Since there are write requests pending, we have to set the
1180 // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
1181 // connect finishes and we finish writing these requests.
1183 // Set SHUT_READ to indicate that reads are shut down, and set the
1184 // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
1185 // pending writes complete.
1186 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
1188 // If a read callback is set, invoke readEOF() immediately to inform it that
1189 // the socket has been closed and no more data can be read.
1190 if (readCallback_) {
1191 // Disable reads if they are enabled
1192 if (!updateEventRegistration(0, EventHandler::READ)) {
1193 // We're now in the error state; callbacks have been cleaned up
1194 assert(state_ == StateEnum::ERROR);
1195 assert(readCallback_ == nullptr);
1197 ReadCallback* callback = readCallback_;
1198 readCallback_ = nullptr;
1199 callback->readEOF();
1204 void AsyncSocket::closeNow() {
1205 VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
1206 << ", state=" << state_ << ", shutdownFlags="
1207 << std::hex << (int) shutdownFlags_;
1208 DestructorGuard dg(this);
1210 eventBase_->dcheckIsInEventBaseThread();
1214 case StateEnum::ESTABLISHED:
1215 case StateEnum::CONNECTING:
1216 case StateEnum::FAST_OPEN: {
1217 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1218 state_ = StateEnum::CLOSED;
1220 // If the write timeout was set, cancel it.
1221 writeTimeout_.cancelTimeout();
1223 // If we are registered for I/O events, unregister.
1224 if (eventFlags_ != EventHandler::NONE) {
1225 eventFlags_ = EventHandler::NONE;
1226 if (!updateEventRegistration()) {
1227 // We will have been moved into the error state.
1228 assert(state_ == StateEnum::ERROR);
1233 if (immediateReadHandler_.isLoopCallbackScheduled()) {
1234 immediateReadHandler_.cancelLoopCallback();
1238 ioHandler_.changeHandlerFD(-1);
1242 invokeConnectErr(socketClosedLocallyEx);
1244 failAllWrites(socketClosedLocallyEx);
1246 if (readCallback_) {
1247 ReadCallback* callback = readCallback_;
1248 readCallback_ = nullptr;
1249 callback->readEOF();
1253 case StateEnum::CLOSED:
1254 // Do nothing. It's possible that we are being called recursively
1255 // from inside a callback that we invoked inside another call to close()
1256 // that is still running.
1258 case StateEnum::ERROR:
1259 // Do nothing. The error handling code has performed (or is performing)
1262 case StateEnum::UNINIT:
1263 assert(eventFlags_ == EventHandler::NONE);
1264 assert(connectCallback_ == nullptr);
1265 assert(readCallback_ == nullptr);
1266 assert(writeReqHead_ == nullptr);
1267 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1268 state_ = StateEnum::CLOSED;
1272 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
1273 << ") called in unknown state " << state_;
1276 void AsyncSocket::closeWithReset() {
1277 // Enable SO_LINGER, with the linger timeout set to 0.
1278 // This will trigger a TCP reset when we close the socket.
1280 struct linger optLinger = {1, 0};
1281 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
1282 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
1283 << "on " << fd_ << ": errno=" << errno;
1287 // Then let closeNow() take care of the rest
1291 void AsyncSocket::shutdownWrite() {
1292 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
1293 << ", state=" << state_ << ", shutdownFlags="
1294 << std::hex << (int) shutdownFlags_;
1296 // If there are no pending writes, shutdownWrite() is identical to
1297 // shutdownWriteNow().
1298 if (writeReqHead_ == nullptr) {
1303 eventBase_->dcheckIsInEventBaseThread();
1305 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
1306 // shutdown will be performed once all writes complete.
1307 shutdownFlags_ |= SHUT_WRITE_PENDING;
1310 void AsyncSocket::shutdownWriteNow() {
1311 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
1312 << ", fd=" << fd_ << ", state=" << state_
1313 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
1315 if (shutdownFlags_ & SHUT_WRITE) {
1316 // Writes are already shutdown; nothing else to do.
1320 // If SHUT_READ is already set, just call closeNow() to completely
1321 // close the socket. This can happen if close() was called with writes
1322 // pending, and then shutdownWriteNow() is called before all pending writes
1324 if (shutdownFlags_ & SHUT_READ) {
1329 DestructorGuard dg(this);
1331 eventBase_->dcheckIsInEventBaseThread();
1334 switch (static_cast<StateEnum>(state_)) {
1335 case StateEnum::ESTABLISHED:
1337 shutdownFlags_ |= SHUT_WRITE;
1339 // If the write timeout was set, cancel it.
1340 writeTimeout_.cancelTimeout();
1342 // If we are registered for write events, unregister.
1343 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1344 // We will have been moved into the error state.
1345 assert(state_ == StateEnum::ERROR);
1349 // Shutdown writes on the file descriptor
1350 shutdown(fd_, SHUT_WR);
1352 // Immediately fail all write requests
1353 failAllWrites(socketShutdownForWritesEx);
1356 case StateEnum::CONNECTING:
1358 // Set the SHUT_WRITE_PENDING flag.
1359 // When the connection completes, it will check this flag,
1360 // shutdown the write half of the socket, and then set SHUT_WRITE.
1361 shutdownFlags_ |= SHUT_WRITE_PENDING;
1363 // Immediately fail all write requests
1364 failAllWrites(socketShutdownForWritesEx);
1367 case StateEnum::UNINIT:
1368 // Callers normally shouldn't call shutdownWriteNow() before the socket
1369 // even starts connecting. Nonetheless, go ahead and set
1370 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
1371 // immediately shut down the write side of the socket.
1372 shutdownFlags_ |= SHUT_WRITE_PENDING;
1374 case StateEnum::FAST_OPEN:
1375 // In fast open state we haven't call connected yet, and if we shutdown
1376 // the writes, we will never try to call connect, so shut everything down
1377 shutdownFlags_ |= SHUT_WRITE;
1378 // Immediately fail all write requests
1379 failAllWrites(socketShutdownForWritesEx);
1381 case StateEnum::CLOSED:
1382 case StateEnum::ERROR:
1383 // We should never get here. SHUT_WRITE should always be set
1384 // in STATE_CLOSED and STATE_ERROR.
1385 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
1386 << ", fd=" << fd_ << ") in unexpected state " << state_
1387 << " with SHUT_WRITE not set ("
1388 << std::hex << (int) shutdownFlags_ << ")";
1393 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
1394 << fd_ << ") called in unknown state " << state_;
1397 bool AsyncSocket::readable() const {
1401 struct pollfd fds[1];
1403 fds[0].events = POLLIN;
1405 int rc = poll(fds, 1, 0);
1409 bool AsyncSocket::writable() const {
1413 struct pollfd fds[1];
1415 fds[0].events = POLLOUT;
1417 int rc = poll(fds, 1, 0);
1421 bool AsyncSocket::isPending() const {
1422 return ioHandler_.isPending();
1425 bool AsyncSocket::hangup() const {
1427 // sanity check, no one should ask for hangup if we are not connected.
1431 #ifdef POLLRDHUP // Linux-only
1432 struct pollfd fds[1];
1434 fds[0].events = POLLRDHUP|POLLHUP;
1437 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1443 bool AsyncSocket::good() const {
1445 (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN ||
1446 state_ == StateEnum::ESTABLISHED) &&
1447 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1450 bool AsyncSocket::error() const {
1451 return (state_ == StateEnum::ERROR);
1454 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1455 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1456 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1457 << ", state=" << state_ << ", events="
1458 << std::hex << eventFlags_ << ")";
1459 assert(eventBase_ == nullptr);
1460 eventBase->dcheckIsInEventBaseThread();
1462 eventBase_ = eventBase;
1463 ioHandler_.attachEventBase(eventBase);
1464 writeTimeout_.attachEventBase(eventBase);
1466 evbChangeCb_->evbAttached(this);
1470 void AsyncSocket::detachEventBase() {
1471 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1472 << ", old evb=" << eventBase_ << ", state=" << state_
1473 << ", events=" << std::hex << eventFlags_ << ")";
1474 assert(eventBase_ != nullptr);
1475 eventBase_->dcheckIsInEventBaseThread();
1477 eventBase_ = nullptr;
1478 ioHandler_.detachEventBase();
1479 writeTimeout_.detachEventBase();
1481 evbChangeCb_->evbDetached(this);
1485 bool AsyncSocket::isDetachable() const {
1486 DCHECK(eventBase_ != nullptr);
1487 eventBase_->dcheckIsInEventBaseThread();
1489 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1492 void AsyncSocket::cacheAddresses() {
1495 cacheLocalAddress();
1497 } catch (const std::system_error& e) {
1498 if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
1499 VLOG(1) << "Error caching addresses: " << e.code().value() << ", "
1500 << e.code().message();
1506 void AsyncSocket::cacheLocalAddress() const {
1507 if (!localAddr_.isInitialized()) {
1508 localAddr_.setFromLocalAddress(fd_);
1512 void AsyncSocket::cachePeerAddress() const {
1513 if (!addr_.isInitialized()) {
1514 addr_.setFromPeerAddress(fd_);
1518 bool AsyncSocket::isZeroCopyWriteInProgress() const noexcept {
1519 eventBase_->dcheckIsInEventBaseThread();
1520 return (!idZeroCopyBufPtrMap_.empty());
1523 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1524 cacheLocalAddress();
1525 *address = localAddr_;
1528 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1533 bool AsyncSocket::getTFOSucceded() const {
1534 return detail::tfo_succeeded(fd_);
1537 int AsyncSocket::setNoDelay(bool noDelay) {
1539 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1540 << this << "(state=" << state_ << ")";
1545 int value = noDelay ? 1 : 0;
1546 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1547 int errnoCopy = errno;
1548 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1549 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1550 << strerror(errnoCopy);
1557 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1559 #ifndef TCP_CONGESTION
1560 #define TCP_CONGESTION 13
1564 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1565 << "socket " << this << "(state=" << state_ << ")";
1575 socklen_t(cname.length() + 1)) != 0) {
1576 int errnoCopy = errno;
1577 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1578 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1579 << strerror(errnoCopy);
1586 int AsyncSocket::setQuickAck(bool quickack) {
1589 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1590 << this << "(state=" << state_ << ")";
1595 #ifdef TCP_QUICKACK // Linux-only
1596 int value = quickack ? 1 : 0;
1597 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1598 int errnoCopy = errno;
1599 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1600 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1601 << strerror(errnoCopy);
1611 int AsyncSocket::setSendBufSize(size_t bufsize) {
1613 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1614 << this << "(state=" << state_ << ")";
1618 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1619 int errnoCopy = errno;
1620 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1621 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1622 << strerror(errnoCopy);
1629 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1631 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1632 << this << "(state=" << state_ << ")";
1636 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1637 int errnoCopy = errno;
1638 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1639 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1640 << strerror(errnoCopy);
1647 int AsyncSocket::setTCPProfile(int profd) {
1649 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1650 << this << "(state=" << state_ << ")";
1654 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1655 int errnoCopy = errno;
1656 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1657 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1658 << strerror(errnoCopy);
1665 void AsyncSocket::ioReady(uint16_t events) noexcept {
1666 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd=" << fd_
1667 << ", events=" << std::hex << events << ", state=" << state_;
1668 DestructorGuard dg(this);
1669 assert(events & EventHandler::READ_WRITE);
1670 eventBase_->dcheckIsInEventBaseThread();
1672 uint16_t relevantEvents = uint16_t(events & EventHandler::READ_WRITE);
1673 EventBase* originalEventBase = eventBase_;
1674 // If we got there it means that either EventHandler::READ or
1675 // EventHandler::WRITE is set. Any of these flags can
1676 // indicate that there are messages available in the socket
1677 // error message queue.
1678 handleErrMessages();
1680 // Return now if handleErrMessages() detached us from our EventBase
1681 if (eventBase_ != originalEventBase) {
1685 if (relevantEvents == EventHandler::READ) {
1687 } else if (relevantEvents == EventHandler::WRITE) {
1689 } else if (relevantEvents == EventHandler::READ_WRITE) {
1690 // If both read and write events are ready, process writes first.
1693 // Return now if handleWrite() detached us from our EventBase
1694 if (eventBase_ != originalEventBase) {
1698 // Only call handleRead() if a read callback is still installed.
1699 // (It's possible that the read callback was uninstalled during
1701 if (readCallback_) {
1705 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1706 << std::hex << events << "(this=" << this << ")";
1711 AsyncSocket::ReadResult
1712 AsyncSocket::performRead(void** buf, size_t* buflen, size_t* /* offset */) {
1713 VLOG(5) << "AsyncSocket::performRead() this=" << this << ", buf=" << *buf
1714 << ", buflen=" << *buflen;
1716 if (preReceivedData_ && !preReceivedData_->empty()) {
1717 VLOG(5) << "AsyncSocket::performRead() this=" << this
1718 << ", reading pre-received data";
1720 io::Cursor cursor(preReceivedData_.get());
1721 auto len = cursor.pullAtMost(*buf, *buflen);
1724 queue.append(std::move(preReceivedData_));
1725 queue.trimStart(len);
1726 preReceivedData_ = queue.move();
1728 appBytesReceived_ += len;
1729 return ReadResult(len);
1732 ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT);
1734 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1735 // No more data to read right now.
1736 return ReadResult(READ_BLOCKING);
1738 return ReadResult(READ_ERROR);
1741 appBytesReceived_ += bytes;
1742 return ReadResult(bytes);
1746 void AsyncSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1747 // no matter what, buffer should be preapared for non-ssl socket
1748 CHECK(readCallback_);
1749 readCallback_->getReadBuffer(buf, buflen);
1752 void AsyncSocket::handleErrMessages() noexcept {
1753 // This method has non-empty implementation only for platforms
1754 // supporting per-socket error queues.
1755 VLOG(5) << "AsyncSocket::handleErrMessages() this=" << this << ", fd=" << fd_
1756 << ", state=" << state_;
1757 if (errMessageCallback_ == nullptr &&
1758 (!zeroCopyEnabled_ || idZeroCopyBufPtrMap_.empty())) {
1759 VLOG(7) << "AsyncSocket::handleErrMessages(): "
1760 << "no callback installed - exiting.";
1770 entry.iov_base = &data;
1771 entry.iov_len = sizeof(data);
1772 msg.msg_iov = &entry;
1774 msg.msg_name = nullptr;
1775 msg.msg_namelen = 0;
1776 msg.msg_control = ctrl;
1777 msg.msg_controllen = sizeof(ctrl);
1782 ret = recvmsg(fd_, &msg, MSG_ERRQUEUE);
1783 VLOG(5) << "AsyncSocket::handleErrMessages(): recvmsg returned " << ret;
1786 if (errno != EAGAIN) {
1787 auto errnoCopy = errno;
1788 LOG(ERROR) << "::recvmsg exited with code " << ret
1789 << ", errno: " << errnoCopy;
1790 AsyncSocketException ex(
1791 AsyncSocketException::INTERNAL_ERROR,
1792 withAddr("recvmsg() failed"),
1794 failErrMessageRead(__func__, ex);
1799 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
1800 cmsg != nullptr && cmsg->cmsg_len != 0;
1801 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1802 if (isZeroCopyMsg(*cmsg)) {
1803 processZeroCopyMsg(*cmsg);
1805 if (errMessageCallback_) {
1806 errMessageCallback_->errMessage(*cmsg);
1811 #endif //MSG_ERRQUEUE
1814 void AsyncSocket::handleRead() noexcept {
1815 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1816 << ", state=" << state_;
1817 assert(state_ == StateEnum::ESTABLISHED);
1818 assert((shutdownFlags_ & SHUT_READ) == 0);
1819 assert(readCallback_ != nullptr);
1820 assert(eventFlags_ & EventHandler::READ);
1823 // - a read attempt would block
1824 // - readCallback_ is uninstalled
1825 // - the number of loop iterations exceeds the optional maximum
1826 // - this AsyncSocket is moved to another EventBase
1828 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1829 // which is why need to check for it here.
1831 // The last bullet point is slightly subtle. readDataAvailable() may also
1832 // detach this socket from this EventBase. However, before
1833 // readDataAvailable() returns another thread may pick it up, attach it to
1834 // a different EventBase, and install another readCallback_. We need to
1835 // exit immediately after readDataAvailable() returns if the eventBase_ has
1836 // changed. (The caller must perform some sort of locking to transfer the
1837 // AsyncSocket between threads properly. This will be sufficient to ensure
1838 // that this thread sees the updated eventBase_ variable after
1839 // readDataAvailable() returns.)
1840 uint16_t numReads = 0;
1841 EventBase* originalEventBase = eventBase_;
1842 while (readCallback_ && eventBase_ == originalEventBase) {
1843 // Get the buffer to read into.
1844 void* buf = nullptr;
1845 size_t buflen = 0, offset = 0;
1847 prepareReadBuffer(&buf, &buflen);
1848 VLOG(5) << "prepareReadBuffer() buf=" << buf << ", buflen=" << buflen;
1849 } catch (const AsyncSocketException& ex) {
1850 return failRead(__func__, ex);
1851 } catch (const std::exception& ex) {
1852 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1853 string("ReadCallback::getReadBuffer() "
1854 "threw exception: ") +
1856 return failRead(__func__, tex);
1858 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1859 "ReadCallback::getReadBuffer() threw "
1860 "non-exception type");
1861 return failRead(__func__, ex);
1863 if (!isBufferMovable_ && (buf == nullptr || buflen == 0)) {
1864 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1865 "ReadCallback::getReadBuffer() returned "
1867 return failRead(__func__, ex);
1871 auto readResult = performRead(&buf, &buflen, &offset);
1872 auto bytesRead = readResult.readReturn;
1873 VLOG(4) << "this=" << this << ", AsyncSocket::handleRead() got "
1874 << bytesRead << " bytes";
1875 if (bytesRead > 0) {
1876 if (!isBufferMovable_) {
1877 readCallback_->readDataAvailable(size_t(bytesRead));
1879 CHECK(kOpenSslModeMoveBufferOwnership);
1880 VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
1881 << "buf=" << buf << ", " << bytesRead << "/" << buflen
1882 << ", offset=" << offset;
1883 auto readBuf = folly::IOBuf::takeOwnership(buf, buflen);
1884 readBuf->trimStart(offset);
1885 readBuf->trimEnd(buflen - offset - bytesRead);
1886 readCallback_->readBufferAvailable(std::move(readBuf));
1889 // Fall through and continue around the loop if the read
1890 // completely filled the available buffer.
1891 // Note that readCallback_ may have been uninstalled or changed inside
1892 // readDataAvailable().
1893 if (size_t(bytesRead) < buflen) {
1896 } else if (bytesRead == READ_BLOCKING) {
1897 // No more data to read right now.
1899 } else if (bytesRead == READ_ERROR) {
1900 readErr_ = READ_ERROR;
1901 if (readResult.exception) {
1902 return failRead(__func__, *readResult.exception);
1904 auto errnoCopy = errno;
1905 AsyncSocketException ex(
1906 AsyncSocketException::INTERNAL_ERROR,
1907 withAddr("recv() failed"),
1909 return failRead(__func__, ex);
1911 assert(bytesRead == READ_EOF);
1912 readErr_ = READ_EOF;
1914 shutdownFlags_ |= SHUT_READ;
1915 if (!updateEventRegistration(0, EventHandler::READ)) {
1916 // we've already been moved into STATE_ERROR
1917 assert(state_ == StateEnum::ERROR);
1918 assert(readCallback_ == nullptr);
1922 ReadCallback* callback = readCallback_;
1923 readCallback_ = nullptr;
1924 callback->readEOF();
1927 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1928 if (readCallback_ != nullptr) {
1929 // We might still have data in the socket.
1930 // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
1931 scheduleImmediateRead();
1939 * This function attempts to write as much data as possible, until no more data
1942 * - If it sends all available data, it unregisters for write events, and stops
1943 * the writeTimeout_.
1945 * - If not all of the data can be sent immediately, it reschedules
1946 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1947 * registered for write events.
1949 void AsyncSocket::handleWrite() noexcept {
1950 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1951 << ", state=" << state_;
1952 DestructorGuard dg(this);
1954 if (state_ == StateEnum::CONNECTING) {
1960 assert(state_ == StateEnum::ESTABLISHED);
1961 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1962 assert(writeReqHead_ != nullptr);
1964 // Loop until we run out of write requests,
1965 // or until this socket is moved to another EventBase.
1966 // (See the comment in handleRead() explaining how this can happen.)
1967 EventBase* originalEventBase = eventBase_;
1968 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1969 auto writeResult = writeReqHead_->performWrite();
1970 if (writeResult.writeReturn < 0) {
1971 if (writeResult.exception) {
1972 return failWrite(__func__, *writeResult.exception);
1974 auto errnoCopy = errno;
1975 AsyncSocketException ex(
1976 AsyncSocketException::INTERNAL_ERROR,
1977 withAddr("writev() failed"),
1979 return failWrite(__func__, ex);
1980 } else if (writeReqHead_->isComplete()) {
1981 // We finished this request
1982 WriteRequest* req = writeReqHead_;
1983 writeReqHead_ = req->getNext();
1985 if (writeReqHead_ == nullptr) {
1986 writeReqTail_ = nullptr;
1987 // This is the last write request.
1988 // Unregister for write events and cancel the send timer
1989 // before we invoke the callback. We have to update the state properly
1990 // before calling the callback, since it may want to detach us from
1992 if (eventFlags_ & EventHandler::WRITE) {
1993 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1994 assert(state_ == StateEnum::ERROR);
1997 // Stop the send timeout
1998 writeTimeout_.cancelTimeout();
2000 assert(!writeTimeout_.isScheduled());
2002 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
2003 // we finish sending the last write request.
2005 // We have to do this before invoking writeSuccess(), since
2006 // writeSuccess() may detach us from our EventBase.
2007 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
2008 assert(connectCallback_ == nullptr);
2009 shutdownFlags_ |= SHUT_WRITE;
2011 if (shutdownFlags_ & SHUT_READ) {
2012 // Reads have already been shutdown. Fully close the socket and
2013 // move to STATE_CLOSED.
2015 // Note: This code currently moves us to STATE_CLOSED even if
2016 // close() hasn't ever been called. This can occur if we have
2017 // received EOF from the peer and shutdownWrite() has been called
2018 // locally. Should we bother staying in STATE_ESTABLISHED in this
2019 // case, until close() is actually called? I can't think of a
2020 // reason why we would need to do so. No other operations besides
2021 // calling close() or destroying the socket can be performed at
2023 assert(readCallback_ == nullptr);
2024 state_ = StateEnum::CLOSED;
2026 ioHandler_.changeHandlerFD(-1);
2030 // Reads are still enabled, so we are only doing a half-shutdown
2031 shutdown(fd_, SHUT_WR);
2036 // Invoke the callback
2037 WriteCallback* callback = req->getCallback();
2040 callback->writeSuccess();
2042 // We'll continue around the loop, trying to write another request
2045 if (bufferCallback_) {
2046 bufferCallback_->onEgressBuffered();
2048 writeReqHead_->consume();
2049 // Stop after a partial write; it's highly likely that a subsequent write
2050 // attempt will just return EAGAIN.
2052 // Ensure that we are registered for write events.
2053 if ((eventFlags_ & EventHandler::WRITE) == 0) {
2054 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
2055 assert(state_ == StateEnum::ERROR);
2060 // Reschedule the send timeout, since we have made some write progress.
2061 if (sendTimeout_ > 0) {
2062 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
2063 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
2064 withAddr("failed to reschedule write timeout"));
2065 return failWrite(__func__, ex);
2071 if (!writeReqHead_ && bufferCallback_) {
2072 bufferCallback_->onEgressBufferCleared();
2076 void AsyncSocket::checkForImmediateRead() noexcept {
2077 // We currently don't attempt to perform optimistic reads in AsyncSocket.
2078 // (However, note that some subclasses do override this method.)
2080 // Simply calling handleRead() here would be bad, as this would call
2081 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
2082 // buffer even though no data may be available. This would waste lots of
2083 // memory, since the buffer will sit around unused until the socket actually
2084 // becomes readable.
2086 // Checking if the socket is readable now also seems like it would probably
2087 // be a pessimism. In most cases it probably wouldn't be readable, and we
2088 // would just waste an extra system call. Even if it is readable, waiting to
2089 // find out from libevent on the next event loop doesn't seem that bad.
2091 // The exception to this is if we have pre-received data. In that case there
2092 // is definitely data available immediately.
2093 if (preReceivedData_ && !preReceivedData_->empty()) {
2098 void AsyncSocket::handleInitialReadWrite() noexcept {
2099 // Our callers should already be holding a DestructorGuard, but grab
2100 // one here just to make sure, in case one of our calling code paths ever
2102 DestructorGuard dg(this);
2103 // If we have a readCallback_, make sure we enable read events. We
2104 // may already be registered for reads if connectSuccess() set
2105 // the read calback.
2106 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
2107 assert(state_ == StateEnum::ESTABLISHED);
2108 assert((shutdownFlags_ & SHUT_READ) == 0);
2109 if (!updateEventRegistration(EventHandler::READ, 0)) {
2110 assert(state_ == StateEnum::ERROR);
2113 checkForImmediateRead();
2114 } else if (readCallback_ == nullptr) {
2115 // Unregister for read events.
2116 updateEventRegistration(0, EventHandler::READ);
2119 // If we have write requests pending, try to send them immediately.
2120 // Since we just finished accepting, there is a very good chance that we can
2121 // write without blocking.
2123 // However, we only process them if EventHandler::WRITE is not already set,
2124 // which means that we're already blocked on a write attempt. (This can
2125 // happen if connectSuccess() called write() before returning.)
2126 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
2127 // Call handleWrite() to perform write processing.
2129 } else if (writeReqHead_ == nullptr) {
2130 // Unregister for write event.
2131 updateEventRegistration(0, EventHandler::WRITE);
2135 void AsyncSocket::handleConnect() noexcept {
2136 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
2137 << ", state=" << state_;
2138 assert(state_ == StateEnum::CONNECTING);
2139 // SHUT_WRITE can never be set while we are still connecting;
2140 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
2142 assert((shutdownFlags_ & SHUT_WRITE) == 0);
2144 // In case we had a connect timeout, cancel the timeout
2145 writeTimeout_.cancelTimeout();
2146 // We don't use a persistent registration when waiting on a connect event,
2147 // so we have been automatically unregistered now. Update eventFlags_ to
2149 assert(eventFlags_ == EventHandler::WRITE);
2150 eventFlags_ = EventHandler::NONE;
2152 // Call getsockopt() to check if the connect succeeded
2154 socklen_t len = sizeof(error);
2155 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
2157 auto errnoCopy = errno;
2158 AsyncSocketException ex(
2159 AsyncSocketException::INTERNAL_ERROR,
2160 withAddr("error calling getsockopt() after connect"),
2162 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
2163 << fd_ << " host=" << addr_.describe()
2164 << ") exception:" << ex.what();
2165 return failConnect(__func__, ex);
2169 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2170 "connect failed", error);
2171 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
2172 << fd_ << " host=" << addr_.describe()
2173 << ") exception: " << ex.what();
2174 return failConnect(__func__, ex);
2177 // Move into STATE_ESTABLISHED
2178 state_ = StateEnum::ESTABLISHED;
2180 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
2181 // perform, immediately shutdown the write half of the socket.
2182 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
2183 // SHUT_READ shouldn't be set. If close() is called on the socket while we
2184 // are still connecting we just abort the connect rather than waiting for
2186 assert((shutdownFlags_ & SHUT_READ) == 0);
2187 shutdown(fd_, SHUT_WR);
2188 shutdownFlags_ |= SHUT_WRITE;
2191 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
2192 << "successfully connected; state=" << state_;
2194 // Remember the EventBase we are attached to, before we start invoking any
2195 // callbacks (since the callbacks may call detachEventBase()).
2196 EventBase* originalEventBase = eventBase_;
2198 invokeConnectSuccess();
2199 // Note that the connect callback may have changed our state.
2200 // (set or unset the read callback, called write(), closed the socket, etc.)
2201 // The following code needs to handle these situations correctly.
2203 // If the socket has been closed, readCallback_ and writeReqHead_ will
2204 // always be nullptr, so that will prevent us from trying to read or write.
2206 // The main thing to check for is if eventBase_ is still originalEventBase.
2207 // If not, we have been detached from this event base, so we shouldn't
2208 // perform any more operations.
2209 if (eventBase_ != originalEventBase) {
2213 handleInitialReadWrite();
2216 void AsyncSocket::timeoutExpired() noexcept {
2217 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
2218 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
2219 DestructorGuard dg(this);
2220 eventBase_->dcheckIsInEventBaseThread();
2222 if (state_ == StateEnum::CONNECTING) {
2223 // connect() timed out
2224 // Unregister for I/O events.
2225 if (connectCallback_) {
2226 AsyncSocketException ex(
2227 AsyncSocketException::TIMED_OUT,
2229 "connect timed out after {}ms", connectTimeout_.count()));
2230 failConnect(__func__, ex);
2232 // we faced a connect error without a connect callback, which could
2233 // happen due to TFO.
2234 AsyncSocketException ex(
2235 AsyncSocketException::TIMED_OUT, "write timed out during connection");
2236 failWrite(__func__, ex);
2239 // a normal write operation timed out
2240 AsyncSocketException ex(
2241 AsyncSocketException::TIMED_OUT,
2242 folly::sformat("write timed out after {}ms", sendTimeout_));
2243 failWrite(__func__, ex);
2247 ssize_t AsyncSocket::tfoSendMsg(int fd, struct msghdr* msg, int msg_flags) {
2248 return detail::tfo_sendmsg(fd, msg, msg_flags);
2251 AsyncSocket::WriteResult
2252 AsyncSocket::sendSocketMessage(int fd, struct msghdr* msg, int msg_flags) {
2253 ssize_t totalWritten = 0;
2254 if (state_ == StateEnum::FAST_OPEN) {
2255 sockaddr_storage addr;
2256 auto len = addr_.getAddress(&addr);
2257 msg->msg_name = &addr;
2258 msg->msg_namelen = len;
2259 totalWritten = tfoSendMsg(fd_, msg, msg_flags);
2260 if (totalWritten >= 0) {
2261 tfoFinished_ = true;
2262 state_ = StateEnum::ESTABLISHED;
2263 // We schedule this asynchrously so that we don't end up
2264 // invoking initial read or write while a write is in progress.
2265 scheduleInitialReadWrite();
2266 } else if (errno == EINPROGRESS) {
2267 VLOG(4) << "TFO falling back to connecting";
2268 // A normal sendmsg doesn't return EINPROGRESS, however
2269 // TFO might fallback to connecting if there is no
2271 state_ = StateEnum::CONNECTING;
2273 scheduleConnectTimeout();
2274 registerForConnectEvents();
2275 } catch (const AsyncSocketException& ex) {
2277 WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
2279 // Let's fake it that no bytes were written and return an errno.
2282 } else if (errno == EOPNOTSUPP) {
2283 // Try falling back to connecting.
2284 VLOG(4) << "TFO not supported";
2285 state_ = StateEnum::CONNECTING;
2287 int ret = socketConnect((const sockaddr*)&addr, len);
2289 // connect succeeded immediately
2290 // Treat this like no data was written.
2291 state_ = StateEnum::ESTABLISHED;
2292 scheduleInitialReadWrite();
2294 // If there was no exception during connections,
2295 // we would return that no bytes were written.
2298 } catch (const AsyncSocketException& ex) {
2300 WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
2302 } else if (errno == EAGAIN) {
2303 // Normally sendmsg would indicate that the write would block.
2304 // However in the fast open case, it would indicate that sendmsg
2305 // fell back to a connect. This is a return code from connect()
2306 // instead, and is an error condition indicating no fds available.
2309 std::make_unique<AsyncSocketException>(
2310 AsyncSocketException::UNKNOWN, "No more free local ports"));
2313 totalWritten = ::sendmsg(fd, msg, msg_flags);
2315 return WriteResult(totalWritten);
2318 AsyncSocket::WriteResult AsyncSocket::performWrite(
2322 uint32_t* countWritten,
2323 uint32_t* partialWritten) {
2324 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
2325 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
2326 // (since it may terminate the program if the main program doesn't explicitly
2329 msg.msg_name = nullptr;
2330 msg.msg_namelen = 0;
2331 msg.msg_iov = const_cast<iovec *>(vec);
2332 msg.msg_iovlen = std::min<size_t>(count, kIovMax);
2334 msg.msg_controllen = sendMsgParamCallback_->getAncillaryDataSize(flags);
2335 CHECK_GE(AsyncSocket::SendMsgParamsCallback::maxAncillaryDataSize,
2336 msg.msg_controllen);
2338 if (msg.msg_controllen != 0) {
2339 msg.msg_control = reinterpret_cast<char*>(alloca(msg.msg_controllen));
2340 sendMsgParamCallback_->getAncillaryData(flags, msg.msg_control);
2342 msg.msg_control = nullptr;
2344 int msg_flags = sendMsgParamCallback_->getFlags(flags, zeroCopyEnabled_);
2346 auto writeResult = sendSocketMessage(fd_, &msg, msg_flags);
2347 auto totalWritten = writeResult.writeReturn;
2348 if (totalWritten < 0) {
2349 bool tryAgain = (errno == EAGAIN);
2351 // Apple has a bug where doing a second write on a socket which we
2352 // have opened with TFO causes an ENOTCONN to be thrown. However the
2353 // socket is really connected, so treat ENOTCONN as a EAGAIN until
2354 // this bug is fixed.
2355 tryAgain |= (errno == ENOTCONN);
2357 if (!writeResult.exception && tryAgain) {
2358 // TCP buffer is full; we can't write any more data right now.
2360 *partialWritten = 0;
2361 return WriteResult(0);
2365 *partialWritten = 0;
2369 appBytesWritten_ += totalWritten;
2371 uint32_t bytesWritten;
2373 for (bytesWritten = uint32_t(totalWritten), n = 0; n < count; ++n) {
2374 const iovec* v = vec + n;
2375 if (v->iov_len > bytesWritten) {
2376 // Partial write finished in the middle of this iovec
2378 *partialWritten = bytesWritten;
2379 return WriteResult(totalWritten);
2382 bytesWritten -= uint32_t(v->iov_len);
2385 assert(bytesWritten == 0);
2387 *partialWritten = 0;
2388 return WriteResult(totalWritten);
2392 * Re-register the EventHandler after eventFlags_ has changed.
2394 * If an error occurs, fail() is called to move the socket into the error state
2395 * and call all currently installed callbacks. After an error, the
2396 * AsyncSocket is completely unregistered.
2398 * @return Returns true on success, or false on error.
2400 bool AsyncSocket::updateEventRegistration() {
2401 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
2402 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
2403 << ", events=" << std::hex << eventFlags_;
2404 eventBase_->dcheckIsInEventBaseThread();
2405 if (eventFlags_ == EventHandler::NONE) {
2406 ioHandler_.unregisterHandler();
2410 // Always register for persistent events, so we don't have to re-register
2411 // after being called back.
2412 if (!ioHandler_.registerHandler(
2413 uint16_t(eventFlags_ | EventHandler::PERSIST))) {
2414 eventFlags_ = EventHandler::NONE; // we're not registered after error
2415 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
2416 withAddr("failed to update AsyncSocket event registration"));
2417 fail("updateEventRegistration", ex);
2424 bool AsyncSocket::updateEventRegistration(uint16_t enable,
2426 uint16_t oldFlags = eventFlags_;
2427 eventFlags_ |= enable;
2428 eventFlags_ &= ~disable;
2429 if (eventFlags_ == oldFlags) {
2432 return updateEventRegistration();
2436 void AsyncSocket::startFail() {
2437 // startFail() should only be called once
2438 assert(state_ != StateEnum::ERROR);
2439 assert(getDestructorGuardCount() > 0);
2440 state_ = StateEnum::ERROR;
2441 // Ensure that SHUT_READ and SHUT_WRITE are set,
2442 // so all future attempts to read or write will be rejected
2443 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
2445 if (eventFlags_ != EventHandler::NONE) {
2446 eventFlags_ = EventHandler::NONE;
2447 ioHandler_.unregisterHandler();
2449 writeTimeout_.cancelTimeout();
2452 ioHandler_.changeHandlerFD(-1);
2457 void AsyncSocket::invokeAllErrors(const AsyncSocketException& ex) {
2458 invokeConnectErr(ex);
2461 if (readCallback_) {
2462 ReadCallback* callback = readCallback_;
2463 readCallback_ = nullptr;
2464 callback->readErr(ex);
2468 void AsyncSocket::finishFail() {
2469 assert(state_ == StateEnum::ERROR);
2470 assert(getDestructorGuardCount() > 0);
2472 AsyncSocketException ex(
2473 AsyncSocketException::INTERNAL_ERROR,
2474 withAddr("socket closing after error"));
2475 invokeAllErrors(ex);
2478 void AsyncSocket::finishFail(const AsyncSocketException& ex) {
2479 assert(state_ == StateEnum::ERROR);
2480 assert(getDestructorGuardCount() > 0);
2481 invokeAllErrors(ex);
2484 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
2485 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2486 << state_ << " host=" << addr_.describe()
2487 << "): failed in " << fn << "(): "
2493 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
2494 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2495 << state_ << " host=" << addr_.describe()
2496 << "): failed while connecting in " << fn << "(): "
2500 invokeConnectErr(ex);
2504 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
2505 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2506 << state_ << " host=" << addr_.describe()
2507 << "): failed while reading in " << fn << "(): "
2511 if (readCallback_ != nullptr) {
2512 ReadCallback* callback = readCallback_;
2513 readCallback_ = nullptr;
2514 callback->readErr(ex);
2520 void AsyncSocket::failErrMessageRead(const char* fn,
2521 const AsyncSocketException& ex) {
2522 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2523 << state_ << " host=" << addr_.describe()
2524 << "): failed while reading message in " << fn << "(): "
2528 if (errMessageCallback_ != nullptr) {
2529 ErrMessageCallback* callback = errMessageCallback_;
2530 errMessageCallback_ = nullptr;
2531 callback->errMessageError(ex);
2537 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
2538 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2539 << state_ << " host=" << addr_.describe()
2540 << "): failed while writing in " << fn << "(): "
2544 // Only invoke the first write callback, since the error occurred while
2545 // writing this request. Let any other pending write callbacks be invoked in
2547 if (writeReqHead_ != nullptr) {
2548 WriteRequest* req = writeReqHead_;
2549 writeReqHead_ = req->getNext();
2550 WriteCallback* callback = req->getCallback();
2551 uint32_t bytesWritten = req->getTotalBytesWritten();
2554 callback->writeErr(bytesWritten, ex);
2561 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
2562 size_t bytesWritten,
2563 const AsyncSocketException& ex) {
2564 // This version of failWrite() is used when the failure occurs before
2565 // we've added the callback to writeReqHead_.
2566 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2567 << state_ << " host=" << addr_.describe()
2568 <<"): failed while writing in " << fn << "(): "
2572 if (callback != nullptr) {
2573 callback->writeErr(bytesWritten, ex);
2579 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
2580 // Invoke writeError() on all write callbacks.
2581 // This is used when writes are forcibly shutdown with write requests
2582 // pending, or when an error occurs with writes pending.
2583 while (writeReqHead_ != nullptr) {
2584 WriteRequest* req = writeReqHead_;
2585 writeReqHead_ = req->getNext();
2586 WriteCallback* callback = req->getCallback();
2588 callback->writeErr(req->getTotalBytesWritten(), ex);
2594 void AsyncSocket::invalidState(ConnectCallback* callback) {
2595 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2596 << "): connect() called in invalid state " << state_;
2599 * The invalidState() methods don't use the normal failure mechanisms,
2600 * since we don't know what state we are in. We don't want to call
2601 * startFail()/finishFail() recursively if we are already in the middle of
2605 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
2606 "connect() called with socket in invalid state");
2607 connectEndTime_ = std::chrono::steady_clock::now();
2608 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2610 callback->connectErr(ex);
2613 // We can't use failConnect() here since connectCallback_
2614 // may already be set to another callback. Invoke this ConnectCallback
2615 // here; any other connectCallback_ will be invoked in finishFail()
2618 callback->connectErr(ex);
2624 void AsyncSocket::invalidState(ErrMessageCallback* callback) {
2625 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2626 << "): setErrMessageCB(" << callback
2627 << ") called in invalid state " << state_;
2629 AsyncSocketException ex(
2630 AsyncSocketException::NOT_OPEN,
2631 msgErrQueueSupported
2632 ? "setErrMessageCB() called with socket in invalid state"
2633 : "This platform does not support socket error message notifications");
2634 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2636 callback->errMessageError(ex);
2641 callback->errMessageError(ex);
2647 void AsyncSocket::invokeConnectErr(const AsyncSocketException& ex) {
2648 connectEndTime_ = std::chrono::steady_clock::now();
2649 if (connectCallback_) {
2650 ConnectCallback* callback = connectCallback_;
2651 connectCallback_ = nullptr;
2652 callback->connectErr(ex);
2656 void AsyncSocket::invokeConnectSuccess() {
2657 connectEndTime_ = std::chrono::steady_clock::now();
2658 if (connectCallback_) {
2659 ConnectCallback* callback = connectCallback_;
2660 connectCallback_ = nullptr;
2661 callback->connectSuccess();
2665 void AsyncSocket::invalidState(ReadCallback* callback) {
2666 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2667 << "): setReadCallback(" << callback
2668 << ") called in invalid state " << state_;
2670 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2671 "setReadCallback() called with socket in "
2673 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2675 callback->readErr(ex);
2680 callback->readErr(ex);
2686 void AsyncSocket::invalidState(WriteCallback* callback) {
2687 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2688 << "): write() called in invalid state " << state_;
2690 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2691 withAddr("write() called with socket in invalid state"));
2692 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2694 callback->writeErr(0, ex);
2699 callback->writeErr(0, ex);
2705 void AsyncSocket::doClose() {
2709 if (const auto shutdownSocketSet = wShutdownSocketSet_.lock()) {
2710 shutdownSocketSet->close(fd_);
2717 std::ostream& operator << (std::ostream& os,
2718 const AsyncSocket::StateEnum& state) {
2719 os << static_cast<int>(state);
2723 std::string AsyncSocket::withAddr(const std::string& s) {
2724 // Don't use addr_ directly because it may not be initialized
2725 // e.g. if constructed from fd
2726 folly::SocketAddress peer, local;
2728 getPeerAddress(&peer);
2729 getLocalAddress(&local);
2730 } catch (const std::exception&) {
2735 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";
2738 void AsyncSocket::setBufferCallback(BufferCallback* cb) {
2739 bufferCallback_ = cb;
2742 } // namespace folly