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 shutdownSocketSet_ = nullptr;
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 (shutdownSocketSet_) {
340 shutdownSocketSet_->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(ShutdownSocketSet* newSS) {
359 if (shutdownSocketSet_ == newSS) {
362 if (shutdownSocketSet_ && fd_ != -1) {
363 shutdownSocketSet_->remove(fd_);
365 shutdownSocketSet_ = newSS;
366 if (shutdownSocketSet_ && fd_ != -1) {
367 shutdownSocketSet_->add(fd_);
371 void AsyncSocket::setCloseOnExec() {
372 int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
374 auto errnoCopy = errno;
375 throw AsyncSocketException(
376 AsyncSocketException::INTERNAL_ERROR,
377 withAddr("failed to set close-on-exec flag"),
382 void AsyncSocket::connect(ConnectCallback* callback,
383 const folly::SocketAddress& address,
385 const OptionMap &options,
386 const folly::SocketAddress& bindAddr) noexcept {
387 DestructorGuard dg(this);
388 eventBase_->dcheckIsInEventBaseThread();
392 // Make sure we're in the uninitialized state
393 if (state_ != StateEnum::UNINIT) {
394 return invalidState(callback);
397 connectTimeout_ = std::chrono::milliseconds(timeout);
398 connectStartTime_ = std::chrono::steady_clock::now();
399 // Make connect end time at least >= connectStartTime.
400 connectEndTime_ = connectStartTime_;
403 state_ = StateEnum::CONNECTING;
404 connectCallback_ = callback;
406 sockaddr_storage addrStorage;
407 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
411 // Technically the first parameter should actually be a protocol family
412 // constant (PF_xxx) rather than an address family (AF_xxx), but the
413 // distinction is mainly just historical. In pretty much all
414 // implementations the PF_foo and AF_foo constants are identical.
415 fd_ = fsp::socket(address.getFamily(), SOCK_STREAM, 0);
417 auto errnoCopy = errno;
418 throw AsyncSocketException(
419 AsyncSocketException::INTERNAL_ERROR,
420 withAddr("failed to create socket"),
423 if (shutdownSocketSet_) {
424 shutdownSocketSet_->add(fd_);
426 ioHandler_.changeHandlerFD(fd_);
430 // Put the socket in non-blocking mode
431 int flags = fcntl(fd_, F_GETFL, 0);
433 auto errnoCopy = errno;
434 throw AsyncSocketException(
435 AsyncSocketException::INTERNAL_ERROR,
436 withAddr("failed to get socket flags"),
439 int rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
441 auto errnoCopy = errno;
442 throw AsyncSocketException(
443 AsyncSocketException::INTERNAL_ERROR,
444 withAddr("failed to put socket in non-blocking mode"),
448 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
449 // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
450 rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
452 auto errnoCopy = errno;
453 throw AsyncSocketException(
454 AsyncSocketException::INTERNAL_ERROR,
455 "failed to enable F_SETNOSIGPIPE on socket",
460 // By default, turn on TCP_NODELAY
461 // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
462 // setNoDelay() will log an error message if it fails.
463 // Also set the cached zeroCopyVal_ since it cannot be set earlier if the fd
465 if (address.getFamily() != AF_UNIX) {
466 (void)setNoDelay(true);
467 setZeroCopy(zeroCopyVal_);
470 VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
471 << ", fd=" << fd_ << ", host=" << address.describe().c_str();
474 if (bindAddr != anyAddress()) {
476 if (setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
477 auto errnoCopy = errno;
479 throw AsyncSocketException(
480 AsyncSocketException::NOT_OPEN,
481 "failed to setsockopt prior to bind on " + bindAddr.describe(),
485 bindAddr.getAddress(&addrStorage);
487 if (bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
488 auto errnoCopy = errno;
490 throw AsyncSocketException(
491 AsyncSocketException::NOT_OPEN,
492 "failed to bind to async socket: " + bindAddr.describe(),
497 // Apply the additional options if any.
498 for (const auto& opt: options) {
499 rv = opt.first.apply(fd_, opt.second);
501 auto errnoCopy = errno;
502 throw AsyncSocketException(
503 AsyncSocketException::INTERNAL_ERROR,
504 withAddr("failed to set socket option"),
509 // Perform the connect()
510 address.getAddress(&addrStorage);
513 state_ = StateEnum::FAST_OPEN;
514 tfoAttempted_ = true;
516 if (socketConnect(saddr, addr_.getActualSize()) < 0) {
521 // If we're still here the connect() succeeded immediately.
522 // Fall through to call the callback outside of this try...catch block
523 } catch (const AsyncSocketException& ex) {
524 return failConnect(__func__, ex);
525 } catch (const std::exception& ex) {
526 // shouldn't happen, but handle it just in case
527 VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
528 << "): unexpected " << typeid(ex).name() << " exception: "
530 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
531 withAddr(string("unexpected exception: ") +
533 return failConnect(__func__, tex);
536 // The connection succeeded immediately
537 // The read callback may not have been set yet, and no writes may be pending
538 // yet, so we don't have to register for any events at the moment.
539 VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
540 assert(errMessageCallback_ == nullptr);
541 assert(readCallback_ == nullptr);
542 assert(writeReqHead_ == nullptr);
543 if (state_ != StateEnum::FAST_OPEN) {
544 state_ = StateEnum::ESTABLISHED;
546 invokeConnectSuccess();
549 int AsyncSocket::socketConnect(const struct sockaddr* saddr, socklen_t len) {
551 if (noTransparentTls_) {
552 // Ignore return value, errors are ok
553 setsockopt(fd_, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0);
556 VLOG(4) << "Disabling TSOCKS for fd " << fd_;
557 // Ignore return value, errors are ok
558 setsockopt(fd_, SOL_SOCKET, SO_NO_TSOCKS, nullptr, 0);
561 int rv = fsp::connect(fd_, saddr, len);
563 auto errnoCopy = errno;
564 if (errnoCopy == EINPROGRESS) {
565 scheduleConnectTimeout();
566 registerForConnectEvents();
568 throw AsyncSocketException(
569 AsyncSocketException::NOT_OPEN,
570 "connect failed (immediately)",
577 void AsyncSocket::scheduleConnectTimeout() {
578 // Connection in progress.
579 auto timeout = connectTimeout_.count();
581 // Start a timer in case the connection takes too long.
582 if (!writeTimeout_.scheduleTimeout(uint32_t(timeout))) {
583 throw AsyncSocketException(
584 AsyncSocketException::INTERNAL_ERROR,
585 withAddr("failed to schedule AsyncSocket connect timeout"));
590 void AsyncSocket::registerForConnectEvents() {
591 // Register for write events, so we'll
592 // be notified when the connection finishes/fails.
593 // Note that we don't register for a persistent event here.
594 assert(eventFlags_ == EventHandler::NONE);
595 eventFlags_ = EventHandler::WRITE;
596 if (!ioHandler_.registerHandler(eventFlags_)) {
597 throw AsyncSocketException(
598 AsyncSocketException::INTERNAL_ERROR,
599 withAddr("failed to register AsyncSocket connect handler"));
603 void AsyncSocket::connect(ConnectCallback* callback,
604 const string& ip, uint16_t port,
606 const OptionMap &options) noexcept {
607 DestructorGuard dg(this);
609 connectCallback_ = callback;
610 connect(callback, folly::SocketAddress(ip, port), timeout, options);
611 } catch (const std::exception& ex) {
612 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
614 return failConnect(__func__, tex);
618 void AsyncSocket::cancelConnect() {
619 connectCallback_ = nullptr;
620 if (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN) {
625 void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
626 sendTimeout_ = milliseconds;
628 eventBase_->dcheckIsInEventBaseThread();
631 // If we are currently pending on write requests, immediately update
632 // writeTimeout_ with the new value.
633 if ((eventFlags_ & EventHandler::WRITE) &&
634 (state_ != StateEnum::CONNECTING && state_ != StateEnum::FAST_OPEN)) {
635 assert(state_ == StateEnum::ESTABLISHED);
636 assert((shutdownFlags_ & SHUT_WRITE) == 0);
637 if (sendTimeout_ > 0) {
638 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
639 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
640 withAddr("failed to reschedule send timeout in setSendTimeout"));
641 return failWrite(__func__, ex);
644 writeTimeout_.cancelTimeout();
649 void AsyncSocket::setErrMessageCB(ErrMessageCallback* callback) {
650 VLOG(6) << "AsyncSocket::setErrMessageCB() this=" << this
651 << ", fd=" << fd_ << ", callback=" << callback
652 << ", state=" << state_;
654 // Short circuit if callback is the same as the existing errMessageCallback_.
655 if (callback == errMessageCallback_) {
659 if (!msgErrQueueSupported) {
660 // Per-socket error message queue is not supported on this platform.
661 return invalidState(callback);
664 DestructorGuard dg(this);
665 eventBase_->dcheckIsInEventBaseThread();
667 if (callback == nullptr) {
668 // We should be able to reset the callback regardless of the
669 // socket state. It's important to have a reliable callback
670 // cancellation mechanism.
671 errMessageCallback_ = callback;
675 switch ((StateEnum)state_) {
676 case StateEnum::CONNECTING:
677 case StateEnum::FAST_OPEN:
678 case StateEnum::ESTABLISHED: {
679 errMessageCallback_ = callback;
682 case StateEnum::CLOSED:
683 case StateEnum::ERROR:
684 // We should never reach here. SHUT_READ should always be set
685 // if we are in STATE_CLOSED or STATE_ERROR.
687 return invalidState(callback);
688 case StateEnum::UNINIT:
689 // We do not allow setReadCallback() to be called before we start
691 return invalidState(callback);
694 // We don't put a default case in the switch statement, so that the compiler
695 // will warn us to update the switch statement if a new state is added.
696 return invalidState(callback);
699 AsyncSocket::ErrMessageCallback* AsyncSocket::getErrMessageCallback() const {
700 return errMessageCallback_;
703 void AsyncSocket::setSendMsgParamCB(SendMsgParamsCallback* callback) {
704 sendMsgParamCallback_ = callback;
707 AsyncSocket::SendMsgParamsCallback* AsyncSocket::getSendMsgParamsCB() const {
708 return sendMsgParamCallback_;
711 void AsyncSocket::setReadCB(ReadCallback *callback) {
712 VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
713 << ", callback=" << callback << ", state=" << state_;
715 // Short circuit if callback is the same as the existing readCallback_.
717 // Note that this is needed for proper functioning during some cleanup cases.
718 // During cleanup we allow setReadCallback(nullptr) to be called even if the
719 // read callback is already unset and we have been detached from an event
720 // base. This check prevents us from asserting
721 // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
722 if (callback == readCallback_) {
726 /* We are removing a read callback */
727 if (callback == nullptr &&
728 immediateReadHandler_.isLoopCallbackScheduled()) {
729 immediateReadHandler_.cancelLoopCallback();
732 if (shutdownFlags_ & SHUT_READ) {
733 // Reads have already been shut down on this socket.
735 // Allow setReadCallback(nullptr) to be called in this case, but don't
736 // allow a new callback to be set.
738 // For example, setReadCallback(nullptr) can happen after an error if we
739 // invoke some other error callback before invoking readError(). The other
740 // error callback that is invoked first may go ahead and clear the read
741 // callback before we get a chance to invoke readError().
742 if (callback != nullptr) {
743 return invalidState(callback);
745 assert((eventFlags_ & EventHandler::READ) == 0);
746 readCallback_ = nullptr;
750 DestructorGuard dg(this);
751 eventBase_->dcheckIsInEventBaseThread();
753 switch ((StateEnum)state_) {
754 case StateEnum::CONNECTING:
755 case StateEnum::FAST_OPEN:
756 // For convenience, we allow the read callback to be set while we are
757 // still connecting. We just store the callback for now. Once the
758 // connection completes we'll register for read events.
759 readCallback_ = callback;
761 case StateEnum::ESTABLISHED:
763 readCallback_ = callback;
764 uint16_t oldFlags = eventFlags_;
766 eventFlags_ |= EventHandler::READ;
768 eventFlags_ &= ~EventHandler::READ;
771 // Update our registration if our flags have changed
772 if (eventFlags_ != oldFlags) {
773 // We intentionally ignore the return value here.
774 // updateEventRegistration() will move us into the error state if it
775 // fails, and we don't need to do anything else here afterwards.
776 (void)updateEventRegistration();
780 checkForImmediateRead();
784 case StateEnum::CLOSED:
785 case StateEnum::ERROR:
786 // We should never reach here. SHUT_READ should always be set
787 // if we are in STATE_CLOSED or STATE_ERROR.
789 return invalidState(callback);
790 case StateEnum::UNINIT:
791 // We do not allow setReadCallback() to be called before we start
793 return invalidState(callback);
796 // We don't put a default case in the switch statement, so that the compiler
797 // will warn us to update the switch statement if a new state is added.
798 return invalidState(callback);
801 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
802 return readCallback_;
805 bool AsyncSocket::setZeroCopy(bool enable) {
806 if (msgErrQueueSupported) {
807 zeroCopyVal_ = enable;
813 int val = enable ? 1 : 0;
814 int ret = setsockopt(fd_, SOL_SOCKET, SO_ZEROCOPY, &val, sizeof(val));
816 // if enable == false, set zeroCopyEnabled_ = false regardless
817 // if SO_ZEROCOPY is set or not
819 zeroCopyEnabled_ = enable;
823 /* if the setsockopt failed, try to see if the socket inherited the flag
824 * since we cannot set SO_ZEROCOPY on a socket s = accept
828 socklen_t optlen = sizeof(val);
829 ret = getsockopt(fd_, SOL_SOCKET, SO_ZEROCOPY, &val, &optlen);
832 enable = val ? true : false;
837 zeroCopyEnabled_ = enable;
846 void AsyncSocket::setZeroCopyWriteChainThreshold(size_t threshold) {
847 zeroCopyWriteChainThreshold_ = threshold;
850 bool AsyncSocket::isZeroCopyRequest(WriteFlags flags) {
851 return (zeroCopyEnabled_ && isSet(flags, WriteFlags::WRITE_MSG_ZEROCOPY));
854 void AsyncSocket::adjustZeroCopyFlags(
856 folly::WriteFlags& flags) {
857 if (zeroCopyEnabled_ && zeroCopyWriteChainThreshold_ && buf) {
858 if (buf->computeChainDataLength() >= zeroCopyWriteChainThreshold_) {
859 flags |= folly::WriteFlags::WRITE_MSG_ZEROCOPY;
861 flags = unSet(flags, folly::WriteFlags::WRITE_MSG_ZEROCOPY);
866 void AsyncSocket::adjustZeroCopyFlags(
869 folly::WriteFlags& flags) {
870 if (zeroCopyEnabled_ && zeroCopyWriteChainThreshold_) {
871 count = std::min<uint32_t>(count, kIovMax);
873 for (uint32_t i = 0; i < count; ++i) {
874 const iovec* v = vec + i;
878 if (sum >= zeroCopyWriteChainThreshold_) {
879 flags |= folly::WriteFlags::WRITE_MSG_ZEROCOPY;
881 flags = unSet(flags, folly::WriteFlags::WRITE_MSG_ZEROCOPY);
886 void AsyncSocket::addZeroCopyBuff(std::unique_ptr<folly::IOBuf>&& buf) {
887 uint32_t id = getNextZeroCopyBuffId();
888 folly::IOBuf* ptr = buf.get();
890 idZeroCopyBufPtrMap_[id] = ptr;
891 auto& p = idZeroCopyBufPtrToBufMap_[ptr];
893 CHECK(p.second.get() == nullptr);
894 p.second = std::move(buf);
897 void AsyncSocket::addZeroCopyBuff(folly::IOBuf* ptr) {
898 uint32_t id = getNextZeroCopyBuffId();
899 idZeroCopyBufPtrMap_[id] = ptr;
901 idZeroCopyBufPtrToBufMap_[ptr].first++;
904 void AsyncSocket::releaseZeroCopyBuff(uint32_t id) {
905 auto iter = idZeroCopyBufPtrMap_.find(id);
906 CHECK(iter != idZeroCopyBufPtrMap_.end());
907 auto ptr = iter->second;
908 auto iter1 = idZeroCopyBufPtrToBufMap_.find(ptr);
909 CHECK(iter1 != idZeroCopyBufPtrToBufMap_.end());
910 if (0 == --iter1->second.first) {
911 idZeroCopyBufPtrToBufMap_.erase(iter1);
915 void AsyncSocket::setZeroCopyBuff(std::unique_ptr<folly::IOBuf>&& buf) {
916 folly::IOBuf* ptr = buf.get();
917 auto& p = idZeroCopyBufPtrToBufMap_[ptr];
918 CHECK(p.second.get() == nullptr);
920 p.second = std::move(buf);
923 bool AsyncSocket::containsZeroCopyBuff(folly::IOBuf* ptr) {
925 idZeroCopyBufPtrToBufMap_.find(ptr) != idZeroCopyBufPtrToBufMap_.end());
928 bool AsyncSocket::isZeroCopyMsg(const cmsghdr& cmsg) const {
930 if (zeroCopyEnabled_ &&
931 ((cmsg.cmsg_level == SOL_IP && cmsg.cmsg_type == IP_RECVERR) ||
932 (cmsg.cmsg_level == SOL_IPV6 && cmsg.cmsg_type == IPV6_RECVERR))) {
933 const struct sock_extended_err* serr =
934 reinterpret_cast<const struct sock_extended_err*>(CMSG_DATA(&cmsg));
936 (serr->ee_errno == 0) && (serr->ee_origin == SO_EE_ORIGIN_ZEROCOPY));
942 void AsyncSocket::processZeroCopyMsg(const cmsghdr& cmsg) {
944 const struct sock_extended_err* serr =
945 reinterpret_cast<const struct sock_extended_err*>(CMSG_DATA(&cmsg));
946 uint32_t hi = serr->ee_data;
947 uint32_t lo = serr->ee_info;
949 for (uint32_t i = lo; i <= hi; i++) {
950 releaseZeroCopyBuff(i);
955 void AsyncSocket::write(WriteCallback* callback,
956 const void* buf, size_t bytes, WriteFlags flags) {
958 op.iov_base = const_cast<void*>(buf);
960 writeImpl(callback, &op, 1, unique_ptr<IOBuf>(), flags);
963 void AsyncSocket::writev(WriteCallback* callback,
967 writeImpl(callback, vec, count, unique_ptr<IOBuf>(), flags);
970 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
972 adjustZeroCopyFlags(buf.get(), flags);
974 constexpr size_t kSmallSizeMax = 64;
975 size_t count = buf->countChainElements();
976 if (count <= kSmallSizeMax) {
977 // suppress "warning: variable length array 'vec' is used [-Wvla]"
979 FOLLY_GCC_DISABLE_WARNING("-Wvla")
980 iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA, count, kSmallSizeMax)];
983 writeChainImpl(callback, vec, count, std::move(buf), flags);
985 iovec* vec = new iovec[count];
986 writeChainImpl(callback, vec, count, std::move(buf), flags);
991 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
992 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
993 size_t veclen = buf->fillIov(vec, count);
994 writeImpl(callback, vec, veclen, std::move(buf), flags);
997 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
998 size_t count, unique_ptr<IOBuf>&& buf,
1000 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
1001 << ", callback=" << callback << ", count=" << count
1002 << ", state=" << state_;
1003 DestructorGuard dg(this);
1004 unique_ptr<IOBuf>ioBuf(std::move(buf));
1005 eventBase_->dcheckIsInEventBaseThread();
1007 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
1008 // No new writes may be performed after the write side of the socket has
1011 // We could just call callback->writeError() here to fail just this write.
1012 // However, fail hard and use invalidState() to fail all outstanding
1013 // callbacks and move the socket into the error state. There's most likely
1014 // a bug in the caller's code, so we abort everything rather than trying to
1015 // proceed as best we can.
1016 return invalidState(callback);
1019 uint32_t countWritten = 0;
1020 uint32_t partialWritten = 0;
1021 ssize_t bytesWritten = 0;
1022 bool mustRegister = false;
1023 if ((state_ == StateEnum::ESTABLISHED || state_ == StateEnum::FAST_OPEN) &&
1025 if (writeReqHead_ == nullptr) {
1026 // If we are established and there are no other writes pending,
1027 // we can attempt to perform the write immediately.
1028 assert(writeReqTail_ == nullptr);
1029 assert((eventFlags_ & EventHandler::WRITE) == 0);
1031 auto writeResult = performWrite(
1032 vec, uint32_t(count), flags, &countWritten, &partialWritten);
1033 bytesWritten = writeResult.writeReturn;
1034 if (bytesWritten < 0) {
1035 auto errnoCopy = errno;
1036 if (writeResult.exception) {
1037 return failWrite(__func__, callback, 0, *writeResult.exception);
1039 AsyncSocketException ex(
1040 AsyncSocketException::INTERNAL_ERROR,
1041 withAddr("writev failed"),
1043 return failWrite(__func__, callback, 0, ex);
1044 } else if (countWritten == count) {
1045 // done, add the whole buffer
1046 if (isZeroCopyRequest(flags)) {
1047 addZeroCopyBuff(std::move(ioBuf));
1049 // We successfully wrote everything.
1050 // Invoke the callback and return.
1052 callback->writeSuccess();
1055 } else { // continue writing the next writeReq
1057 if (isZeroCopyRequest(flags)) {
1058 addZeroCopyBuff(ioBuf.get());
1060 if (bufferCallback_) {
1061 bufferCallback_->onEgressBuffered();
1064 if (!connecting()) {
1065 // Writes might put the socket back into connecting state
1066 // if TFO is enabled, and using TFO fails.
1067 // This means that write timeouts would not be active, however
1068 // connect timeouts would affect this stage.
1069 mustRegister = true;
1072 } else if (!connecting()) {
1073 // Invalid state for writing
1074 return invalidState(callback);
1077 // Create a new WriteRequest to add to the queue
1080 req = BytesWriteRequest::newRequest(
1084 uint32_t(count - countWritten),
1086 uint32_t(bytesWritten),
1089 } catch (const std::exception& ex) {
1090 // we mainly expect to catch std::bad_alloc here
1091 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
1092 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
1093 return failWrite(__func__, callback, size_t(bytesWritten), tex);
1096 if (writeReqTail_ == nullptr) {
1097 assert(writeReqHead_ == nullptr);
1098 writeReqHead_ = writeReqTail_ = req;
1100 writeReqTail_->append(req);
1101 writeReqTail_ = req;
1104 // Register for write events if are established and not currently
1105 // waiting on write events
1107 assert(state_ == StateEnum::ESTABLISHED);
1108 assert((eventFlags_ & EventHandler::WRITE) == 0);
1109 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1110 assert(state_ == StateEnum::ERROR);
1113 if (sendTimeout_ > 0) {
1114 // Schedule a timeout to fire if the write takes too long.
1115 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1116 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1117 withAddr("failed to schedule send timeout"));
1118 return failWrite(__func__, ex);
1124 void AsyncSocket::writeRequest(WriteRequest* req) {
1125 if (writeReqTail_ == nullptr) {
1126 assert(writeReqHead_ == nullptr);
1127 writeReqHead_ = writeReqTail_ = req;
1130 writeReqTail_->append(req);
1131 writeReqTail_ = req;
1135 void AsyncSocket::close() {
1136 VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
1137 << ", state=" << state_ << ", shutdownFlags="
1138 << std::hex << (int) shutdownFlags_;
1140 // close() is only different from closeNow() when there are pending writes
1141 // that need to drain before we can close. In all other cases, just call
1144 // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
1145 // STATE_ERROR if close() is invoked while a previous closeNow() or failure
1146 // is still running. (e.g., If there are multiple pending writes, and we
1147 // call writeError() on the first one, it may call close(). In this case we
1148 // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
1149 // writes will still be in the queue.)
1151 // We only need to drain pending writes if we are still in STATE_CONNECTING
1152 // or STATE_ESTABLISHED
1153 if ((writeReqHead_ == nullptr) ||
1154 !(state_ == StateEnum::CONNECTING ||
1155 state_ == StateEnum::ESTABLISHED)) {
1160 // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
1161 // destroyed until close() returns.
1162 DestructorGuard dg(this);
1163 eventBase_->dcheckIsInEventBaseThread();
1165 // Since there are write requests pending, we have to set the
1166 // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
1167 // connect finishes and we finish writing these requests.
1169 // Set SHUT_READ to indicate that reads are shut down, and set the
1170 // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
1171 // pending writes complete.
1172 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
1174 // If a read callback is set, invoke readEOF() immediately to inform it that
1175 // the socket has been closed and no more data can be read.
1176 if (readCallback_) {
1177 // Disable reads if they are enabled
1178 if (!updateEventRegistration(0, EventHandler::READ)) {
1179 // We're now in the error state; callbacks have been cleaned up
1180 assert(state_ == StateEnum::ERROR);
1181 assert(readCallback_ == nullptr);
1183 ReadCallback* callback = readCallback_;
1184 readCallback_ = nullptr;
1185 callback->readEOF();
1190 void AsyncSocket::closeNow() {
1191 VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
1192 << ", state=" << state_ << ", shutdownFlags="
1193 << std::hex << (int) shutdownFlags_;
1194 DestructorGuard dg(this);
1196 eventBase_->dcheckIsInEventBaseThread();
1200 case StateEnum::ESTABLISHED:
1201 case StateEnum::CONNECTING:
1202 case StateEnum::FAST_OPEN: {
1203 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1204 state_ = StateEnum::CLOSED;
1206 // If the write timeout was set, cancel it.
1207 writeTimeout_.cancelTimeout();
1209 // If we are registered for I/O events, unregister.
1210 if (eventFlags_ != EventHandler::NONE) {
1211 eventFlags_ = EventHandler::NONE;
1212 if (!updateEventRegistration()) {
1213 // We will have been moved into the error state.
1214 assert(state_ == StateEnum::ERROR);
1219 if (immediateReadHandler_.isLoopCallbackScheduled()) {
1220 immediateReadHandler_.cancelLoopCallback();
1224 ioHandler_.changeHandlerFD(-1);
1228 invokeConnectErr(socketClosedLocallyEx);
1230 failAllWrites(socketClosedLocallyEx);
1232 if (readCallback_) {
1233 ReadCallback* callback = readCallback_;
1234 readCallback_ = nullptr;
1235 callback->readEOF();
1239 case StateEnum::CLOSED:
1240 // Do nothing. It's possible that we are being called recursively
1241 // from inside a callback that we invoked inside another call to close()
1242 // that is still running.
1244 case StateEnum::ERROR:
1245 // Do nothing. The error handling code has performed (or is performing)
1248 case StateEnum::UNINIT:
1249 assert(eventFlags_ == EventHandler::NONE);
1250 assert(connectCallback_ == nullptr);
1251 assert(readCallback_ == nullptr);
1252 assert(writeReqHead_ == nullptr);
1253 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1254 state_ = StateEnum::CLOSED;
1258 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
1259 << ") called in unknown state " << state_;
1262 void AsyncSocket::closeWithReset() {
1263 // Enable SO_LINGER, with the linger timeout set to 0.
1264 // This will trigger a TCP reset when we close the socket.
1266 struct linger optLinger = {1, 0};
1267 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
1268 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
1269 << "on " << fd_ << ": errno=" << errno;
1273 // Then let closeNow() take care of the rest
1277 void AsyncSocket::shutdownWrite() {
1278 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
1279 << ", state=" << state_ << ", shutdownFlags="
1280 << std::hex << (int) shutdownFlags_;
1282 // If there are no pending writes, shutdownWrite() is identical to
1283 // shutdownWriteNow().
1284 if (writeReqHead_ == nullptr) {
1289 eventBase_->dcheckIsInEventBaseThread();
1291 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
1292 // shutdown will be performed once all writes complete.
1293 shutdownFlags_ |= SHUT_WRITE_PENDING;
1296 void AsyncSocket::shutdownWriteNow() {
1297 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
1298 << ", fd=" << fd_ << ", state=" << state_
1299 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
1301 if (shutdownFlags_ & SHUT_WRITE) {
1302 // Writes are already shutdown; nothing else to do.
1306 // If SHUT_READ is already set, just call closeNow() to completely
1307 // close the socket. This can happen if close() was called with writes
1308 // pending, and then shutdownWriteNow() is called before all pending writes
1310 if (shutdownFlags_ & SHUT_READ) {
1315 DestructorGuard dg(this);
1317 eventBase_->dcheckIsInEventBaseThread();
1320 switch (static_cast<StateEnum>(state_)) {
1321 case StateEnum::ESTABLISHED:
1323 shutdownFlags_ |= SHUT_WRITE;
1325 // If the write timeout was set, cancel it.
1326 writeTimeout_.cancelTimeout();
1328 // If we are registered for write events, unregister.
1329 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1330 // We will have been moved into the error state.
1331 assert(state_ == StateEnum::ERROR);
1335 // Shutdown writes on the file descriptor
1336 shutdown(fd_, SHUT_WR);
1338 // Immediately fail all write requests
1339 failAllWrites(socketShutdownForWritesEx);
1342 case StateEnum::CONNECTING:
1344 // Set the SHUT_WRITE_PENDING flag.
1345 // When the connection completes, it will check this flag,
1346 // shutdown the write half of the socket, and then set SHUT_WRITE.
1347 shutdownFlags_ |= SHUT_WRITE_PENDING;
1349 // Immediately fail all write requests
1350 failAllWrites(socketShutdownForWritesEx);
1353 case StateEnum::UNINIT:
1354 // Callers normally shouldn't call shutdownWriteNow() before the socket
1355 // even starts connecting. Nonetheless, go ahead and set
1356 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
1357 // immediately shut down the write side of the socket.
1358 shutdownFlags_ |= SHUT_WRITE_PENDING;
1360 case StateEnum::FAST_OPEN:
1361 // In fast open state we haven't call connected yet, and if we shutdown
1362 // the writes, we will never try to call connect, so shut everything down
1363 shutdownFlags_ |= SHUT_WRITE;
1364 // Immediately fail all write requests
1365 failAllWrites(socketShutdownForWritesEx);
1367 case StateEnum::CLOSED:
1368 case StateEnum::ERROR:
1369 // We should never get here. SHUT_WRITE should always be set
1370 // in STATE_CLOSED and STATE_ERROR.
1371 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
1372 << ", fd=" << fd_ << ") in unexpected state " << state_
1373 << " with SHUT_WRITE not set ("
1374 << std::hex << (int) shutdownFlags_ << ")";
1379 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
1380 << fd_ << ") called in unknown state " << state_;
1383 bool AsyncSocket::readable() const {
1387 struct pollfd fds[1];
1389 fds[0].events = POLLIN;
1391 int rc = poll(fds, 1, 0);
1395 bool AsyncSocket::writable() const {
1399 struct pollfd fds[1];
1401 fds[0].events = POLLOUT;
1403 int rc = poll(fds, 1, 0);
1407 bool AsyncSocket::isPending() const {
1408 return ioHandler_.isPending();
1411 bool AsyncSocket::hangup() const {
1413 // sanity check, no one should ask for hangup if we are not connected.
1417 #ifdef POLLRDHUP // Linux-only
1418 struct pollfd fds[1];
1420 fds[0].events = POLLRDHUP|POLLHUP;
1423 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1429 bool AsyncSocket::good() const {
1431 (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN ||
1432 state_ == StateEnum::ESTABLISHED) &&
1433 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1436 bool AsyncSocket::error() const {
1437 return (state_ == StateEnum::ERROR);
1440 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1441 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1442 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1443 << ", state=" << state_ << ", events="
1444 << std::hex << eventFlags_ << ")";
1445 assert(eventBase_ == nullptr);
1446 eventBase->dcheckIsInEventBaseThread();
1448 eventBase_ = eventBase;
1449 ioHandler_.attachEventBase(eventBase);
1450 writeTimeout_.attachEventBase(eventBase);
1452 evbChangeCb_->evbAttached(this);
1456 void AsyncSocket::detachEventBase() {
1457 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1458 << ", old evb=" << eventBase_ << ", state=" << state_
1459 << ", events=" << std::hex << eventFlags_ << ")";
1460 assert(eventBase_ != nullptr);
1461 eventBase_->dcheckIsInEventBaseThread();
1463 eventBase_ = nullptr;
1464 ioHandler_.detachEventBase();
1465 writeTimeout_.detachEventBase();
1467 evbChangeCb_->evbDetached(this);
1471 bool AsyncSocket::isDetachable() const {
1472 DCHECK(eventBase_ != nullptr);
1473 eventBase_->dcheckIsInEventBaseThread();
1475 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1478 void AsyncSocket::cacheAddresses() {
1481 cacheLocalAddress();
1483 } catch (const std::system_error& e) {
1484 if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
1485 VLOG(1) << "Error caching addresses: " << e.code().value() << ", "
1486 << e.code().message();
1492 void AsyncSocket::cacheLocalAddress() const {
1493 if (!localAddr_.isInitialized()) {
1494 localAddr_.setFromLocalAddress(fd_);
1498 void AsyncSocket::cachePeerAddress() const {
1499 if (!addr_.isInitialized()) {
1500 addr_.setFromPeerAddress(fd_);
1504 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1505 cacheLocalAddress();
1506 *address = localAddr_;
1509 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1514 bool AsyncSocket::getTFOSucceded() const {
1515 return detail::tfo_succeeded(fd_);
1518 int AsyncSocket::setNoDelay(bool noDelay) {
1520 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1521 << this << "(state=" << state_ << ")";
1526 int value = noDelay ? 1 : 0;
1527 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1528 int errnoCopy = errno;
1529 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1530 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1531 << strerror(errnoCopy);
1538 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1540 #ifndef TCP_CONGESTION
1541 #define TCP_CONGESTION 13
1545 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1546 << "socket " << this << "(state=" << state_ << ")";
1556 socklen_t(cname.length() + 1)) != 0) {
1557 int errnoCopy = errno;
1558 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1559 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1560 << strerror(errnoCopy);
1567 int AsyncSocket::setQuickAck(bool quickack) {
1570 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1571 << this << "(state=" << state_ << ")";
1576 #ifdef TCP_QUICKACK // Linux-only
1577 int value = quickack ? 1 : 0;
1578 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1579 int errnoCopy = errno;
1580 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1581 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1582 << strerror(errnoCopy);
1592 int AsyncSocket::setSendBufSize(size_t bufsize) {
1594 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1595 << this << "(state=" << state_ << ")";
1599 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1600 int errnoCopy = errno;
1601 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1602 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1603 << strerror(errnoCopy);
1610 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1612 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1613 << this << "(state=" << state_ << ")";
1617 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1618 int errnoCopy = errno;
1619 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1620 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1621 << strerror(errnoCopy);
1628 int AsyncSocket::setTCPProfile(int profd) {
1630 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1631 << this << "(state=" << state_ << ")";
1635 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1636 int errnoCopy = errno;
1637 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1638 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1639 << strerror(errnoCopy);
1646 void AsyncSocket::ioReady(uint16_t events) noexcept {
1647 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd=" << fd_
1648 << ", events=" << std::hex << events << ", state=" << state_;
1649 DestructorGuard dg(this);
1650 assert(events & EventHandler::READ_WRITE);
1651 eventBase_->dcheckIsInEventBaseThread();
1653 uint16_t relevantEvents = uint16_t(events & EventHandler::READ_WRITE);
1654 EventBase* originalEventBase = eventBase_;
1655 // If we got there it means that either EventHandler::READ or
1656 // EventHandler::WRITE is set. Any of these flags can
1657 // indicate that there are messages available in the socket
1658 // error message queue.
1659 handleErrMessages();
1661 // Return now if handleErrMessages() detached us from our EventBase
1662 if (eventBase_ != originalEventBase) {
1666 if (relevantEvents == EventHandler::READ) {
1668 } else if (relevantEvents == EventHandler::WRITE) {
1670 } else if (relevantEvents == EventHandler::READ_WRITE) {
1671 // If both read and write events are ready, process writes first.
1674 // Return now if handleWrite() detached us from our EventBase
1675 if (eventBase_ != originalEventBase) {
1679 // Only call handleRead() if a read callback is still installed.
1680 // (It's possible that the read callback was uninstalled during
1682 if (readCallback_) {
1686 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1687 << std::hex << events << "(this=" << this << ")";
1692 AsyncSocket::ReadResult
1693 AsyncSocket::performRead(void** buf, size_t* buflen, size_t* /* offset */) {
1694 VLOG(5) << "AsyncSocket::performRead() this=" << this << ", buf=" << *buf
1695 << ", buflen=" << *buflen;
1697 if (preReceivedData_ && !preReceivedData_->empty()) {
1698 VLOG(5) << "AsyncSocket::performRead() this=" << this
1699 << ", reading pre-received data";
1701 io::Cursor cursor(preReceivedData_.get());
1702 auto len = cursor.pullAtMost(*buf, *buflen);
1705 queue.append(std::move(preReceivedData_));
1706 queue.trimStart(len);
1707 preReceivedData_ = queue.move();
1709 appBytesReceived_ += len;
1710 return ReadResult(len);
1713 ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT);
1715 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1716 // No more data to read right now.
1717 return ReadResult(READ_BLOCKING);
1719 return ReadResult(READ_ERROR);
1722 appBytesReceived_ += bytes;
1723 return ReadResult(bytes);
1727 void AsyncSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1728 // no matter what, buffer should be preapared for non-ssl socket
1729 CHECK(readCallback_);
1730 readCallback_->getReadBuffer(buf, buflen);
1733 void AsyncSocket::handleErrMessages() noexcept {
1734 // This method has non-empty implementation only for platforms
1735 // supporting per-socket error queues.
1736 VLOG(5) << "AsyncSocket::handleErrMessages() this=" << this << ", fd=" << fd_
1737 << ", state=" << state_;
1738 if (errMessageCallback_ == nullptr &&
1739 (!zeroCopyEnabled_ || idZeroCopyBufPtrMap_.empty())) {
1740 VLOG(7) << "AsyncSocket::handleErrMessages(): "
1741 << "no callback installed - exiting.";
1751 entry.iov_base = &data;
1752 entry.iov_len = sizeof(data);
1753 msg.msg_iov = &entry;
1755 msg.msg_name = nullptr;
1756 msg.msg_namelen = 0;
1757 msg.msg_control = ctrl;
1758 msg.msg_controllen = sizeof(ctrl);
1763 ret = recvmsg(fd_, &msg, MSG_ERRQUEUE);
1764 VLOG(5) << "AsyncSocket::handleErrMessages(): recvmsg returned " << ret;
1767 if (errno != EAGAIN) {
1768 auto errnoCopy = errno;
1769 LOG(ERROR) << "::recvmsg exited with code " << ret
1770 << ", errno: " << errnoCopy;
1771 AsyncSocketException ex(
1772 AsyncSocketException::INTERNAL_ERROR,
1773 withAddr("recvmsg() failed"),
1775 failErrMessageRead(__func__, ex);
1780 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
1781 cmsg != nullptr && cmsg->cmsg_len != 0;
1782 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1783 if (isZeroCopyMsg(*cmsg)) {
1784 processZeroCopyMsg(*cmsg);
1786 if (errMessageCallback_) {
1787 errMessageCallback_->errMessage(*cmsg);
1792 #endif //MSG_ERRQUEUE
1795 void AsyncSocket::handleRead() noexcept {
1796 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1797 << ", state=" << state_;
1798 assert(state_ == StateEnum::ESTABLISHED);
1799 assert((shutdownFlags_ & SHUT_READ) == 0);
1800 assert(readCallback_ != nullptr);
1801 assert(eventFlags_ & EventHandler::READ);
1804 // - a read attempt would block
1805 // - readCallback_ is uninstalled
1806 // - the number of loop iterations exceeds the optional maximum
1807 // - this AsyncSocket is moved to another EventBase
1809 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1810 // which is why need to check for it here.
1812 // The last bullet point is slightly subtle. readDataAvailable() may also
1813 // detach this socket from this EventBase. However, before
1814 // readDataAvailable() returns another thread may pick it up, attach it to
1815 // a different EventBase, and install another readCallback_. We need to
1816 // exit immediately after readDataAvailable() returns if the eventBase_ has
1817 // changed. (The caller must perform some sort of locking to transfer the
1818 // AsyncSocket between threads properly. This will be sufficient to ensure
1819 // that this thread sees the updated eventBase_ variable after
1820 // readDataAvailable() returns.)
1821 uint16_t numReads = 0;
1822 EventBase* originalEventBase = eventBase_;
1823 while (readCallback_ && eventBase_ == originalEventBase) {
1824 // Get the buffer to read into.
1825 void* buf = nullptr;
1826 size_t buflen = 0, offset = 0;
1828 prepareReadBuffer(&buf, &buflen);
1829 VLOG(5) << "prepareReadBuffer() buf=" << buf << ", buflen=" << buflen;
1830 } catch (const AsyncSocketException& ex) {
1831 return failRead(__func__, ex);
1832 } catch (const std::exception& ex) {
1833 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1834 string("ReadCallback::getReadBuffer() "
1835 "threw exception: ") +
1837 return failRead(__func__, tex);
1839 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1840 "ReadCallback::getReadBuffer() threw "
1841 "non-exception type");
1842 return failRead(__func__, ex);
1844 if (!isBufferMovable_ && (buf == nullptr || buflen == 0)) {
1845 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1846 "ReadCallback::getReadBuffer() returned "
1848 return failRead(__func__, ex);
1852 auto readResult = performRead(&buf, &buflen, &offset);
1853 auto bytesRead = readResult.readReturn;
1854 VLOG(4) << "this=" << this << ", AsyncSocket::handleRead() got "
1855 << bytesRead << " bytes";
1856 if (bytesRead > 0) {
1857 if (!isBufferMovable_) {
1858 readCallback_->readDataAvailable(size_t(bytesRead));
1860 CHECK(kOpenSslModeMoveBufferOwnership);
1861 VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
1862 << "buf=" << buf << ", " << bytesRead << "/" << buflen
1863 << ", offset=" << offset;
1864 auto readBuf = folly::IOBuf::takeOwnership(buf, buflen);
1865 readBuf->trimStart(offset);
1866 readBuf->trimEnd(buflen - offset - bytesRead);
1867 readCallback_->readBufferAvailable(std::move(readBuf));
1870 // Fall through and continue around the loop if the read
1871 // completely filled the available buffer.
1872 // Note that readCallback_ may have been uninstalled or changed inside
1873 // readDataAvailable().
1874 if (size_t(bytesRead) < buflen) {
1877 } else if (bytesRead == READ_BLOCKING) {
1878 // No more data to read right now.
1880 } else if (bytesRead == READ_ERROR) {
1881 readErr_ = READ_ERROR;
1882 if (readResult.exception) {
1883 return failRead(__func__, *readResult.exception);
1885 auto errnoCopy = errno;
1886 AsyncSocketException ex(
1887 AsyncSocketException::INTERNAL_ERROR,
1888 withAddr("recv() failed"),
1890 return failRead(__func__, ex);
1892 assert(bytesRead == READ_EOF);
1893 readErr_ = READ_EOF;
1895 shutdownFlags_ |= SHUT_READ;
1896 if (!updateEventRegistration(0, EventHandler::READ)) {
1897 // we've already been moved into STATE_ERROR
1898 assert(state_ == StateEnum::ERROR);
1899 assert(readCallback_ == nullptr);
1903 ReadCallback* callback = readCallback_;
1904 readCallback_ = nullptr;
1905 callback->readEOF();
1908 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1909 if (readCallback_ != nullptr) {
1910 // We might still have data in the socket.
1911 // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
1912 scheduleImmediateRead();
1920 * This function attempts to write as much data as possible, until no more data
1923 * - If it sends all available data, it unregisters for write events, and stops
1924 * the writeTimeout_.
1926 * - If not all of the data can be sent immediately, it reschedules
1927 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1928 * registered for write events.
1930 void AsyncSocket::handleWrite() noexcept {
1931 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1932 << ", state=" << state_;
1933 DestructorGuard dg(this);
1935 if (state_ == StateEnum::CONNECTING) {
1941 assert(state_ == StateEnum::ESTABLISHED);
1942 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1943 assert(writeReqHead_ != nullptr);
1945 // Loop until we run out of write requests,
1946 // or until this socket is moved to another EventBase.
1947 // (See the comment in handleRead() explaining how this can happen.)
1948 EventBase* originalEventBase = eventBase_;
1949 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1950 auto writeResult = writeReqHead_->performWrite();
1951 if (writeResult.writeReturn < 0) {
1952 if (writeResult.exception) {
1953 return failWrite(__func__, *writeResult.exception);
1955 auto errnoCopy = errno;
1956 AsyncSocketException ex(
1957 AsyncSocketException::INTERNAL_ERROR,
1958 withAddr("writev() failed"),
1960 return failWrite(__func__, ex);
1961 } else if (writeReqHead_->isComplete()) {
1962 // We finished this request
1963 WriteRequest* req = writeReqHead_;
1964 writeReqHead_ = req->getNext();
1966 if (writeReqHead_ == nullptr) {
1967 writeReqTail_ = nullptr;
1968 // This is the last write request.
1969 // Unregister for write events and cancel the send timer
1970 // before we invoke the callback. We have to update the state properly
1971 // before calling the callback, since it may want to detach us from
1973 if (eventFlags_ & EventHandler::WRITE) {
1974 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1975 assert(state_ == StateEnum::ERROR);
1978 // Stop the send timeout
1979 writeTimeout_.cancelTimeout();
1981 assert(!writeTimeout_.isScheduled());
1983 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
1984 // we finish sending the last write request.
1986 // We have to do this before invoking writeSuccess(), since
1987 // writeSuccess() may detach us from our EventBase.
1988 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
1989 assert(connectCallback_ == nullptr);
1990 shutdownFlags_ |= SHUT_WRITE;
1992 if (shutdownFlags_ & SHUT_READ) {
1993 // Reads have already been shutdown. Fully close the socket and
1994 // move to STATE_CLOSED.
1996 // Note: This code currently moves us to STATE_CLOSED even if
1997 // close() hasn't ever been called. This can occur if we have
1998 // received EOF from the peer and shutdownWrite() has been called
1999 // locally. Should we bother staying in STATE_ESTABLISHED in this
2000 // case, until close() is actually called? I can't think of a
2001 // reason why we would need to do so. No other operations besides
2002 // calling close() or destroying the socket can be performed at
2004 assert(readCallback_ == nullptr);
2005 state_ = StateEnum::CLOSED;
2007 ioHandler_.changeHandlerFD(-1);
2011 // Reads are still enabled, so we are only doing a half-shutdown
2012 shutdown(fd_, SHUT_WR);
2017 // Invoke the callback
2018 WriteCallback* callback = req->getCallback();
2021 callback->writeSuccess();
2023 // We'll continue around the loop, trying to write another request
2026 if (bufferCallback_) {
2027 bufferCallback_->onEgressBuffered();
2029 writeReqHead_->consume();
2030 // Stop after a partial write; it's highly likely that a subsequent write
2031 // attempt will just return EAGAIN.
2033 // Ensure that we are registered for write events.
2034 if ((eventFlags_ & EventHandler::WRITE) == 0) {
2035 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
2036 assert(state_ == StateEnum::ERROR);
2041 // Reschedule the send timeout, since we have made some write progress.
2042 if (sendTimeout_ > 0) {
2043 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
2044 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
2045 withAddr("failed to reschedule write timeout"));
2046 return failWrite(__func__, ex);
2052 if (!writeReqHead_ && bufferCallback_) {
2053 bufferCallback_->onEgressBufferCleared();
2057 void AsyncSocket::checkForImmediateRead() noexcept {
2058 // We currently don't attempt to perform optimistic reads in AsyncSocket.
2059 // (However, note that some subclasses do override this method.)
2061 // Simply calling handleRead() here would be bad, as this would call
2062 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
2063 // buffer even though no data may be available. This would waste lots of
2064 // memory, since the buffer will sit around unused until the socket actually
2065 // becomes readable.
2067 // Checking if the socket is readable now also seems like it would probably
2068 // be a pessimism. In most cases it probably wouldn't be readable, and we
2069 // would just waste an extra system call. Even if it is readable, waiting to
2070 // find out from libevent on the next event loop doesn't seem that bad.
2072 // The exception to this is if we have pre-received data. In that case there
2073 // is definitely data available immediately.
2074 if (preReceivedData_ && !preReceivedData_->empty()) {
2079 void AsyncSocket::handleInitialReadWrite() noexcept {
2080 // Our callers should already be holding a DestructorGuard, but grab
2081 // one here just to make sure, in case one of our calling code paths ever
2083 DestructorGuard dg(this);
2084 // If we have a readCallback_, make sure we enable read events. We
2085 // may already be registered for reads if connectSuccess() set
2086 // the read calback.
2087 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
2088 assert(state_ == StateEnum::ESTABLISHED);
2089 assert((shutdownFlags_ & SHUT_READ) == 0);
2090 if (!updateEventRegistration(EventHandler::READ, 0)) {
2091 assert(state_ == StateEnum::ERROR);
2094 checkForImmediateRead();
2095 } else if (readCallback_ == nullptr) {
2096 // Unregister for read events.
2097 updateEventRegistration(0, EventHandler::READ);
2100 // If we have write requests pending, try to send them immediately.
2101 // Since we just finished accepting, there is a very good chance that we can
2102 // write without blocking.
2104 // However, we only process them if EventHandler::WRITE is not already set,
2105 // which means that we're already blocked on a write attempt. (This can
2106 // happen if connectSuccess() called write() before returning.)
2107 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
2108 // Call handleWrite() to perform write processing.
2110 } else if (writeReqHead_ == nullptr) {
2111 // Unregister for write event.
2112 updateEventRegistration(0, EventHandler::WRITE);
2116 void AsyncSocket::handleConnect() noexcept {
2117 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
2118 << ", state=" << state_;
2119 assert(state_ == StateEnum::CONNECTING);
2120 // SHUT_WRITE can never be set while we are still connecting;
2121 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
2123 assert((shutdownFlags_ & SHUT_WRITE) == 0);
2125 // In case we had a connect timeout, cancel the timeout
2126 writeTimeout_.cancelTimeout();
2127 // We don't use a persistent registration when waiting on a connect event,
2128 // so we have been automatically unregistered now. Update eventFlags_ to
2130 assert(eventFlags_ == EventHandler::WRITE);
2131 eventFlags_ = EventHandler::NONE;
2133 // Call getsockopt() to check if the connect succeeded
2135 socklen_t len = sizeof(error);
2136 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
2138 auto errnoCopy = errno;
2139 AsyncSocketException ex(
2140 AsyncSocketException::INTERNAL_ERROR,
2141 withAddr("error calling getsockopt() after connect"),
2143 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
2144 << fd_ << " host=" << addr_.describe()
2145 << ") exception:" << ex.what();
2146 return failConnect(__func__, ex);
2150 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2151 "connect failed", error);
2152 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
2153 << fd_ << " host=" << addr_.describe()
2154 << ") exception: " << ex.what();
2155 return failConnect(__func__, ex);
2158 // Move into STATE_ESTABLISHED
2159 state_ = StateEnum::ESTABLISHED;
2161 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
2162 // perform, immediately shutdown the write half of the socket.
2163 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
2164 // SHUT_READ shouldn't be set. If close() is called on the socket while we
2165 // are still connecting we just abort the connect rather than waiting for
2167 assert((shutdownFlags_ & SHUT_READ) == 0);
2168 shutdown(fd_, SHUT_WR);
2169 shutdownFlags_ |= SHUT_WRITE;
2172 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
2173 << "successfully connected; state=" << state_;
2175 // Remember the EventBase we are attached to, before we start invoking any
2176 // callbacks (since the callbacks may call detachEventBase()).
2177 EventBase* originalEventBase = eventBase_;
2179 invokeConnectSuccess();
2180 // Note that the connect callback may have changed our state.
2181 // (set or unset the read callback, called write(), closed the socket, etc.)
2182 // The following code needs to handle these situations correctly.
2184 // If the socket has been closed, readCallback_ and writeReqHead_ will
2185 // always be nullptr, so that will prevent us from trying to read or write.
2187 // The main thing to check for is if eventBase_ is still originalEventBase.
2188 // If not, we have been detached from this event base, so we shouldn't
2189 // perform any more operations.
2190 if (eventBase_ != originalEventBase) {
2194 handleInitialReadWrite();
2197 void AsyncSocket::timeoutExpired() noexcept {
2198 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
2199 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
2200 DestructorGuard dg(this);
2201 eventBase_->dcheckIsInEventBaseThread();
2203 if (state_ == StateEnum::CONNECTING) {
2204 // connect() timed out
2205 // Unregister for I/O events.
2206 if (connectCallback_) {
2207 AsyncSocketException ex(
2208 AsyncSocketException::TIMED_OUT,
2210 "connect timed out after {}ms", connectTimeout_.count()));
2211 failConnect(__func__, ex);
2213 // we faced a connect error without a connect callback, which could
2214 // happen due to TFO.
2215 AsyncSocketException ex(
2216 AsyncSocketException::TIMED_OUT, "write timed out during connection");
2217 failWrite(__func__, ex);
2220 // a normal write operation timed out
2221 AsyncSocketException ex(
2222 AsyncSocketException::TIMED_OUT,
2223 folly::sformat("write timed out after {}ms", sendTimeout_));
2224 failWrite(__func__, ex);
2228 ssize_t AsyncSocket::tfoSendMsg(int fd, struct msghdr* msg, int msg_flags) {
2229 return detail::tfo_sendmsg(fd, msg, msg_flags);
2232 AsyncSocket::WriteResult
2233 AsyncSocket::sendSocketMessage(int fd, struct msghdr* msg, int msg_flags) {
2234 ssize_t totalWritten = 0;
2235 if (state_ == StateEnum::FAST_OPEN) {
2236 sockaddr_storage addr;
2237 auto len = addr_.getAddress(&addr);
2238 msg->msg_name = &addr;
2239 msg->msg_namelen = len;
2240 totalWritten = tfoSendMsg(fd_, msg, msg_flags);
2241 if (totalWritten >= 0) {
2242 tfoFinished_ = true;
2243 state_ = StateEnum::ESTABLISHED;
2244 // We schedule this asynchrously so that we don't end up
2245 // invoking initial read or write while a write is in progress.
2246 scheduleInitialReadWrite();
2247 } else if (errno == EINPROGRESS) {
2248 VLOG(4) << "TFO falling back to connecting";
2249 // A normal sendmsg doesn't return EINPROGRESS, however
2250 // TFO might fallback to connecting if there is no
2252 state_ = StateEnum::CONNECTING;
2254 scheduleConnectTimeout();
2255 registerForConnectEvents();
2256 } catch (const AsyncSocketException& ex) {
2258 WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
2260 // Let's fake it that no bytes were written and return an errno.
2263 } else if (errno == EOPNOTSUPP) {
2264 // Try falling back to connecting.
2265 VLOG(4) << "TFO not supported";
2266 state_ = StateEnum::CONNECTING;
2268 int ret = socketConnect((const sockaddr*)&addr, len);
2270 // connect succeeded immediately
2271 // Treat this like no data was written.
2272 state_ = StateEnum::ESTABLISHED;
2273 scheduleInitialReadWrite();
2275 // If there was no exception during connections,
2276 // we would return that no bytes were written.
2279 } catch (const AsyncSocketException& ex) {
2281 WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
2283 } else if (errno == EAGAIN) {
2284 // Normally sendmsg would indicate that the write would block.
2285 // However in the fast open case, it would indicate that sendmsg
2286 // fell back to a connect. This is a return code from connect()
2287 // instead, and is an error condition indicating no fds available.
2290 std::make_unique<AsyncSocketException>(
2291 AsyncSocketException::UNKNOWN, "No more free local ports"));
2294 totalWritten = ::sendmsg(fd, msg, msg_flags);
2296 return WriteResult(totalWritten);
2299 AsyncSocket::WriteResult AsyncSocket::performWrite(
2303 uint32_t* countWritten,
2304 uint32_t* partialWritten) {
2305 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
2306 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
2307 // (since it may terminate the program if the main program doesn't explicitly
2310 msg.msg_name = nullptr;
2311 msg.msg_namelen = 0;
2312 msg.msg_iov = const_cast<iovec *>(vec);
2313 msg.msg_iovlen = std::min<size_t>(count, kIovMax);
2315 msg.msg_controllen = sendMsgParamCallback_->getAncillaryDataSize(flags);
2316 CHECK_GE(AsyncSocket::SendMsgParamsCallback::maxAncillaryDataSize,
2317 msg.msg_controllen);
2319 if (msg.msg_controllen != 0) {
2320 msg.msg_control = reinterpret_cast<char*>(alloca(msg.msg_controllen));
2321 sendMsgParamCallback_->getAncillaryData(flags, msg.msg_control);
2323 msg.msg_control = nullptr;
2325 int msg_flags = sendMsgParamCallback_->getFlags(flags, zeroCopyEnabled_);
2327 auto writeResult = sendSocketMessage(fd_, &msg, msg_flags);
2328 auto totalWritten = writeResult.writeReturn;
2329 if (totalWritten < 0) {
2330 bool tryAgain = (errno == EAGAIN);
2332 // Apple has a bug where doing a second write on a socket which we
2333 // have opened with TFO causes an ENOTCONN to be thrown. However the
2334 // socket is really connected, so treat ENOTCONN as a EAGAIN until
2335 // this bug is fixed.
2336 tryAgain |= (errno == ENOTCONN);
2338 if (!writeResult.exception && tryAgain) {
2339 // TCP buffer is full; we can't write any more data right now.
2341 *partialWritten = 0;
2342 return WriteResult(0);
2346 *partialWritten = 0;
2350 appBytesWritten_ += totalWritten;
2352 uint32_t bytesWritten;
2354 for (bytesWritten = uint32_t(totalWritten), n = 0; n < count; ++n) {
2355 const iovec* v = vec + n;
2356 if (v->iov_len > bytesWritten) {
2357 // Partial write finished in the middle of this iovec
2359 *partialWritten = bytesWritten;
2360 return WriteResult(totalWritten);
2363 bytesWritten -= uint32_t(v->iov_len);
2366 assert(bytesWritten == 0);
2368 *partialWritten = 0;
2369 return WriteResult(totalWritten);
2373 * Re-register the EventHandler after eventFlags_ has changed.
2375 * If an error occurs, fail() is called to move the socket into the error state
2376 * and call all currently installed callbacks. After an error, the
2377 * AsyncSocket is completely unregistered.
2379 * @return Returns true on success, or false on error.
2381 bool AsyncSocket::updateEventRegistration() {
2382 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
2383 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
2384 << ", events=" << std::hex << eventFlags_;
2385 eventBase_->dcheckIsInEventBaseThread();
2386 if (eventFlags_ == EventHandler::NONE) {
2387 ioHandler_.unregisterHandler();
2391 // Always register for persistent events, so we don't have to re-register
2392 // after being called back.
2393 if (!ioHandler_.registerHandler(
2394 uint16_t(eventFlags_ | EventHandler::PERSIST))) {
2395 eventFlags_ = EventHandler::NONE; // we're not registered after error
2396 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
2397 withAddr("failed to update AsyncSocket event registration"));
2398 fail("updateEventRegistration", ex);
2405 bool AsyncSocket::updateEventRegistration(uint16_t enable,
2407 uint16_t oldFlags = eventFlags_;
2408 eventFlags_ |= enable;
2409 eventFlags_ &= ~disable;
2410 if (eventFlags_ == oldFlags) {
2413 return updateEventRegistration();
2417 void AsyncSocket::startFail() {
2418 // startFail() should only be called once
2419 assert(state_ != StateEnum::ERROR);
2420 assert(getDestructorGuardCount() > 0);
2421 state_ = StateEnum::ERROR;
2422 // Ensure that SHUT_READ and SHUT_WRITE are set,
2423 // so all future attempts to read or write will be rejected
2424 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
2426 if (eventFlags_ != EventHandler::NONE) {
2427 eventFlags_ = EventHandler::NONE;
2428 ioHandler_.unregisterHandler();
2430 writeTimeout_.cancelTimeout();
2433 ioHandler_.changeHandlerFD(-1);
2438 void AsyncSocket::invokeAllErrors(const AsyncSocketException& ex) {
2439 invokeConnectErr(ex);
2442 if (readCallback_) {
2443 ReadCallback* callback = readCallback_;
2444 readCallback_ = nullptr;
2445 callback->readErr(ex);
2449 void AsyncSocket::finishFail() {
2450 assert(state_ == StateEnum::ERROR);
2451 assert(getDestructorGuardCount() > 0);
2453 AsyncSocketException ex(
2454 AsyncSocketException::INTERNAL_ERROR,
2455 withAddr("socket closing after error"));
2456 invokeAllErrors(ex);
2459 void AsyncSocket::finishFail(const AsyncSocketException& ex) {
2460 assert(state_ == StateEnum::ERROR);
2461 assert(getDestructorGuardCount() > 0);
2462 invokeAllErrors(ex);
2465 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
2466 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2467 << state_ << " host=" << addr_.describe()
2468 << "): failed in " << fn << "(): "
2474 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
2475 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2476 << state_ << " host=" << addr_.describe()
2477 << "): failed while connecting in " << fn << "(): "
2481 invokeConnectErr(ex);
2485 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
2486 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2487 << state_ << " host=" << addr_.describe()
2488 << "): failed while reading in " << fn << "(): "
2492 if (readCallback_ != nullptr) {
2493 ReadCallback* callback = readCallback_;
2494 readCallback_ = nullptr;
2495 callback->readErr(ex);
2501 void AsyncSocket::failErrMessageRead(const char* fn,
2502 const AsyncSocketException& ex) {
2503 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2504 << state_ << " host=" << addr_.describe()
2505 << "): failed while reading message in " << fn << "(): "
2509 if (errMessageCallback_ != nullptr) {
2510 ErrMessageCallback* callback = errMessageCallback_;
2511 errMessageCallback_ = nullptr;
2512 callback->errMessageError(ex);
2518 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
2519 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2520 << state_ << " host=" << addr_.describe()
2521 << "): failed while writing in " << fn << "(): "
2525 // Only invoke the first write callback, since the error occurred while
2526 // writing this request. Let any other pending write callbacks be invoked in
2528 if (writeReqHead_ != nullptr) {
2529 WriteRequest* req = writeReqHead_;
2530 writeReqHead_ = req->getNext();
2531 WriteCallback* callback = req->getCallback();
2532 uint32_t bytesWritten = req->getTotalBytesWritten();
2535 callback->writeErr(bytesWritten, ex);
2542 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
2543 size_t bytesWritten,
2544 const AsyncSocketException& ex) {
2545 // This version of failWrite() is used when the failure occurs before
2546 // we've added the callback to writeReqHead_.
2547 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2548 << state_ << " host=" << addr_.describe()
2549 <<"): failed while writing in " << fn << "(): "
2553 if (callback != nullptr) {
2554 callback->writeErr(bytesWritten, ex);
2560 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
2561 // Invoke writeError() on all write callbacks.
2562 // This is used when writes are forcibly shutdown with write requests
2563 // pending, or when an error occurs with writes pending.
2564 while (writeReqHead_ != nullptr) {
2565 WriteRequest* req = writeReqHead_;
2566 writeReqHead_ = req->getNext();
2567 WriteCallback* callback = req->getCallback();
2569 callback->writeErr(req->getTotalBytesWritten(), ex);
2575 void AsyncSocket::invalidState(ConnectCallback* callback) {
2576 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2577 << "): connect() called in invalid state " << state_;
2580 * The invalidState() methods don't use the normal failure mechanisms,
2581 * since we don't know what state we are in. We don't want to call
2582 * startFail()/finishFail() recursively if we are already in the middle of
2586 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
2587 "connect() called with socket in invalid state");
2588 connectEndTime_ = std::chrono::steady_clock::now();
2589 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2591 callback->connectErr(ex);
2594 // We can't use failConnect() here since connectCallback_
2595 // may already be set to another callback. Invoke this ConnectCallback
2596 // here; any other connectCallback_ will be invoked in finishFail()
2599 callback->connectErr(ex);
2605 void AsyncSocket::invalidState(ErrMessageCallback* callback) {
2606 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2607 << "): setErrMessageCB(" << callback
2608 << ") called in invalid state " << state_;
2610 AsyncSocketException ex(
2611 AsyncSocketException::NOT_OPEN,
2612 msgErrQueueSupported
2613 ? "setErrMessageCB() called with socket in invalid state"
2614 : "This platform does not support socket error message notifications");
2615 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2617 callback->errMessageError(ex);
2622 callback->errMessageError(ex);
2628 void AsyncSocket::invokeConnectErr(const AsyncSocketException& ex) {
2629 connectEndTime_ = std::chrono::steady_clock::now();
2630 if (connectCallback_) {
2631 ConnectCallback* callback = connectCallback_;
2632 connectCallback_ = nullptr;
2633 callback->connectErr(ex);
2637 void AsyncSocket::invokeConnectSuccess() {
2638 connectEndTime_ = std::chrono::steady_clock::now();
2639 if (connectCallback_) {
2640 ConnectCallback* callback = connectCallback_;
2641 connectCallback_ = nullptr;
2642 callback->connectSuccess();
2646 void AsyncSocket::invalidState(ReadCallback* callback) {
2647 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2648 << "): setReadCallback(" << callback
2649 << ") called in invalid state " << state_;
2651 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2652 "setReadCallback() called with socket in "
2654 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2656 callback->readErr(ex);
2661 callback->readErr(ex);
2667 void AsyncSocket::invalidState(WriteCallback* callback) {
2668 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2669 << "): write() called in invalid state " << state_;
2671 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2672 withAddr("write() called with socket in invalid state"));
2673 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2675 callback->writeErr(0, ex);
2680 callback->writeErr(0, ex);
2686 void AsyncSocket::doClose() {
2687 if (fd_ == -1) return;
2688 if (shutdownSocketSet_) {
2689 shutdownSocketSet_->close(fd_);
2696 std::ostream& operator << (std::ostream& os,
2697 const AsyncSocket::StateEnum& state) {
2698 os << static_cast<int>(state);
2702 std::string AsyncSocket::withAddr(const std::string& s) {
2703 // Don't use addr_ directly because it may not be initialized
2704 // e.g. if constructed from fd
2705 folly::SocketAddress peer, local;
2707 getPeerAddress(&peer);
2708 getLocalAddress(&local);
2709 } catch (const std::exception&) {
2714 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";
2717 void AsyncSocket::setBufferCallback(BufferCallback* cb) {
2718 bufferCallback_ = cb;
2721 } // namespace folly