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_->addZeroCopyBuff(std::move(ioBuf_));
119 socket_->addZeroCopyBuff(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_->containsZeroCopyBuff(ioBuf_.get())) {
126 socket_->setZeroCopyBuff(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::addZeroCopyBuff(std::unique_ptr<folly::IOBuf>&& buf) {
895 uint32_t id = getNextZeroCopyBuffId();
896 folly::IOBuf* ptr = buf.get();
898 idZeroCopyBufPtrMap_[id] = ptr;
899 auto& p = idZeroCopyBufPtrToBufMap_[ptr];
901 CHECK(p.second.get() == nullptr);
902 p.second = std::move(buf);
905 void AsyncSocket::addZeroCopyBuff(folly::IOBuf* ptr) {
906 uint32_t id = getNextZeroCopyBuffId();
907 idZeroCopyBufPtrMap_[id] = ptr;
909 idZeroCopyBufPtrToBufMap_[ptr].first++;
912 void AsyncSocket::releaseZeroCopyBuff(uint32_t id) {
913 auto iter = idZeroCopyBufPtrMap_.find(id);
914 CHECK(iter != idZeroCopyBufPtrMap_.end());
915 auto ptr = iter->second;
916 auto iter1 = idZeroCopyBufPtrToBufMap_.find(ptr);
917 CHECK(iter1 != idZeroCopyBufPtrToBufMap_.end());
918 if (0 == --iter1->second.first) {
919 idZeroCopyBufPtrToBufMap_.erase(iter1);
923 void AsyncSocket::setZeroCopyBuff(std::unique_ptr<folly::IOBuf>&& buf) {
924 folly::IOBuf* ptr = buf.get();
925 auto& p = idZeroCopyBufPtrToBufMap_[ptr];
926 CHECK(p.second.get() == nullptr);
928 p.second = std::move(buf);
931 bool AsyncSocket::containsZeroCopyBuff(folly::IOBuf* ptr) {
933 idZeroCopyBufPtrToBufMap_.find(ptr) != idZeroCopyBufPtrToBufMap_.end());
936 bool AsyncSocket::isZeroCopyMsg(const cmsghdr& cmsg) const {
938 if (zeroCopyEnabled_ &&
939 ((cmsg.cmsg_level == SOL_IP && cmsg.cmsg_type == IP_RECVERR) ||
940 (cmsg.cmsg_level == SOL_IPV6 && cmsg.cmsg_type == IPV6_RECVERR))) {
941 const struct sock_extended_err* serr =
942 reinterpret_cast<const struct sock_extended_err*>(CMSG_DATA(&cmsg));
944 (serr->ee_errno == 0) && (serr->ee_origin == SO_EE_ORIGIN_ZEROCOPY));
950 void AsyncSocket::processZeroCopyMsg(const cmsghdr& cmsg) {
952 const struct sock_extended_err* serr =
953 reinterpret_cast<const struct sock_extended_err*>(CMSG_DATA(&cmsg));
954 uint32_t hi = serr->ee_data;
955 uint32_t lo = serr->ee_info;
957 for (uint32_t i = lo; i <= hi; i++) {
958 releaseZeroCopyBuff(i);
963 void AsyncSocket::write(WriteCallback* callback,
964 const void* buf, size_t bytes, WriteFlags flags) {
966 op.iov_base = const_cast<void*>(buf);
968 writeImpl(callback, &op, 1, unique_ptr<IOBuf>(), flags);
971 void AsyncSocket::writev(WriteCallback* callback,
975 writeImpl(callback, vec, count, unique_ptr<IOBuf>(), flags);
978 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
980 adjustZeroCopyFlags(buf.get(), flags);
982 constexpr size_t kSmallSizeMax = 64;
983 size_t count = buf->countChainElements();
984 if (count <= kSmallSizeMax) {
985 // suppress "warning: variable length array 'vec' is used [-Wvla]"
987 FOLLY_GCC_DISABLE_WARNING("-Wvla")
988 iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA, count, kSmallSizeMax)];
991 writeChainImpl(callback, vec, count, std::move(buf), flags);
993 iovec* vec = new iovec[count];
994 writeChainImpl(callback, vec, count, std::move(buf), flags);
999 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
1000 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
1001 size_t veclen = buf->fillIov(vec, count);
1002 writeImpl(callback, vec, veclen, std::move(buf), flags);
1005 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
1006 size_t count, unique_ptr<IOBuf>&& buf,
1008 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
1009 << ", callback=" << callback << ", count=" << count
1010 << ", state=" << state_;
1011 DestructorGuard dg(this);
1012 unique_ptr<IOBuf>ioBuf(std::move(buf));
1013 eventBase_->dcheckIsInEventBaseThread();
1015 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
1016 // No new writes may be performed after the write side of the socket has
1019 // We could just call callback->writeError() here to fail just this write.
1020 // However, fail hard and use invalidState() to fail all outstanding
1021 // callbacks and move the socket into the error state. There's most likely
1022 // a bug in the caller's code, so we abort everything rather than trying to
1023 // proceed as best we can.
1024 return invalidState(callback);
1027 uint32_t countWritten = 0;
1028 uint32_t partialWritten = 0;
1029 ssize_t bytesWritten = 0;
1030 bool mustRegister = false;
1031 if ((state_ == StateEnum::ESTABLISHED || state_ == StateEnum::FAST_OPEN) &&
1033 if (writeReqHead_ == nullptr) {
1034 // If we are established and there are no other writes pending,
1035 // we can attempt to perform the write immediately.
1036 assert(writeReqTail_ == nullptr);
1037 assert((eventFlags_ & EventHandler::WRITE) == 0);
1039 auto writeResult = performWrite(
1040 vec, uint32_t(count), flags, &countWritten, &partialWritten);
1041 bytesWritten = writeResult.writeReturn;
1042 if (bytesWritten < 0) {
1043 auto errnoCopy = errno;
1044 if (writeResult.exception) {
1045 return failWrite(__func__, callback, 0, *writeResult.exception);
1047 AsyncSocketException ex(
1048 AsyncSocketException::INTERNAL_ERROR,
1049 withAddr("writev failed"),
1051 return failWrite(__func__, callback, 0, ex);
1052 } else if (countWritten == count) {
1053 // done, add the whole buffer
1054 if (isZeroCopyRequest(flags)) {
1055 addZeroCopyBuff(std::move(ioBuf));
1057 // We successfully wrote everything.
1058 // Invoke the callback and return.
1060 callback->writeSuccess();
1063 } else { // continue writing the next writeReq
1065 if (isZeroCopyRequest(flags)) {
1066 addZeroCopyBuff(ioBuf.get());
1068 if (bufferCallback_) {
1069 bufferCallback_->onEgressBuffered();
1072 if (!connecting()) {
1073 // Writes might put the socket back into connecting state
1074 // if TFO is enabled, and using TFO fails.
1075 // This means that write timeouts would not be active, however
1076 // connect timeouts would affect this stage.
1077 mustRegister = true;
1080 } else if (!connecting()) {
1081 // Invalid state for writing
1082 return invalidState(callback);
1085 // Create a new WriteRequest to add to the queue
1088 req = BytesWriteRequest::newRequest(
1092 uint32_t(count - countWritten),
1094 uint32_t(bytesWritten),
1097 } catch (const std::exception& ex) {
1098 // we mainly expect to catch std::bad_alloc here
1099 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
1100 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
1101 return failWrite(__func__, callback, size_t(bytesWritten), tex);
1104 if (writeReqTail_ == nullptr) {
1105 assert(writeReqHead_ == nullptr);
1106 writeReqHead_ = writeReqTail_ = req;
1108 writeReqTail_->append(req);
1109 writeReqTail_ = req;
1112 // Register for write events if are established and not currently
1113 // waiting on write events
1115 assert(state_ == StateEnum::ESTABLISHED);
1116 assert((eventFlags_ & EventHandler::WRITE) == 0);
1117 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1118 assert(state_ == StateEnum::ERROR);
1121 if (sendTimeout_ > 0) {
1122 // Schedule a timeout to fire if the write takes too long.
1123 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1124 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1125 withAddr("failed to schedule send timeout"));
1126 return failWrite(__func__, ex);
1132 void AsyncSocket::writeRequest(WriteRequest* req) {
1133 if (writeReqTail_ == nullptr) {
1134 assert(writeReqHead_ == nullptr);
1135 writeReqHead_ = writeReqTail_ = req;
1138 writeReqTail_->append(req);
1139 writeReqTail_ = req;
1143 void AsyncSocket::close() {
1144 VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
1145 << ", state=" << state_ << ", shutdownFlags="
1146 << std::hex << (int) shutdownFlags_;
1148 // close() is only different from closeNow() when there are pending writes
1149 // that need to drain before we can close. In all other cases, just call
1152 // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
1153 // STATE_ERROR if close() is invoked while a previous closeNow() or failure
1154 // is still running. (e.g., If there are multiple pending writes, and we
1155 // call writeError() on the first one, it may call close(). In this case we
1156 // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
1157 // writes will still be in the queue.)
1159 // We only need to drain pending writes if we are still in STATE_CONNECTING
1160 // or STATE_ESTABLISHED
1161 if ((writeReqHead_ == nullptr) ||
1162 !(state_ == StateEnum::CONNECTING ||
1163 state_ == StateEnum::ESTABLISHED)) {
1168 // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
1169 // destroyed until close() returns.
1170 DestructorGuard dg(this);
1171 eventBase_->dcheckIsInEventBaseThread();
1173 // Since there are write requests pending, we have to set the
1174 // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
1175 // connect finishes and we finish writing these requests.
1177 // Set SHUT_READ to indicate that reads are shut down, and set the
1178 // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
1179 // pending writes complete.
1180 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
1182 // If a read callback is set, invoke readEOF() immediately to inform it that
1183 // the socket has been closed and no more data can be read.
1184 if (readCallback_) {
1185 // Disable reads if they are enabled
1186 if (!updateEventRegistration(0, EventHandler::READ)) {
1187 // We're now in the error state; callbacks have been cleaned up
1188 assert(state_ == StateEnum::ERROR);
1189 assert(readCallback_ == nullptr);
1191 ReadCallback* callback = readCallback_;
1192 readCallback_ = nullptr;
1193 callback->readEOF();
1198 void AsyncSocket::closeNow() {
1199 VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
1200 << ", state=" << state_ << ", shutdownFlags="
1201 << std::hex << (int) shutdownFlags_;
1202 DestructorGuard dg(this);
1204 eventBase_->dcheckIsInEventBaseThread();
1208 case StateEnum::ESTABLISHED:
1209 case StateEnum::CONNECTING:
1210 case StateEnum::FAST_OPEN: {
1211 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1212 state_ = StateEnum::CLOSED;
1214 // If the write timeout was set, cancel it.
1215 writeTimeout_.cancelTimeout();
1217 // If we are registered for I/O events, unregister.
1218 if (eventFlags_ != EventHandler::NONE) {
1219 eventFlags_ = EventHandler::NONE;
1220 if (!updateEventRegistration()) {
1221 // We will have been moved into the error state.
1222 assert(state_ == StateEnum::ERROR);
1227 if (immediateReadHandler_.isLoopCallbackScheduled()) {
1228 immediateReadHandler_.cancelLoopCallback();
1232 ioHandler_.changeHandlerFD(-1);
1236 invokeConnectErr(socketClosedLocallyEx);
1238 failAllWrites(socketClosedLocallyEx);
1240 if (readCallback_) {
1241 ReadCallback* callback = readCallback_;
1242 readCallback_ = nullptr;
1243 callback->readEOF();
1247 case StateEnum::CLOSED:
1248 // Do nothing. It's possible that we are being called recursively
1249 // from inside a callback that we invoked inside another call to close()
1250 // that is still running.
1252 case StateEnum::ERROR:
1253 // Do nothing. The error handling code has performed (or is performing)
1256 case StateEnum::UNINIT:
1257 assert(eventFlags_ == EventHandler::NONE);
1258 assert(connectCallback_ == nullptr);
1259 assert(readCallback_ == nullptr);
1260 assert(writeReqHead_ == nullptr);
1261 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1262 state_ = StateEnum::CLOSED;
1266 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
1267 << ") called in unknown state " << state_;
1270 void AsyncSocket::closeWithReset() {
1271 // Enable SO_LINGER, with the linger timeout set to 0.
1272 // This will trigger a TCP reset when we close the socket.
1274 struct linger optLinger = {1, 0};
1275 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
1276 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
1277 << "on " << fd_ << ": errno=" << errno;
1281 // Then let closeNow() take care of the rest
1285 void AsyncSocket::shutdownWrite() {
1286 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
1287 << ", state=" << state_ << ", shutdownFlags="
1288 << std::hex << (int) shutdownFlags_;
1290 // If there are no pending writes, shutdownWrite() is identical to
1291 // shutdownWriteNow().
1292 if (writeReqHead_ == nullptr) {
1297 eventBase_->dcheckIsInEventBaseThread();
1299 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
1300 // shutdown will be performed once all writes complete.
1301 shutdownFlags_ |= SHUT_WRITE_PENDING;
1304 void AsyncSocket::shutdownWriteNow() {
1305 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
1306 << ", fd=" << fd_ << ", state=" << state_
1307 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
1309 if (shutdownFlags_ & SHUT_WRITE) {
1310 // Writes are already shutdown; nothing else to do.
1314 // If SHUT_READ is already set, just call closeNow() to completely
1315 // close the socket. This can happen if close() was called with writes
1316 // pending, and then shutdownWriteNow() is called before all pending writes
1318 if (shutdownFlags_ & SHUT_READ) {
1323 DestructorGuard dg(this);
1325 eventBase_->dcheckIsInEventBaseThread();
1328 switch (static_cast<StateEnum>(state_)) {
1329 case StateEnum::ESTABLISHED:
1331 shutdownFlags_ |= SHUT_WRITE;
1333 // If the write timeout was set, cancel it.
1334 writeTimeout_.cancelTimeout();
1336 // If we are registered for write events, unregister.
1337 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1338 // We will have been moved into the error state.
1339 assert(state_ == StateEnum::ERROR);
1343 // Shutdown writes on the file descriptor
1344 shutdown(fd_, SHUT_WR);
1346 // Immediately fail all write requests
1347 failAllWrites(socketShutdownForWritesEx);
1350 case StateEnum::CONNECTING:
1352 // Set the SHUT_WRITE_PENDING flag.
1353 // When the connection completes, it will check this flag,
1354 // shutdown the write half of the socket, and then set SHUT_WRITE.
1355 shutdownFlags_ |= SHUT_WRITE_PENDING;
1357 // Immediately fail all write requests
1358 failAllWrites(socketShutdownForWritesEx);
1361 case StateEnum::UNINIT:
1362 // Callers normally shouldn't call shutdownWriteNow() before the socket
1363 // even starts connecting. Nonetheless, go ahead and set
1364 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
1365 // immediately shut down the write side of the socket.
1366 shutdownFlags_ |= SHUT_WRITE_PENDING;
1368 case StateEnum::FAST_OPEN:
1369 // In fast open state we haven't call connected yet, and if we shutdown
1370 // the writes, we will never try to call connect, so shut everything down
1371 shutdownFlags_ |= SHUT_WRITE;
1372 // Immediately fail all write requests
1373 failAllWrites(socketShutdownForWritesEx);
1375 case StateEnum::CLOSED:
1376 case StateEnum::ERROR:
1377 // We should never get here. SHUT_WRITE should always be set
1378 // in STATE_CLOSED and STATE_ERROR.
1379 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
1380 << ", fd=" << fd_ << ") in unexpected state " << state_
1381 << " with SHUT_WRITE not set ("
1382 << std::hex << (int) shutdownFlags_ << ")";
1387 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
1388 << fd_ << ") called in unknown state " << state_;
1391 bool AsyncSocket::readable() const {
1395 struct pollfd fds[1];
1397 fds[0].events = POLLIN;
1399 int rc = poll(fds, 1, 0);
1403 bool AsyncSocket::writable() const {
1407 struct pollfd fds[1];
1409 fds[0].events = POLLOUT;
1411 int rc = poll(fds, 1, 0);
1415 bool AsyncSocket::isPending() const {
1416 return ioHandler_.isPending();
1419 bool AsyncSocket::hangup() const {
1421 // sanity check, no one should ask for hangup if we are not connected.
1425 #ifdef POLLRDHUP // Linux-only
1426 struct pollfd fds[1];
1428 fds[0].events = POLLRDHUP|POLLHUP;
1431 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1437 bool AsyncSocket::good() const {
1439 (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN ||
1440 state_ == StateEnum::ESTABLISHED) &&
1441 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1444 bool AsyncSocket::error() const {
1445 return (state_ == StateEnum::ERROR);
1448 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1449 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1450 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1451 << ", state=" << state_ << ", events="
1452 << std::hex << eventFlags_ << ")";
1453 assert(eventBase_ == nullptr);
1454 eventBase->dcheckIsInEventBaseThread();
1456 eventBase_ = eventBase;
1457 ioHandler_.attachEventBase(eventBase);
1458 writeTimeout_.attachEventBase(eventBase);
1460 evbChangeCb_->evbAttached(this);
1464 void AsyncSocket::detachEventBase() {
1465 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1466 << ", old evb=" << eventBase_ << ", state=" << state_
1467 << ", events=" << std::hex << eventFlags_ << ")";
1468 assert(eventBase_ != nullptr);
1469 eventBase_->dcheckIsInEventBaseThread();
1471 eventBase_ = nullptr;
1472 ioHandler_.detachEventBase();
1473 writeTimeout_.detachEventBase();
1475 evbChangeCb_->evbDetached(this);
1479 bool AsyncSocket::isDetachable() const {
1480 DCHECK(eventBase_ != nullptr);
1481 eventBase_->dcheckIsInEventBaseThread();
1483 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1486 void AsyncSocket::cacheAddresses() {
1489 cacheLocalAddress();
1491 } catch (const std::system_error& e) {
1492 if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
1493 VLOG(1) << "Error caching addresses: " << e.code().value() << ", "
1494 << e.code().message();
1500 void AsyncSocket::cacheLocalAddress() const {
1501 if (!localAddr_.isInitialized()) {
1502 localAddr_.setFromLocalAddress(fd_);
1506 void AsyncSocket::cachePeerAddress() const {
1507 if (!addr_.isInitialized()) {
1508 addr_.setFromPeerAddress(fd_);
1512 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1513 cacheLocalAddress();
1514 *address = localAddr_;
1517 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1522 bool AsyncSocket::getTFOSucceded() const {
1523 return detail::tfo_succeeded(fd_);
1526 int AsyncSocket::setNoDelay(bool noDelay) {
1528 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1529 << this << "(state=" << state_ << ")";
1534 int value = noDelay ? 1 : 0;
1535 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1536 int errnoCopy = errno;
1537 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1538 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1539 << strerror(errnoCopy);
1546 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1548 #ifndef TCP_CONGESTION
1549 #define TCP_CONGESTION 13
1553 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1554 << "socket " << this << "(state=" << state_ << ")";
1564 socklen_t(cname.length() + 1)) != 0) {
1565 int errnoCopy = errno;
1566 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1567 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1568 << strerror(errnoCopy);
1575 int AsyncSocket::setQuickAck(bool quickack) {
1578 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1579 << this << "(state=" << state_ << ")";
1584 #ifdef TCP_QUICKACK // Linux-only
1585 int value = quickack ? 1 : 0;
1586 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1587 int errnoCopy = errno;
1588 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1589 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1590 << strerror(errnoCopy);
1600 int AsyncSocket::setSendBufSize(size_t bufsize) {
1602 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1603 << this << "(state=" << state_ << ")";
1607 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1608 int errnoCopy = errno;
1609 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1610 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1611 << strerror(errnoCopy);
1618 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1620 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1621 << this << "(state=" << state_ << ")";
1625 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1626 int errnoCopy = errno;
1627 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1628 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1629 << strerror(errnoCopy);
1636 int AsyncSocket::setTCPProfile(int profd) {
1638 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1639 << this << "(state=" << state_ << ")";
1643 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1644 int errnoCopy = errno;
1645 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1646 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1647 << strerror(errnoCopy);
1654 void AsyncSocket::ioReady(uint16_t events) noexcept {
1655 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd=" << fd_
1656 << ", events=" << std::hex << events << ", state=" << state_;
1657 DestructorGuard dg(this);
1658 assert(events & EventHandler::READ_WRITE);
1659 eventBase_->dcheckIsInEventBaseThread();
1661 uint16_t relevantEvents = uint16_t(events & EventHandler::READ_WRITE);
1662 EventBase* originalEventBase = eventBase_;
1663 // If we got there it means that either EventHandler::READ or
1664 // EventHandler::WRITE is set. Any of these flags can
1665 // indicate that there are messages available in the socket
1666 // error message queue.
1667 handleErrMessages();
1669 // Return now if handleErrMessages() detached us from our EventBase
1670 if (eventBase_ != originalEventBase) {
1674 if (relevantEvents == EventHandler::READ) {
1676 } else if (relevantEvents == EventHandler::WRITE) {
1678 } else if (relevantEvents == EventHandler::READ_WRITE) {
1679 // If both read and write events are ready, process writes first.
1682 // Return now if handleWrite() detached us from our EventBase
1683 if (eventBase_ != originalEventBase) {
1687 // Only call handleRead() if a read callback is still installed.
1688 // (It's possible that the read callback was uninstalled during
1690 if (readCallback_) {
1694 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1695 << std::hex << events << "(this=" << this << ")";
1700 AsyncSocket::ReadResult
1701 AsyncSocket::performRead(void** buf, size_t* buflen, size_t* /* offset */) {
1702 VLOG(5) << "AsyncSocket::performRead() this=" << this << ", buf=" << *buf
1703 << ", buflen=" << *buflen;
1705 if (preReceivedData_ && !preReceivedData_->empty()) {
1706 VLOG(5) << "AsyncSocket::performRead() this=" << this
1707 << ", reading pre-received data";
1709 io::Cursor cursor(preReceivedData_.get());
1710 auto len = cursor.pullAtMost(*buf, *buflen);
1713 queue.append(std::move(preReceivedData_));
1714 queue.trimStart(len);
1715 preReceivedData_ = queue.move();
1717 appBytesReceived_ += len;
1718 return ReadResult(len);
1721 ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT);
1723 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1724 // No more data to read right now.
1725 return ReadResult(READ_BLOCKING);
1727 return ReadResult(READ_ERROR);
1730 appBytesReceived_ += bytes;
1731 return ReadResult(bytes);
1735 void AsyncSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1736 // no matter what, buffer should be preapared for non-ssl socket
1737 CHECK(readCallback_);
1738 readCallback_->getReadBuffer(buf, buflen);
1741 void AsyncSocket::handleErrMessages() noexcept {
1742 // This method has non-empty implementation only for platforms
1743 // supporting per-socket error queues.
1744 VLOG(5) << "AsyncSocket::handleErrMessages() this=" << this << ", fd=" << fd_
1745 << ", state=" << state_;
1746 if (errMessageCallback_ == nullptr &&
1747 (!zeroCopyEnabled_ || idZeroCopyBufPtrMap_.empty())) {
1748 VLOG(7) << "AsyncSocket::handleErrMessages(): "
1749 << "no callback installed - exiting.";
1759 entry.iov_base = &data;
1760 entry.iov_len = sizeof(data);
1761 msg.msg_iov = &entry;
1763 msg.msg_name = nullptr;
1764 msg.msg_namelen = 0;
1765 msg.msg_control = ctrl;
1766 msg.msg_controllen = sizeof(ctrl);
1771 ret = recvmsg(fd_, &msg, MSG_ERRQUEUE);
1772 VLOG(5) << "AsyncSocket::handleErrMessages(): recvmsg returned " << ret;
1775 if (errno != EAGAIN) {
1776 auto errnoCopy = errno;
1777 LOG(ERROR) << "::recvmsg exited with code " << ret
1778 << ", errno: " << errnoCopy;
1779 AsyncSocketException ex(
1780 AsyncSocketException::INTERNAL_ERROR,
1781 withAddr("recvmsg() failed"),
1783 failErrMessageRead(__func__, ex);
1788 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
1789 cmsg != nullptr && cmsg->cmsg_len != 0;
1790 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1791 if (isZeroCopyMsg(*cmsg)) {
1792 processZeroCopyMsg(*cmsg);
1794 if (errMessageCallback_) {
1795 errMessageCallback_->errMessage(*cmsg);
1800 #endif //MSG_ERRQUEUE
1803 void AsyncSocket::handleRead() noexcept {
1804 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1805 << ", state=" << state_;
1806 assert(state_ == StateEnum::ESTABLISHED);
1807 assert((shutdownFlags_ & SHUT_READ) == 0);
1808 assert(readCallback_ != nullptr);
1809 assert(eventFlags_ & EventHandler::READ);
1812 // - a read attempt would block
1813 // - readCallback_ is uninstalled
1814 // - the number of loop iterations exceeds the optional maximum
1815 // - this AsyncSocket is moved to another EventBase
1817 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1818 // which is why need to check for it here.
1820 // The last bullet point is slightly subtle. readDataAvailable() may also
1821 // detach this socket from this EventBase. However, before
1822 // readDataAvailable() returns another thread may pick it up, attach it to
1823 // a different EventBase, and install another readCallback_. We need to
1824 // exit immediately after readDataAvailable() returns if the eventBase_ has
1825 // changed. (The caller must perform some sort of locking to transfer the
1826 // AsyncSocket between threads properly. This will be sufficient to ensure
1827 // that this thread sees the updated eventBase_ variable after
1828 // readDataAvailable() returns.)
1829 uint16_t numReads = 0;
1830 EventBase* originalEventBase = eventBase_;
1831 while (readCallback_ && eventBase_ == originalEventBase) {
1832 // Get the buffer to read into.
1833 void* buf = nullptr;
1834 size_t buflen = 0, offset = 0;
1836 prepareReadBuffer(&buf, &buflen);
1837 VLOG(5) << "prepareReadBuffer() buf=" << buf << ", buflen=" << buflen;
1838 } catch (const AsyncSocketException& ex) {
1839 return failRead(__func__, ex);
1840 } catch (const std::exception& ex) {
1841 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1842 string("ReadCallback::getReadBuffer() "
1843 "threw exception: ") +
1845 return failRead(__func__, tex);
1847 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1848 "ReadCallback::getReadBuffer() threw "
1849 "non-exception type");
1850 return failRead(__func__, ex);
1852 if (!isBufferMovable_ && (buf == nullptr || buflen == 0)) {
1853 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1854 "ReadCallback::getReadBuffer() returned "
1856 return failRead(__func__, ex);
1860 auto readResult = performRead(&buf, &buflen, &offset);
1861 auto bytesRead = readResult.readReturn;
1862 VLOG(4) << "this=" << this << ", AsyncSocket::handleRead() got "
1863 << bytesRead << " bytes";
1864 if (bytesRead > 0) {
1865 if (!isBufferMovable_) {
1866 readCallback_->readDataAvailable(size_t(bytesRead));
1868 CHECK(kOpenSslModeMoveBufferOwnership);
1869 VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
1870 << "buf=" << buf << ", " << bytesRead << "/" << buflen
1871 << ", offset=" << offset;
1872 auto readBuf = folly::IOBuf::takeOwnership(buf, buflen);
1873 readBuf->trimStart(offset);
1874 readBuf->trimEnd(buflen - offset - bytesRead);
1875 readCallback_->readBufferAvailable(std::move(readBuf));
1878 // Fall through and continue around the loop if the read
1879 // completely filled the available buffer.
1880 // Note that readCallback_ may have been uninstalled or changed inside
1881 // readDataAvailable().
1882 if (size_t(bytesRead) < buflen) {
1885 } else if (bytesRead == READ_BLOCKING) {
1886 // No more data to read right now.
1888 } else if (bytesRead == READ_ERROR) {
1889 readErr_ = READ_ERROR;
1890 if (readResult.exception) {
1891 return failRead(__func__, *readResult.exception);
1893 auto errnoCopy = errno;
1894 AsyncSocketException ex(
1895 AsyncSocketException::INTERNAL_ERROR,
1896 withAddr("recv() failed"),
1898 return failRead(__func__, ex);
1900 assert(bytesRead == READ_EOF);
1901 readErr_ = READ_EOF;
1903 shutdownFlags_ |= SHUT_READ;
1904 if (!updateEventRegistration(0, EventHandler::READ)) {
1905 // we've already been moved into STATE_ERROR
1906 assert(state_ == StateEnum::ERROR);
1907 assert(readCallback_ == nullptr);
1911 ReadCallback* callback = readCallback_;
1912 readCallback_ = nullptr;
1913 callback->readEOF();
1916 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1917 if (readCallback_ != nullptr) {
1918 // We might still have data in the socket.
1919 // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
1920 scheduleImmediateRead();
1928 * This function attempts to write as much data as possible, until no more data
1931 * - If it sends all available data, it unregisters for write events, and stops
1932 * the writeTimeout_.
1934 * - If not all of the data can be sent immediately, it reschedules
1935 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1936 * registered for write events.
1938 void AsyncSocket::handleWrite() noexcept {
1939 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1940 << ", state=" << state_;
1941 DestructorGuard dg(this);
1943 if (state_ == StateEnum::CONNECTING) {
1949 assert(state_ == StateEnum::ESTABLISHED);
1950 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1951 assert(writeReqHead_ != nullptr);
1953 // Loop until we run out of write requests,
1954 // or until this socket is moved to another EventBase.
1955 // (See the comment in handleRead() explaining how this can happen.)
1956 EventBase* originalEventBase = eventBase_;
1957 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1958 auto writeResult = writeReqHead_->performWrite();
1959 if (writeResult.writeReturn < 0) {
1960 if (writeResult.exception) {
1961 return failWrite(__func__, *writeResult.exception);
1963 auto errnoCopy = errno;
1964 AsyncSocketException ex(
1965 AsyncSocketException::INTERNAL_ERROR,
1966 withAddr("writev() failed"),
1968 return failWrite(__func__, ex);
1969 } else if (writeReqHead_->isComplete()) {
1970 // We finished this request
1971 WriteRequest* req = writeReqHead_;
1972 writeReqHead_ = req->getNext();
1974 if (writeReqHead_ == nullptr) {
1975 writeReqTail_ = nullptr;
1976 // This is the last write request.
1977 // Unregister for write events and cancel the send timer
1978 // before we invoke the callback. We have to update the state properly
1979 // before calling the callback, since it may want to detach us from
1981 if (eventFlags_ & EventHandler::WRITE) {
1982 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1983 assert(state_ == StateEnum::ERROR);
1986 // Stop the send timeout
1987 writeTimeout_.cancelTimeout();
1989 assert(!writeTimeout_.isScheduled());
1991 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
1992 // we finish sending the last write request.
1994 // We have to do this before invoking writeSuccess(), since
1995 // writeSuccess() may detach us from our EventBase.
1996 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
1997 assert(connectCallback_ == nullptr);
1998 shutdownFlags_ |= SHUT_WRITE;
2000 if (shutdownFlags_ & SHUT_READ) {
2001 // Reads have already been shutdown. Fully close the socket and
2002 // move to STATE_CLOSED.
2004 // Note: This code currently moves us to STATE_CLOSED even if
2005 // close() hasn't ever been called. This can occur if we have
2006 // received EOF from the peer and shutdownWrite() has been called
2007 // locally. Should we bother staying in STATE_ESTABLISHED in this
2008 // case, until close() is actually called? I can't think of a
2009 // reason why we would need to do so. No other operations besides
2010 // calling close() or destroying the socket can be performed at
2012 assert(readCallback_ == nullptr);
2013 state_ = StateEnum::CLOSED;
2015 ioHandler_.changeHandlerFD(-1);
2019 // Reads are still enabled, so we are only doing a half-shutdown
2020 shutdown(fd_, SHUT_WR);
2025 // Invoke the callback
2026 WriteCallback* callback = req->getCallback();
2029 callback->writeSuccess();
2031 // We'll continue around the loop, trying to write another request
2034 if (bufferCallback_) {
2035 bufferCallback_->onEgressBuffered();
2037 writeReqHead_->consume();
2038 // Stop after a partial write; it's highly likely that a subsequent write
2039 // attempt will just return EAGAIN.
2041 // Ensure that we are registered for write events.
2042 if ((eventFlags_ & EventHandler::WRITE) == 0) {
2043 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
2044 assert(state_ == StateEnum::ERROR);
2049 // Reschedule the send timeout, since we have made some write progress.
2050 if (sendTimeout_ > 0) {
2051 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
2052 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
2053 withAddr("failed to reschedule write timeout"));
2054 return failWrite(__func__, ex);
2060 if (!writeReqHead_ && bufferCallback_) {
2061 bufferCallback_->onEgressBufferCleared();
2065 void AsyncSocket::checkForImmediateRead() noexcept {
2066 // We currently don't attempt to perform optimistic reads in AsyncSocket.
2067 // (However, note that some subclasses do override this method.)
2069 // Simply calling handleRead() here would be bad, as this would call
2070 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
2071 // buffer even though no data may be available. This would waste lots of
2072 // memory, since the buffer will sit around unused until the socket actually
2073 // becomes readable.
2075 // Checking if the socket is readable now also seems like it would probably
2076 // be a pessimism. In most cases it probably wouldn't be readable, and we
2077 // would just waste an extra system call. Even if it is readable, waiting to
2078 // find out from libevent on the next event loop doesn't seem that bad.
2080 // The exception to this is if we have pre-received data. In that case there
2081 // is definitely data available immediately.
2082 if (preReceivedData_ && !preReceivedData_->empty()) {
2087 void AsyncSocket::handleInitialReadWrite() noexcept {
2088 // Our callers should already be holding a DestructorGuard, but grab
2089 // one here just to make sure, in case one of our calling code paths ever
2091 DestructorGuard dg(this);
2092 // If we have a readCallback_, make sure we enable read events. We
2093 // may already be registered for reads if connectSuccess() set
2094 // the read calback.
2095 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
2096 assert(state_ == StateEnum::ESTABLISHED);
2097 assert((shutdownFlags_ & SHUT_READ) == 0);
2098 if (!updateEventRegistration(EventHandler::READ, 0)) {
2099 assert(state_ == StateEnum::ERROR);
2102 checkForImmediateRead();
2103 } else if (readCallback_ == nullptr) {
2104 // Unregister for read events.
2105 updateEventRegistration(0, EventHandler::READ);
2108 // If we have write requests pending, try to send them immediately.
2109 // Since we just finished accepting, there is a very good chance that we can
2110 // write without blocking.
2112 // However, we only process them if EventHandler::WRITE is not already set,
2113 // which means that we're already blocked on a write attempt. (This can
2114 // happen if connectSuccess() called write() before returning.)
2115 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
2116 // Call handleWrite() to perform write processing.
2118 } else if (writeReqHead_ == nullptr) {
2119 // Unregister for write event.
2120 updateEventRegistration(0, EventHandler::WRITE);
2124 void AsyncSocket::handleConnect() noexcept {
2125 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
2126 << ", state=" << state_;
2127 assert(state_ == StateEnum::CONNECTING);
2128 // SHUT_WRITE can never be set while we are still connecting;
2129 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
2131 assert((shutdownFlags_ & SHUT_WRITE) == 0);
2133 // In case we had a connect timeout, cancel the timeout
2134 writeTimeout_.cancelTimeout();
2135 // We don't use a persistent registration when waiting on a connect event,
2136 // so we have been automatically unregistered now. Update eventFlags_ to
2138 assert(eventFlags_ == EventHandler::WRITE);
2139 eventFlags_ = EventHandler::NONE;
2141 // Call getsockopt() to check if the connect succeeded
2143 socklen_t len = sizeof(error);
2144 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
2146 auto errnoCopy = errno;
2147 AsyncSocketException ex(
2148 AsyncSocketException::INTERNAL_ERROR,
2149 withAddr("error calling getsockopt() after connect"),
2151 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
2152 << fd_ << " host=" << addr_.describe()
2153 << ") exception:" << ex.what();
2154 return failConnect(__func__, ex);
2158 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2159 "connect failed", error);
2160 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
2161 << fd_ << " host=" << addr_.describe()
2162 << ") exception: " << ex.what();
2163 return failConnect(__func__, ex);
2166 // Move into STATE_ESTABLISHED
2167 state_ = StateEnum::ESTABLISHED;
2169 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
2170 // perform, immediately shutdown the write half of the socket.
2171 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
2172 // SHUT_READ shouldn't be set. If close() is called on the socket while we
2173 // are still connecting we just abort the connect rather than waiting for
2175 assert((shutdownFlags_ & SHUT_READ) == 0);
2176 shutdown(fd_, SHUT_WR);
2177 shutdownFlags_ |= SHUT_WRITE;
2180 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
2181 << "successfully connected; state=" << state_;
2183 // Remember the EventBase we are attached to, before we start invoking any
2184 // callbacks (since the callbacks may call detachEventBase()).
2185 EventBase* originalEventBase = eventBase_;
2187 invokeConnectSuccess();
2188 // Note that the connect callback may have changed our state.
2189 // (set or unset the read callback, called write(), closed the socket, etc.)
2190 // The following code needs to handle these situations correctly.
2192 // If the socket has been closed, readCallback_ and writeReqHead_ will
2193 // always be nullptr, so that will prevent us from trying to read or write.
2195 // The main thing to check for is if eventBase_ is still originalEventBase.
2196 // If not, we have been detached from this event base, so we shouldn't
2197 // perform any more operations.
2198 if (eventBase_ != originalEventBase) {
2202 handleInitialReadWrite();
2205 void AsyncSocket::timeoutExpired() noexcept {
2206 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
2207 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
2208 DestructorGuard dg(this);
2209 eventBase_->dcheckIsInEventBaseThread();
2211 if (state_ == StateEnum::CONNECTING) {
2212 // connect() timed out
2213 // Unregister for I/O events.
2214 if (connectCallback_) {
2215 AsyncSocketException ex(
2216 AsyncSocketException::TIMED_OUT,
2218 "connect timed out after {}ms", connectTimeout_.count()));
2219 failConnect(__func__, ex);
2221 // we faced a connect error without a connect callback, which could
2222 // happen due to TFO.
2223 AsyncSocketException ex(
2224 AsyncSocketException::TIMED_OUT, "write timed out during connection");
2225 failWrite(__func__, ex);
2228 // a normal write operation timed out
2229 AsyncSocketException ex(
2230 AsyncSocketException::TIMED_OUT,
2231 folly::sformat("write timed out after {}ms", sendTimeout_));
2232 failWrite(__func__, ex);
2236 ssize_t AsyncSocket::tfoSendMsg(int fd, struct msghdr* msg, int msg_flags) {
2237 return detail::tfo_sendmsg(fd, msg, msg_flags);
2240 AsyncSocket::WriteResult
2241 AsyncSocket::sendSocketMessage(int fd, struct msghdr* msg, int msg_flags) {
2242 ssize_t totalWritten = 0;
2243 if (state_ == StateEnum::FAST_OPEN) {
2244 sockaddr_storage addr;
2245 auto len = addr_.getAddress(&addr);
2246 msg->msg_name = &addr;
2247 msg->msg_namelen = len;
2248 totalWritten = tfoSendMsg(fd_, msg, msg_flags);
2249 if (totalWritten >= 0) {
2250 tfoFinished_ = true;
2251 state_ = StateEnum::ESTABLISHED;
2252 // We schedule this asynchrously so that we don't end up
2253 // invoking initial read or write while a write is in progress.
2254 scheduleInitialReadWrite();
2255 } else if (errno == EINPROGRESS) {
2256 VLOG(4) << "TFO falling back to connecting";
2257 // A normal sendmsg doesn't return EINPROGRESS, however
2258 // TFO might fallback to connecting if there is no
2260 state_ = StateEnum::CONNECTING;
2262 scheduleConnectTimeout();
2263 registerForConnectEvents();
2264 } catch (const AsyncSocketException& ex) {
2266 WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
2268 // Let's fake it that no bytes were written and return an errno.
2271 } else if (errno == EOPNOTSUPP) {
2272 // Try falling back to connecting.
2273 VLOG(4) << "TFO not supported";
2274 state_ = StateEnum::CONNECTING;
2276 int ret = socketConnect((const sockaddr*)&addr, len);
2278 // connect succeeded immediately
2279 // Treat this like no data was written.
2280 state_ = StateEnum::ESTABLISHED;
2281 scheduleInitialReadWrite();
2283 // If there was no exception during connections,
2284 // we would return that no bytes were written.
2287 } catch (const AsyncSocketException& ex) {
2289 WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
2291 } else if (errno == EAGAIN) {
2292 // Normally sendmsg would indicate that the write would block.
2293 // However in the fast open case, it would indicate that sendmsg
2294 // fell back to a connect. This is a return code from connect()
2295 // instead, and is an error condition indicating no fds available.
2298 std::make_unique<AsyncSocketException>(
2299 AsyncSocketException::UNKNOWN, "No more free local ports"));
2302 totalWritten = ::sendmsg(fd, msg, msg_flags);
2304 return WriteResult(totalWritten);
2307 AsyncSocket::WriteResult AsyncSocket::performWrite(
2311 uint32_t* countWritten,
2312 uint32_t* partialWritten) {
2313 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
2314 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
2315 // (since it may terminate the program if the main program doesn't explicitly
2318 msg.msg_name = nullptr;
2319 msg.msg_namelen = 0;
2320 msg.msg_iov = const_cast<iovec *>(vec);
2321 msg.msg_iovlen = std::min<size_t>(count, kIovMax);
2323 msg.msg_controllen = sendMsgParamCallback_->getAncillaryDataSize(flags);
2324 CHECK_GE(AsyncSocket::SendMsgParamsCallback::maxAncillaryDataSize,
2325 msg.msg_controllen);
2327 if (msg.msg_controllen != 0) {
2328 msg.msg_control = reinterpret_cast<char*>(alloca(msg.msg_controllen));
2329 sendMsgParamCallback_->getAncillaryData(flags, msg.msg_control);
2331 msg.msg_control = nullptr;
2333 int msg_flags = sendMsgParamCallback_->getFlags(flags, zeroCopyEnabled_);
2335 auto writeResult = sendSocketMessage(fd_, &msg, msg_flags);
2336 auto totalWritten = writeResult.writeReturn;
2337 if (totalWritten < 0) {
2338 bool tryAgain = (errno == EAGAIN);
2340 // Apple has a bug where doing a second write on a socket which we
2341 // have opened with TFO causes an ENOTCONN to be thrown. However the
2342 // socket is really connected, so treat ENOTCONN as a EAGAIN until
2343 // this bug is fixed.
2344 tryAgain |= (errno == ENOTCONN);
2346 if (!writeResult.exception && tryAgain) {
2347 // TCP buffer is full; we can't write any more data right now.
2349 *partialWritten = 0;
2350 return WriteResult(0);
2354 *partialWritten = 0;
2358 appBytesWritten_ += totalWritten;
2360 uint32_t bytesWritten;
2362 for (bytesWritten = uint32_t(totalWritten), n = 0; n < count; ++n) {
2363 const iovec* v = vec + n;
2364 if (v->iov_len > bytesWritten) {
2365 // Partial write finished in the middle of this iovec
2367 *partialWritten = bytesWritten;
2368 return WriteResult(totalWritten);
2371 bytesWritten -= uint32_t(v->iov_len);
2374 assert(bytesWritten == 0);
2376 *partialWritten = 0;
2377 return WriteResult(totalWritten);
2381 * Re-register the EventHandler after eventFlags_ has changed.
2383 * If an error occurs, fail() is called to move the socket into the error state
2384 * and call all currently installed callbacks. After an error, the
2385 * AsyncSocket is completely unregistered.
2387 * @return Returns true on success, or false on error.
2389 bool AsyncSocket::updateEventRegistration() {
2390 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
2391 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
2392 << ", events=" << std::hex << eventFlags_;
2393 eventBase_->dcheckIsInEventBaseThread();
2394 if (eventFlags_ == EventHandler::NONE) {
2395 ioHandler_.unregisterHandler();
2399 // Always register for persistent events, so we don't have to re-register
2400 // after being called back.
2401 if (!ioHandler_.registerHandler(
2402 uint16_t(eventFlags_ | EventHandler::PERSIST))) {
2403 eventFlags_ = EventHandler::NONE; // we're not registered after error
2404 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
2405 withAddr("failed to update AsyncSocket event registration"));
2406 fail("updateEventRegistration", ex);
2413 bool AsyncSocket::updateEventRegistration(uint16_t enable,
2415 uint16_t oldFlags = eventFlags_;
2416 eventFlags_ |= enable;
2417 eventFlags_ &= ~disable;
2418 if (eventFlags_ == oldFlags) {
2421 return updateEventRegistration();
2425 void AsyncSocket::startFail() {
2426 // startFail() should only be called once
2427 assert(state_ != StateEnum::ERROR);
2428 assert(getDestructorGuardCount() > 0);
2429 state_ = StateEnum::ERROR;
2430 // Ensure that SHUT_READ and SHUT_WRITE are set,
2431 // so all future attempts to read or write will be rejected
2432 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
2434 if (eventFlags_ != EventHandler::NONE) {
2435 eventFlags_ = EventHandler::NONE;
2436 ioHandler_.unregisterHandler();
2438 writeTimeout_.cancelTimeout();
2441 ioHandler_.changeHandlerFD(-1);
2446 void AsyncSocket::invokeAllErrors(const AsyncSocketException& ex) {
2447 invokeConnectErr(ex);
2450 if (readCallback_) {
2451 ReadCallback* callback = readCallback_;
2452 readCallback_ = nullptr;
2453 callback->readErr(ex);
2457 void AsyncSocket::finishFail() {
2458 assert(state_ == StateEnum::ERROR);
2459 assert(getDestructorGuardCount() > 0);
2461 AsyncSocketException ex(
2462 AsyncSocketException::INTERNAL_ERROR,
2463 withAddr("socket closing after error"));
2464 invokeAllErrors(ex);
2467 void AsyncSocket::finishFail(const AsyncSocketException& ex) {
2468 assert(state_ == StateEnum::ERROR);
2469 assert(getDestructorGuardCount() > 0);
2470 invokeAllErrors(ex);
2473 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
2474 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2475 << state_ << " host=" << addr_.describe()
2476 << "): failed in " << fn << "(): "
2482 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
2483 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2484 << state_ << " host=" << addr_.describe()
2485 << "): failed while connecting in " << fn << "(): "
2489 invokeConnectErr(ex);
2493 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
2494 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2495 << state_ << " host=" << addr_.describe()
2496 << "): failed while reading in " << fn << "(): "
2500 if (readCallback_ != nullptr) {
2501 ReadCallback* callback = readCallback_;
2502 readCallback_ = nullptr;
2503 callback->readErr(ex);
2509 void AsyncSocket::failErrMessageRead(const char* fn,
2510 const AsyncSocketException& ex) {
2511 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2512 << state_ << " host=" << addr_.describe()
2513 << "): failed while reading message in " << fn << "(): "
2517 if (errMessageCallback_ != nullptr) {
2518 ErrMessageCallback* callback = errMessageCallback_;
2519 errMessageCallback_ = nullptr;
2520 callback->errMessageError(ex);
2526 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
2527 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2528 << state_ << " host=" << addr_.describe()
2529 << "): failed while writing in " << fn << "(): "
2533 // Only invoke the first write callback, since the error occurred while
2534 // writing this request. Let any other pending write callbacks be invoked in
2536 if (writeReqHead_ != nullptr) {
2537 WriteRequest* req = writeReqHead_;
2538 writeReqHead_ = req->getNext();
2539 WriteCallback* callback = req->getCallback();
2540 uint32_t bytesWritten = req->getTotalBytesWritten();
2543 callback->writeErr(bytesWritten, ex);
2550 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
2551 size_t bytesWritten,
2552 const AsyncSocketException& ex) {
2553 // This version of failWrite() is used when the failure occurs before
2554 // we've added the callback to writeReqHead_.
2555 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2556 << state_ << " host=" << addr_.describe()
2557 <<"): failed while writing in " << fn << "(): "
2561 if (callback != nullptr) {
2562 callback->writeErr(bytesWritten, ex);
2568 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
2569 // Invoke writeError() on all write callbacks.
2570 // This is used when writes are forcibly shutdown with write requests
2571 // pending, or when an error occurs with writes pending.
2572 while (writeReqHead_ != nullptr) {
2573 WriteRequest* req = writeReqHead_;
2574 writeReqHead_ = req->getNext();
2575 WriteCallback* callback = req->getCallback();
2577 callback->writeErr(req->getTotalBytesWritten(), ex);
2583 void AsyncSocket::invalidState(ConnectCallback* callback) {
2584 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2585 << "): connect() called in invalid state " << state_;
2588 * The invalidState() methods don't use the normal failure mechanisms,
2589 * since we don't know what state we are in. We don't want to call
2590 * startFail()/finishFail() recursively if we are already in the middle of
2594 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
2595 "connect() called with socket in invalid state");
2596 connectEndTime_ = std::chrono::steady_clock::now();
2597 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2599 callback->connectErr(ex);
2602 // We can't use failConnect() here since connectCallback_
2603 // may already be set to another callback. Invoke this ConnectCallback
2604 // here; any other connectCallback_ will be invoked in finishFail()
2607 callback->connectErr(ex);
2613 void AsyncSocket::invalidState(ErrMessageCallback* callback) {
2614 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2615 << "): setErrMessageCB(" << callback
2616 << ") called in invalid state " << state_;
2618 AsyncSocketException ex(
2619 AsyncSocketException::NOT_OPEN,
2620 msgErrQueueSupported
2621 ? "setErrMessageCB() called with socket in invalid state"
2622 : "This platform does not support socket error message notifications");
2623 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2625 callback->errMessageError(ex);
2630 callback->errMessageError(ex);
2636 void AsyncSocket::invokeConnectErr(const AsyncSocketException& ex) {
2637 connectEndTime_ = std::chrono::steady_clock::now();
2638 if (connectCallback_) {
2639 ConnectCallback* callback = connectCallback_;
2640 connectCallback_ = nullptr;
2641 callback->connectErr(ex);
2645 void AsyncSocket::invokeConnectSuccess() {
2646 connectEndTime_ = std::chrono::steady_clock::now();
2647 if (connectCallback_) {
2648 ConnectCallback* callback = connectCallback_;
2649 connectCallback_ = nullptr;
2650 callback->connectSuccess();
2654 void AsyncSocket::invalidState(ReadCallback* callback) {
2655 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2656 << "): setReadCallback(" << callback
2657 << ") called in invalid state " << state_;
2659 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2660 "setReadCallback() called with socket in "
2662 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2664 callback->readErr(ex);
2669 callback->readErr(ex);
2675 void AsyncSocket::invalidState(WriteCallback* callback) {
2676 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2677 << "): write() called in invalid state " << state_;
2679 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2680 withAddr("write() called with socket in invalid state"));
2681 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2683 callback->writeErr(0, ex);
2688 callback->writeErr(0, ex);
2694 void AsyncSocket::doClose() {
2698 if (const auto shutdownSocketSet = wShutdownSocketSet_.lock()) {
2699 shutdownSocketSet->close(fd_);
2706 std::ostream& operator << (std::ostream& os,
2707 const AsyncSocket::StateEnum& state) {
2708 os << static_cast<int>(state);
2712 std::string AsyncSocket::withAddr(const std::string& s) {
2713 // Don't use addr_ directly because it may not be initialized
2714 // e.g. if constructed from fd
2715 folly::SocketAddress peer, local;
2717 getPeerAddress(&peer);
2718 getLocalAddress(&local);
2719 } catch (const std::exception&) {
2724 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";
2727 void AsyncSocket::setBufferCallback(BufferCallback* cb) {
2728 bufferCallback_ = cb;
2731 } // namespace folly