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/Portability.h>
21 #include <folly/SocketAddress.h>
22 #include <folly/io/Cursor.h>
23 #include <folly/io/IOBuf.h>
24 #include <folly/io/IOBufQueue.h>
25 #include <folly/portability/Fcntl.h>
26 #include <folly/portability/Sockets.h>
27 #include <folly/portability/SysUio.h>
28 #include <folly/portability/Unistd.h>
30 #include <boost/preprocessor/control/if.hpp>
33 #include <sys/types.h>
37 using std::unique_ptr;
39 namespace fsp = folly::portability::sockets;
43 static constexpr bool msgErrQueueSupported =
48 #endif // MSG_ERRQUEUE
50 // static members initializers
51 const AsyncSocket::OptionMap AsyncSocket::emptyOptionMap;
53 const AsyncSocketException socketClosedLocallyEx(
54 AsyncSocketException::END_OF_FILE, "socket closed locally");
55 const AsyncSocketException socketShutdownForWritesEx(
56 AsyncSocketException::END_OF_FILE, "socket shutdown for writes");
58 // TODO: It might help performance to provide a version of BytesWriteRequest that
59 // users could derive from, so we can avoid the extra allocation for each call
60 // to write()/writev(). We could templatize TFramedAsyncChannel just like the
61 // protocols are currently templatized for transports.
63 // We would need the version for external users where they provide the iovec
64 // storage space, and only our internal version would allocate it at the end of
67 /* The default WriteRequest implementation, used for write(), writev() and
70 * A new BytesWriteRequest operation is allocated on the heap for all write
71 * operations that cannot be completed immediately.
73 class AsyncSocket::BytesWriteRequest : public AsyncSocket::WriteRequest {
75 static BytesWriteRequest* newRequest(AsyncSocket* socket,
76 WriteCallback* callback,
79 uint32_t partialWritten,
80 uint32_t bytesWritten,
81 unique_ptr<IOBuf>&& ioBuf,
84 // Since we put a variable size iovec array at the end
85 // of each BytesWriteRequest, we have to manually allocate the memory.
86 void* buf = malloc(sizeof(BytesWriteRequest) +
87 (opCount * sizeof(struct iovec)));
89 throw std::bad_alloc();
92 return new(buf) BytesWriteRequest(socket, callback, ops, opCount,
93 partialWritten, bytesWritten,
94 std::move(ioBuf), flags);
97 void destroy() override {
98 this->~BytesWriteRequest();
102 WriteResult performWrite() override {
103 WriteFlags writeFlags = flags_;
104 if (getNext() != nullptr) {
105 writeFlags |= WriteFlags::CORK;
107 auto writeResult = socket_->performWrite(
108 getOps(), getOpCount(), writeFlags, &opsWritten_, &partialBytes_);
109 bytesWritten_ = writeResult.writeReturn > 0 ? writeResult.writeReturn : 0;
113 bool isComplete() override {
114 return opsWritten_ == getOpCount();
117 void consume() override {
118 // Advance opIndex_ forward by opsWritten_
119 opIndex_ += opsWritten_;
120 assert(opIndex_ < opCount_);
122 // If we've finished writing any IOBufs, release them
124 for (uint32_t i = opsWritten_; i != 0; --i) {
126 ioBuf_ = ioBuf_->pop();
130 // Move partialBytes_ forward into the current iovec buffer
131 struct iovec* currentOp = writeOps_ + opIndex_;
132 assert((partialBytes_ < currentOp->iov_len) || (currentOp->iov_len == 0));
133 currentOp->iov_base =
134 reinterpret_cast<uint8_t*>(currentOp->iov_base) + partialBytes_;
135 currentOp->iov_len -= partialBytes_;
137 // Increment the totalBytesWritten_ count by bytesWritten_;
138 assert(bytesWritten_ >= 0);
139 totalBytesWritten_ += uint32_t(bytesWritten_);
143 BytesWriteRequest(AsyncSocket* socket,
144 WriteCallback* callback,
145 const struct iovec* ops,
147 uint32_t partialBytes,
148 uint32_t bytesWritten,
149 unique_ptr<IOBuf>&& ioBuf,
151 : AsyncSocket::WriteRequest(socket, callback)
155 , ioBuf_(std::move(ioBuf))
157 , partialBytes_(partialBytes)
158 , bytesWritten_(bytesWritten) {
159 memcpy(writeOps_, ops, sizeof(*ops) * opCount_);
162 // private destructor, to ensure callers use destroy()
163 ~BytesWriteRequest() override = default;
165 const struct iovec* getOps() const {
166 assert(opCount_ > opIndex_);
167 return writeOps_ + opIndex_;
170 uint32_t getOpCount() const {
171 assert(opCount_ > opIndex_);
172 return opCount_ - opIndex_;
175 uint32_t opCount_; ///< number of entries in writeOps_
176 uint32_t opIndex_; ///< current index into writeOps_
177 WriteFlags flags_; ///< set for WriteFlags
178 unique_ptr<IOBuf> ioBuf_; ///< underlying IOBuf, or nullptr if N/A
180 // for consume(), how much we wrote on the last write
181 uint32_t opsWritten_; ///< complete ops written
182 uint32_t partialBytes_; ///< partial bytes of incomplete op written
183 ssize_t bytesWritten_; ///< bytes written altogether
185 struct iovec writeOps_[]; ///< write operation(s) list
188 int AsyncSocket::SendMsgParamsCallback::getDefaultFlags(folly::WriteFlags flags)
190 int msg_flags = MSG_DONTWAIT;
192 #ifdef MSG_NOSIGNAL // Linux-only
193 msg_flags |= MSG_NOSIGNAL;
195 if (isSet(flags, WriteFlags::CORK)) {
196 // MSG_MORE tells the kernel we have more data to send, so wait for us to
197 // give it the rest of the data rather than immediately sending a partial
198 // frame, even when TCP_NODELAY is enabled.
199 msg_flags |= MSG_MORE;
202 #endif // MSG_NOSIGNAL
203 if (isSet(flags, WriteFlags::EOR)) {
204 // marks that this is the last byte of a record (response)
205 msg_flags |= MSG_EOR;
212 static AsyncSocket::SendMsgParamsCallback defaultSendMsgParamsCallback;
215 AsyncSocket::AsyncSocket()
216 : eventBase_(nullptr),
217 writeTimeout_(this, nullptr),
218 ioHandler_(this, nullptr),
219 immediateReadHandler_(this) {
220 VLOG(5) << "new AsyncSocket()";
224 AsyncSocket::AsyncSocket(EventBase* evb)
226 writeTimeout_(this, evb),
227 ioHandler_(this, evb),
228 immediateReadHandler_(this) {
229 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
233 AsyncSocket::AsyncSocket(EventBase* evb,
234 const folly::SocketAddress& address,
235 uint32_t connectTimeout)
237 connect(nullptr, address, connectTimeout);
240 AsyncSocket::AsyncSocket(EventBase* evb,
241 const std::string& ip,
243 uint32_t connectTimeout)
245 connect(nullptr, ip, port, connectTimeout);
248 AsyncSocket::AsyncSocket(EventBase* evb, int fd)
250 writeTimeout_(this, evb),
251 ioHandler_(this, evb, fd),
252 immediateReadHandler_(this) {
253 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ", fd="
258 state_ = StateEnum::ESTABLISHED;
261 AsyncSocket::AsyncSocket(AsyncSocket::UniquePtr oldAsyncSocket)
262 : AsyncSocket(oldAsyncSocket->getEventBase(), oldAsyncSocket->detachFd()) {
263 preReceivedData_ = std::move(oldAsyncSocket->preReceivedData_);
266 // init() method, since constructor forwarding isn't supported in most
268 void AsyncSocket::init() {
269 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
271 state_ = StateEnum::UNINIT;
272 eventFlags_ = EventHandler::NONE;
275 maxReadsPerEvent_ = 16;
276 connectCallback_ = nullptr;
277 errMessageCallback_ = nullptr;
278 readCallback_ = nullptr;
279 writeReqHead_ = nullptr;
280 writeReqTail_ = nullptr;
281 shutdownSocketSet_ = nullptr;
282 appBytesWritten_ = 0;
283 appBytesReceived_ = 0;
284 sendMsgParamCallback_ = &defaultSendMsgParamsCallback;
287 AsyncSocket::~AsyncSocket() {
288 VLOG(7) << "actual destruction of AsyncSocket(this=" << this
289 << ", evb=" << eventBase_ << ", fd=" << fd_
290 << ", state=" << state_ << ")";
293 void AsyncSocket::destroy() {
294 VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
295 << ", fd=" << fd_ << ", state=" << state_;
296 // When destroy is called, close the socket immediately
299 // Then call DelayedDestruction::destroy() to take care of
300 // whether or not we need immediate or delayed destruction
301 DelayedDestruction::destroy();
304 int AsyncSocket::detachFd() {
305 VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
306 << ", evb=" << eventBase_ << ", state=" << state_
307 << ", events=" << std::hex << eventFlags_ << ")";
308 // Extract the fd, and set fd_ to -1 first, so closeNow() won't
309 // actually close the descriptor.
310 if (shutdownSocketSet_) {
311 shutdownSocketSet_->remove(fd_);
315 // Call closeNow() to invoke all pending callbacks with an error.
317 // Update the EventHandler to stop using this fd.
318 // This can only be done after closeNow() unregisters the handler.
319 ioHandler_.changeHandlerFD(-1);
323 const folly::SocketAddress& AsyncSocket::anyAddress() {
324 static const folly::SocketAddress anyAddress =
325 folly::SocketAddress("0.0.0.0", 0);
329 void AsyncSocket::setShutdownSocketSet(ShutdownSocketSet* newSS) {
330 if (shutdownSocketSet_ == newSS) {
333 if (shutdownSocketSet_ && fd_ != -1) {
334 shutdownSocketSet_->remove(fd_);
336 shutdownSocketSet_ = newSS;
337 if (shutdownSocketSet_ && fd_ != -1) {
338 shutdownSocketSet_->add(fd_);
342 void AsyncSocket::setCloseOnExec() {
343 int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
345 auto errnoCopy = errno;
346 throw AsyncSocketException(
347 AsyncSocketException::INTERNAL_ERROR,
348 withAddr("failed to set close-on-exec flag"),
353 void AsyncSocket::connect(ConnectCallback* callback,
354 const folly::SocketAddress& address,
356 const OptionMap &options,
357 const folly::SocketAddress& bindAddr) noexcept {
358 DestructorGuard dg(this);
359 assert(eventBase_->isInEventBaseThread());
363 // Make sure we're in the uninitialized state
364 if (state_ != StateEnum::UNINIT) {
365 return invalidState(callback);
368 connectTimeout_ = std::chrono::milliseconds(timeout);
369 connectStartTime_ = std::chrono::steady_clock::now();
370 // Make connect end time at least >= connectStartTime.
371 connectEndTime_ = connectStartTime_;
374 state_ = StateEnum::CONNECTING;
375 connectCallback_ = callback;
377 sockaddr_storage addrStorage;
378 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
382 // Technically the first parameter should actually be a protocol family
383 // constant (PF_xxx) rather than an address family (AF_xxx), but the
384 // distinction is mainly just historical. In pretty much all
385 // implementations the PF_foo and AF_foo constants are identical.
386 fd_ = fsp::socket(address.getFamily(), SOCK_STREAM, 0);
388 auto errnoCopy = errno;
389 throw AsyncSocketException(
390 AsyncSocketException::INTERNAL_ERROR,
391 withAddr("failed to create socket"),
394 if (shutdownSocketSet_) {
395 shutdownSocketSet_->add(fd_);
397 ioHandler_.changeHandlerFD(fd_);
401 // Put the socket in non-blocking mode
402 int flags = fcntl(fd_, F_GETFL, 0);
404 auto errnoCopy = errno;
405 throw AsyncSocketException(
406 AsyncSocketException::INTERNAL_ERROR,
407 withAddr("failed to get socket flags"),
410 int rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
412 auto errnoCopy = errno;
413 throw AsyncSocketException(
414 AsyncSocketException::INTERNAL_ERROR,
415 withAddr("failed to put socket in non-blocking mode"),
419 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
420 // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
421 rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
423 auto errnoCopy = errno;
424 throw AsyncSocketException(
425 AsyncSocketException::INTERNAL_ERROR,
426 "failed to enable F_SETNOSIGPIPE on socket",
431 // By default, turn on TCP_NODELAY
432 // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
433 // setNoDelay() will log an error message if it fails.
434 if (address.getFamily() != AF_UNIX) {
435 (void)setNoDelay(true);
438 VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
439 << ", fd=" << fd_ << ", host=" << address.describe().c_str();
442 if (bindAddr != anyAddress()) {
444 if (setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
445 auto errnoCopy = errno;
447 throw AsyncSocketException(
448 AsyncSocketException::NOT_OPEN,
449 "failed to setsockopt prior to bind on " + bindAddr.describe(),
453 bindAddr.getAddress(&addrStorage);
455 if (bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
456 auto errnoCopy = errno;
458 throw AsyncSocketException(
459 AsyncSocketException::NOT_OPEN,
460 "failed to bind to async socket: " + bindAddr.describe(),
465 // Apply the additional options if any.
466 for (const auto& opt: options) {
467 rv = opt.first.apply(fd_, opt.second);
469 auto errnoCopy = errno;
470 throw AsyncSocketException(
471 AsyncSocketException::INTERNAL_ERROR,
472 withAddr("failed to set socket option"),
477 // Perform the connect()
478 address.getAddress(&addrStorage);
481 state_ = StateEnum::FAST_OPEN;
482 tfoAttempted_ = true;
484 if (socketConnect(saddr, addr_.getActualSize()) < 0) {
489 // If we're still here the connect() succeeded immediately.
490 // Fall through to call the callback outside of this try...catch block
491 } catch (const AsyncSocketException& ex) {
492 return failConnect(__func__, ex);
493 } catch (const std::exception& ex) {
494 // shouldn't happen, but handle it just in case
495 VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
496 << "): unexpected " << typeid(ex).name() << " exception: "
498 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
499 withAddr(string("unexpected exception: ") +
501 return failConnect(__func__, tex);
504 // The connection succeeded immediately
505 // The read callback may not have been set yet, and no writes may be pending
506 // yet, so we don't have to register for any events at the moment.
507 VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
508 assert(errMessageCallback_ == nullptr);
509 assert(readCallback_ == nullptr);
510 assert(writeReqHead_ == nullptr);
511 if (state_ != StateEnum::FAST_OPEN) {
512 state_ = StateEnum::ESTABLISHED;
514 invokeConnectSuccess();
517 int AsyncSocket::socketConnect(const struct sockaddr* saddr, socklen_t len) {
519 if (noTransparentTls_) {
520 // Ignore return value, errors are ok
521 setsockopt(fd_, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0);
524 VLOG(4) << "Disabling TSOCKS for fd " << fd_;
525 // Ignore return value, errors are ok
526 setsockopt(fd_, SOL_SOCKET, SO_NO_TSOCKS, nullptr, 0);
529 int rv = fsp::connect(fd_, saddr, len);
531 auto errnoCopy = errno;
532 if (errnoCopy == EINPROGRESS) {
533 scheduleConnectTimeout();
534 registerForConnectEvents();
536 throw AsyncSocketException(
537 AsyncSocketException::NOT_OPEN,
538 "connect failed (immediately)",
545 void AsyncSocket::scheduleConnectTimeout() {
546 // Connection in progress.
547 auto timeout = connectTimeout_.count();
549 // Start a timer in case the connection takes too long.
550 if (!writeTimeout_.scheduleTimeout(uint32_t(timeout))) {
551 throw AsyncSocketException(
552 AsyncSocketException::INTERNAL_ERROR,
553 withAddr("failed to schedule AsyncSocket connect timeout"));
558 void AsyncSocket::registerForConnectEvents() {
559 // Register for write events, so we'll
560 // be notified when the connection finishes/fails.
561 // Note that we don't register for a persistent event here.
562 assert(eventFlags_ == EventHandler::NONE);
563 eventFlags_ = EventHandler::WRITE;
564 if (!ioHandler_.registerHandler(eventFlags_)) {
565 throw AsyncSocketException(
566 AsyncSocketException::INTERNAL_ERROR,
567 withAddr("failed to register AsyncSocket connect handler"));
571 void AsyncSocket::connect(ConnectCallback* callback,
572 const string& ip, uint16_t port,
574 const OptionMap &options) noexcept {
575 DestructorGuard dg(this);
577 connectCallback_ = callback;
578 connect(callback, folly::SocketAddress(ip, port), timeout, options);
579 } catch (const std::exception& ex) {
580 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
582 return failConnect(__func__, tex);
586 void AsyncSocket::cancelConnect() {
587 connectCallback_ = nullptr;
588 if (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN) {
593 void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
594 sendTimeout_ = milliseconds;
595 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
597 // If we are currently pending on write requests, immediately update
598 // writeTimeout_ with the new value.
599 if ((eventFlags_ & EventHandler::WRITE) &&
600 (state_ != StateEnum::CONNECTING && state_ != StateEnum::FAST_OPEN)) {
601 assert(state_ == StateEnum::ESTABLISHED);
602 assert((shutdownFlags_ & SHUT_WRITE) == 0);
603 if (sendTimeout_ > 0) {
604 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
605 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
606 withAddr("failed to reschedule send timeout in setSendTimeout"));
607 return failWrite(__func__, ex);
610 writeTimeout_.cancelTimeout();
615 void AsyncSocket::setErrMessageCB(ErrMessageCallback* callback) {
616 VLOG(6) << "AsyncSocket::setErrMessageCB() this=" << this
617 << ", fd=" << fd_ << ", callback=" << callback
618 << ", state=" << state_;
620 // Short circuit if callback is the same as the existing errMessageCallback_.
621 if (callback == errMessageCallback_) {
625 if (!msgErrQueueSupported) {
626 // Per-socket error message queue is not supported on this platform.
627 return invalidState(callback);
630 DestructorGuard dg(this);
631 assert(eventBase_->isInEventBaseThread());
633 if (callback == nullptr) {
634 // We should be able to reset the callback regardless of the
635 // socket state. It's important to have a reliable callback
636 // cancellation mechanism.
637 errMessageCallback_ = callback;
641 switch ((StateEnum)state_) {
642 case StateEnum::CONNECTING:
643 case StateEnum::FAST_OPEN:
644 case StateEnum::ESTABLISHED: {
645 errMessageCallback_ = callback;
648 case StateEnum::CLOSED:
649 case StateEnum::ERROR:
650 // We should never reach here. SHUT_READ should always be set
651 // if we are in STATE_CLOSED or STATE_ERROR.
653 return invalidState(callback);
654 case StateEnum::UNINIT:
655 // We do not allow setReadCallback() to be called before we start
657 return invalidState(callback);
660 // We don't put a default case in the switch statement, so that the compiler
661 // will warn us to update the switch statement if a new state is added.
662 return invalidState(callback);
665 AsyncSocket::ErrMessageCallback* AsyncSocket::getErrMessageCallback() const {
666 return errMessageCallback_;
669 void AsyncSocket::setSendMsgParamCB(SendMsgParamsCallback* callback) {
670 sendMsgParamCallback_ = callback;
673 AsyncSocket::SendMsgParamsCallback* AsyncSocket::getSendMsgParamsCB() const {
674 return sendMsgParamCallback_;
677 void AsyncSocket::setReadCB(ReadCallback *callback) {
678 VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
679 << ", callback=" << callback << ", state=" << state_;
681 // Short circuit if callback is the same as the existing readCallback_.
683 // Note that this is needed for proper functioning during some cleanup cases.
684 // During cleanup we allow setReadCallback(nullptr) to be called even if the
685 // read callback is already unset and we have been detached from an event
686 // base. This check prevents us from asserting
687 // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
688 if (callback == readCallback_) {
692 /* We are removing a read callback */
693 if (callback == nullptr &&
694 immediateReadHandler_.isLoopCallbackScheduled()) {
695 immediateReadHandler_.cancelLoopCallback();
698 if (shutdownFlags_ & SHUT_READ) {
699 // Reads have already been shut down on this socket.
701 // Allow setReadCallback(nullptr) to be called in this case, but don't
702 // allow a new callback to be set.
704 // For example, setReadCallback(nullptr) can happen after an error if we
705 // invoke some other error callback before invoking readError(). The other
706 // error callback that is invoked first may go ahead and clear the read
707 // callback before we get a chance to invoke readError().
708 if (callback != nullptr) {
709 return invalidState(callback);
711 assert((eventFlags_ & EventHandler::READ) == 0);
712 readCallback_ = nullptr;
716 DestructorGuard dg(this);
717 assert(eventBase_->isInEventBaseThread());
719 switch ((StateEnum)state_) {
720 case StateEnum::CONNECTING:
721 case StateEnum::FAST_OPEN:
722 // For convenience, we allow the read callback to be set while we are
723 // still connecting. We just store the callback for now. Once the
724 // connection completes we'll register for read events.
725 readCallback_ = callback;
727 case StateEnum::ESTABLISHED:
729 readCallback_ = callback;
730 uint16_t oldFlags = eventFlags_;
732 eventFlags_ |= EventHandler::READ;
734 eventFlags_ &= ~EventHandler::READ;
737 // Update our registration if our flags have changed
738 if (eventFlags_ != oldFlags) {
739 // We intentionally ignore the return value here.
740 // updateEventRegistration() will move us into the error state if it
741 // fails, and we don't need to do anything else here afterwards.
742 (void)updateEventRegistration();
746 checkForImmediateRead();
750 case StateEnum::CLOSED:
751 case StateEnum::ERROR:
752 // We should never reach here. SHUT_READ should always be set
753 // if we are in STATE_CLOSED or STATE_ERROR.
755 return invalidState(callback);
756 case StateEnum::UNINIT:
757 // We do not allow setReadCallback() to be called before we start
759 return invalidState(callback);
762 // We don't put a default case in the switch statement, so that the compiler
763 // will warn us to update the switch statement if a new state is added.
764 return invalidState(callback);
767 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
768 return readCallback_;
771 void AsyncSocket::write(WriteCallback* callback,
772 const void* buf, size_t bytes, WriteFlags flags) {
774 op.iov_base = const_cast<void*>(buf);
776 writeImpl(callback, &op, 1, unique_ptr<IOBuf>(), flags);
779 void AsyncSocket::writev(WriteCallback* callback,
783 writeImpl(callback, vec, count, unique_ptr<IOBuf>(), flags);
786 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
788 constexpr size_t kSmallSizeMax = 64;
789 size_t count = buf->countChainElements();
790 if (count <= kSmallSizeMax) {
791 // suppress "warning: variable length array 'vec' is used [-Wvla]"
793 FOLLY_GCC_DISABLE_WARNING("-Wvla")
794 iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA, count, kSmallSizeMax)];
797 writeChainImpl(callback, vec, count, std::move(buf), flags);
799 iovec* vec = new iovec[count];
800 writeChainImpl(callback, vec, count, std::move(buf), flags);
805 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
806 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
807 size_t veclen = buf->fillIov(vec, count);
808 writeImpl(callback, vec, veclen, std::move(buf), flags);
811 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
812 size_t count, unique_ptr<IOBuf>&& buf,
814 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
815 << ", callback=" << callback << ", count=" << count
816 << ", state=" << state_;
817 DestructorGuard dg(this);
818 unique_ptr<IOBuf>ioBuf(std::move(buf));
819 assert(eventBase_->isInEventBaseThread());
821 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
822 // No new writes may be performed after the write side of the socket has
825 // We could just call callback->writeError() here to fail just this write.
826 // However, fail hard and use invalidState() to fail all outstanding
827 // callbacks and move the socket into the error state. There's most likely
828 // a bug in the caller's code, so we abort everything rather than trying to
829 // proceed as best we can.
830 return invalidState(callback);
833 uint32_t countWritten = 0;
834 uint32_t partialWritten = 0;
835 ssize_t bytesWritten = 0;
836 bool mustRegister = false;
837 if ((state_ == StateEnum::ESTABLISHED || state_ == StateEnum::FAST_OPEN) &&
839 if (writeReqHead_ == nullptr) {
840 // If we are established and there are no other writes pending,
841 // we can attempt to perform the write immediately.
842 assert(writeReqTail_ == nullptr);
843 assert((eventFlags_ & EventHandler::WRITE) == 0);
845 auto writeResult = performWrite(
846 vec, uint32_t(count), flags, &countWritten, &partialWritten);
847 bytesWritten = writeResult.writeReturn;
848 if (bytesWritten < 0) {
849 auto errnoCopy = errno;
850 if (writeResult.exception) {
851 return failWrite(__func__, callback, 0, *writeResult.exception);
853 AsyncSocketException ex(
854 AsyncSocketException::INTERNAL_ERROR,
855 withAddr("writev failed"),
857 return failWrite(__func__, callback, 0, ex);
858 } else if (countWritten == count) {
859 // We successfully wrote everything.
860 // Invoke the callback and return.
862 callback->writeSuccess();
865 } else { // continue writing the next writeReq
866 if (bufferCallback_) {
867 bufferCallback_->onEgressBuffered();
871 // Writes might put the socket back into connecting state
872 // if TFO is enabled, and using TFO fails.
873 // This means that write timeouts would not be active, however
874 // connect timeouts would affect this stage.
878 } else if (!connecting()) {
879 // Invalid state for writing
880 return invalidState(callback);
883 // Create a new WriteRequest to add to the queue
886 req = BytesWriteRequest::newRequest(
890 uint32_t(count - countWritten),
892 uint32_t(bytesWritten),
895 } catch (const std::exception& ex) {
896 // we mainly expect to catch std::bad_alloc here
897 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
898 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
899 return failWrite(__func__, callback, size_t(bytesWritten), tex);
902 if (writeReqTail_ == nullptr) {
903 assert(writeReqHead_ == nullptr);
904 writeReqHead_ = writeReqTail_ = req;
906 writeReqTail_->append(req);
910 // Register for write events if are established and not currently
911 // waiting on write events
913 assert(state_ == StateEnum::ESTABLISHED);
914 assert((eventFlags_ & EventHandler::WRITE) == 0);
915 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
916 assert(state_ == StateEnum::ERROR);
919 if (sendTimeout_ > 0) {
920 // Schedule a timeout to fire if the write takes too long.
921 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
922 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
923 withAddr("failed to schedule send timeout"));
924 return failWrite(__func__, ex);
930 void AsyncSocket::writeRequest(WriteRequest* req) {
931 if (writeReqTail_ == nullptr) {
932 assert(writeReqHead_ == nullptr);
933 writeReqHead_ = writeReqTail_ = req;
936 writeReqTail_->append(req);
941 void AsyncSocket::close() {
942 VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
943 << ", state=" << state_ << ", shutdownFlags="
944 << std::hex << (int) shutdownFlags_;
946 // close() is only different from closeNow() when there are pending writes
947 // that need to drain before we can close. In all other cases, just call
950 // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
951 // STATE_ERROR if close() is invoked while a previous closeNow() or failure
952 // is still running. (e.g., If there are multiple pending writes, and we
953 // call writeError() on the first one, it may call close(). In this case we
954 // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
955 // writes will still be in the queue.)
957 // We only need to drain pending writes if we are still in STATE_CONNECTING
958 // or STATE_ESTABLISHED
959 if ((writeReqHead_ == nullptr) ||
960 !(state_ == StateEnum::CONNECTING ||
961 state_ == StateEnum::ESTABLISHED)) {
966 // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
967 // destroyed until close() returns.
968 DestructorGuard dg(this);
969 assert(eventBase_->isInEventBaseThread());
971 // Since there are write requests pending, we have to set the
972 // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
973 // connect finishes and we finish writing these requests.
975 // Set SHUT_READ to indicate that reads are shut down, and set the
976 // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
977 // pending writes complete.
978 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
980 // If a read callback is set, invoke readEOF() immediately to inform it that
981 // the socket has been closed and no more data can be read.
983 // Disable reads if they are enabled
984 if (!updateEventRegistration(0, EventHandler::READ)) {
985 // We're now in the error state; callbacks have been cleaned up
986 assert(state_ == StateEnum::ERROR);
987 assert(readCallback_ == nullptr);
989 ReadCallback* callback = readCallback_;
990 readCallback_ = nullptr;
996 void AsyncSocket::closeNow() {
997 VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
998 << ", state=" << state_ << ", shutdownFlags="
999 << std::hex << (int) shutdownFlags_;
1000 DestructorGuard dg(this);
1001 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
1004 case StateEnum::ESTABLISHED:
1005 case StateEnum::CONNECTING:
1006 case StateEnum::FAST_OPEN: {
1007 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1008 state_ = StateEnum::CLOSED;
1010 // If the write timeout was set, cancel it.
1011 writeTimeout_.cancelTimeout();
1013 // If we are registered for I/O events, unregister.
1014 if (eventFlags_ != EventHandler::NONE) {
1015 eventFlags_ = EventHandler::NONE;
1016 if (!updateEventRegistration()) {
1017 // We will have been moved into the error state.
1018 assert(state_ == StateEnum::ERROR);
1023 if (immediateReadHandler_.isLoopCallbackScheduled()) {
1024 immediateReadHandler_.cancelLoopCallback();
1028 ioHandler_.changeHandlerFD(-1);
1032 invokeConnectErr(socketClosedLocallyEx);
1034 failAllWrites(socketClosedLocallyEx);
1036 if (readCallback_) {
1037 ReadCallback* callback = readCallback_;
1038 readCallback_ = nullptr;
1039 callback->readEOF();
1043 case StateEnum::CLOSED:
1044 // Do nothing. It's possible that we are being called recursively
1045 // from inside a callback that we invoked inside another call to close()
1046 // that is still running.
1048 case StateEnum::ERROR:
1049 // Do nothing. The error handling code has performed (or is performing)
1052 case StateEnum::UNINIT:
1053 assert(eventFlags_ == EventHandler::NONE);
1054 assert(connectCallback_ == nullptr);
1055 assert(readCallback_ == nullptr);
1056 assert(writeReqHead_ == nullptr);
1057 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1058 state_ = StateEnum::CLOSED;
1062 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
1063 << ") called in unknown state " << state_;
1066 void AsyncSocket::closeWithReset() {
1067 // Enable SO_LINGER, with the linger timeout set to 0.
1068 // This will trigger a TCP reset when we close the socket.
1070 struct linger optLinger = {1, 0};
1071 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
1072 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
1073 << "on " << fd_ << ": errno=" << errno;
1077 // Then let closeNow() take care of the rest
1081 void AsyncSocket::shutdownWrite() {
1082 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
1083 << ", state=" << state_ << ", shutdownFlags="
1084 << std::hex << (int) shutdownFlags_;
1086 // If there are no pending writes, shutdownWrite() is identical to
1087 // shutdownWriteNow().
1088 if (writeReqHead_ == nullptr) {
1093 assert(eventBase_->isInEventBaseThread());
1095 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
1096 // shutdown will be performed once all writes complete.
1097 shutdownFlags_ |= SHUT_WRITE_PENDING;
1100 void AsyncSocket::shutdownWriteNow() {
1101 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
1102 << ", fd=" << fd_ << ", state=" << state_
1103 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
1105 if (shutdownFlags_ & SHUT_WRITE) {
1106 // Writes are already shutdown; nothing else to do.
1110 // If SHUT_READ is already set, just call closeNow() to completely
1111 // close the socket. This can happen if close() was called with writes
1112 // pending, and then shutdownWriteNow() is called before all pending writes
1114 if (shutdownFlags_ & SHUT_READ) {
1119 DestructorGuard dg(this);
1120 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
1122 switch (static_cast<StateEnum>(state_)) {
1123 case StateEnum::ESTABLISHED:
1125 shutdownFlags_ |= SHUT_WRITE;
1127 // If the write timeout was set, cancel it.
1128 writeTimeout_.cancelTimeout();
1130 // If we are registered for write events, unregister.
1131 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1132 // We will have been moved into the error state.
1133 assert(state_ == StateEnum::ERROR);
1137 // Shutdown writes on the file descriptor
1138 shutdown(fd_, SHUT_WR);
1140 // Immediately fail all write requests
1141 failAllWrites(socketShutdownForWritesEx);
1144 case StateEnum::CONNECTING:
1146 // Set the SHUT_WRITE_PENDING flag.
1147 // When the connection completes, it will check this flag,
1148 // shutdown the write half of the socket, and then set SHUT_WRITE.
1149 shutdownFlags_ |= SHUT_WRITE_PENDING;
1151 // Immediately fail all write requests
1152 failAllWrites(socketShutdownForWritesEx);
1155 case StateEnum::UNINIT:
1156 // Callers normally shouldn't call shutdownWriteNow() before the socket
1157 // even starts connecting. Nonetheless, go ahead and set
1158 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
1159 // immediately shut down the write side of the socket.
1160 shutdownFlags_ |= SHUT_WRITE_PENDING;
1162 case StateEnum::FAST_OPEN:
1163 // In fast open state we haven't call connected yet, and if we shutdown
1164 // the writes, we will never try to call connect, so shut everything down
1165 shutdownFlags_ |= SHUT_WRITE;
1166 // Immediately fail all write requests
1167 failAllWrites(socketShutdownForWritesEx);
1169 case StateEnum::CLOSED:
1170 case StateEnum::ERROR:
1171 // We should never get here. SHUT_WRITE should always be set
1172 // in STATE_CLOSED and STATE_ERROR.
1173 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
1174 << ", fd=" << fd_ << ") in unexpected state " << state_
1175 << " with SHUT_WRITE not set ("
1176 << std::hex << (int) shutdownFlags_ << ")";
1181 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
1182 << fd_ << ") called in unknown state " << state_;
1185 bool AsyncSocket::readable() const {
1189 struct pollfd fds[1];
1191 fds[0].events = POLLIN;
1193 int rc = poll(fds, 1, 0);
1197 bool AsyncSocket::writable() const {
1201 struct pollfd fds[1];
1203 fds[0].events = POLLOUT;
1205 int rc = poll(fds, 1, 0);
1209 bool AsyncSocket::isPending() const {
1210 return ioHandler_.isPending();
1213 bool AsyncSocket::hangup() const {
1215 // sanity check, no one should ask for hangup if we are not connected.
1219 #ifdef POLLRDHUP // Linux-only
1220 struct pollfd fds[1];
1222 fds[0].events = POLLRDHUP|POLLHUP;
1225 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1231 bool AsyncSocket::good() const {
1233 (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN ||
1234 state_ == StateEnum::ESTABLISHED) &&
1235 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1238 bool AsyncSocket::error() const {
1239 return (state_ == StateEnum::ERROR);
1242 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1243 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1244 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1245 << ", state=" << state_ << ", events="
1246 << std::hex << eventFlags_ << ")";
1247 assert(eventBase_ == nullptr);
1248 assert(eventBase->isInEventBaseThread());
1250 eventBase_ = eventBase;
1251 ioHandler_.attachEventBase(eventBase);
1252 writeTimeout_.attachEventBase(eventBase);
1254 evbChangeCb_->evbAttached(this);
1258 void AsyncSocket::detachEventBase() {
1259 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1260 << ", old evb=" << eventBase_ << ", state=" << state_
1261 << ", events=" << std::hex << eventFlags_ << ")";
1262 assert(eventBase_ != nullptr);
1263 assert(eventBase_->isInEventBaseThread());
1265 eventBase_ = nullptr;
1266 ioHandler_.detachEventBase();
1267 writeTimeout_.detachEventBase();
1269 evbChangeCb_->evbDetached(this);
1273 bool AsyncSocket::isDetachable() const {
1274 DCHECK(eventBase_ != nullptr);
1275 DCHECK(eventBase_->isInEventBaseThread());
1277 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1280 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1281 if (!localAddr_.isInitialized()) {
1282 localAddr_.setFromLocalAddress(fd_);
1284 *address = localAddr_;
1287 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1288 if (!addr_.isInitialized()) {
1289 addr_.setFromPeerAddress(fd_);
1294 bool AsyncSocket::getTFOSucceded() const {
1295 return detail::tfo_succeeded(fd_);
1298 int AsyncSocket::setNoDelay(bool noDelay) {
1300 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1301 << this << "(state=" << state_ << ")";
1306 int value = noDelay ? 1 : 0;
1307 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1308 int errnoCopy = errno;
1309 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1310 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1311 << strerror(errnoCopy);
1318 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1320 #ifndef TCP_CONGESTION
1321 #define TCP_CONGESTION 13
1325 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1326 << "socket " << this << "(state=" << state_ << ")";
1336 socklen_t(cname.length() + 1)) != 0) {
1337 int errnoCopy = errno;
1338 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1339 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1340 << strerror(errnoCopy);
1347 int AsyncSocket::setQuickAck(bool quickack) {
1350 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1351 << this << "(state=" << state_ << ")";
1356 #ifdef TCP_QUICKACK // Linux-only
1357 int value = quickack ? 1 : 0;
1358 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1359 int errnoCopy = errno;
1360 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1361 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1362 << strerror(errnoCopy);
1372 int AsyncSocket::setSendBufSize(size_t bufsize) {
1374 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1375 << this << "(state=" << state_ << ")";
1379 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1380 int errnoCopy = errno;
1381 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1382 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1383 << strerror(errnoCopy);
1390 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1392 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1393 << this << "(state=" << state_ << ")";
1397 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1398 int errnoCopy = errno;
1399 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1400 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1401 << strerror(errnoCopy);
1408 int AsyncSocket::setTCPProfile(int profd) {
1410 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1411 << this << "(state=" << state_ << ")";
1415 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1416 int errnoCopy = errno;
1417 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1418 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1419 << strerror(errnoCopy);
1426 void AsyncSocket::ioReady(uint16_t events) noexcept {
1427 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd=" << fd_
1428 << ", events=" << std::hex << events << ", state=" << state_;
1429 DestructorGuard dg(this);
1430 assert(events & EventHandler::READ_WRITE);
1431 assert(eventBase_->isInEventBaseThread());
1433 uint16_t relevantEvents = uint16_t(events & EventHandler::READ_WRITE);
1434 EventBase* originalEventBase = eventBase_;
1435 // If we got there it means that either EventHandler::READ or
1436 // EventHandler::WRITE is set. Any of these flags can
1437 // indicate that there are messages available in the socket
1438 // error message queue.
1439 handleErrMessages();
1441 // Return now if handleErrMessages() detached us from our EventBase
1442 if (eventBase_ != originalEventBase) {
1446 if (relevantEvents == EventHandler::READ) {
1448 } else if (relevantEvents == EventHandler::WRITE) {
1450 } else if (relevantEvents == EventHandler::READ_WRITE) {
1451 // If both read and write events are ready, process writes first.
1454 // Return now if handleWrite() detached us from our EventBase
1455 if (eventBase_ != originalEventBase) {
1459 // Only call handleRead() if a read callback is still installed.
1460 // (It's possible that the read callback was uninstalled during
1462 if (readCallback_) {
1466 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1467 << std::hex << events << "(this=" << this << ")";
1472 AsyncSocket::ReadResult
1473 AsyncSocket::performRead(void** buf, size_t* buflen, size_t* /* offset */) {
1474 VLOG(5) << "AsyncSocket::performRead() this=" << this << ", buf=" << *buf
1475 << ", buflen=" << *buflen;
1477 if (preReceivedData_ && !preReceivedData_->empty()) {
1478 VLOG(5) << "AsyncSocket::performRead() this=" << this
1479 << ", reading pre-received data";
1481 io::Cursor cursor(preReceivedData_.get());
1482 auto len = cursor.pullAtMost(*buf, *buflen);
1485 queue.append(std::move(preReceivedData_));
1486 queue.trimStart(len);
1487 preReceivedData_ = queue.move();
1489 appBytesReceived_ += len;
1490 return ReadResult(len);
1493 ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT);
1495 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1496 // No more data to read right now.
1497 return ReadResult(READ_BLOCKING);
1499 return ReadResult(READ_ERROR);
1502 appBytesReceived_ += bytes;
1503 return ReadResult(bytes);
1507 void AsyncSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1508 // no matter what, buffer should be preapared for non-ssl socket
1509 CHECK(readCallback_);
1510 readCallback_->getReadBuffer(buf, buflen);
1513 void AsyncSocket::handleErrMessages() noexcept {
1514 // This method has non-empty implementation only for platforms
1515 // supporting per-socket error queues.
1516 VLOG(5) << "AsyncSocket::handleErrMessages() this=" << this << ", fd=" << fd_
1517 << ", state=" << state_;
1518 if (errMessageCallback_ == nullptr) {
1519 VLOG(7) << "AsyncSocket::handleErrMessages(): "
1520 << "no callback installed - exiting.";
1530 entry.iov_base = &data;
1531 entry.iov_len = sizeof(data);
1532 msg.msg_iov = &entry;
1534 msg.msg_name = nullptr;
1535 msg.msg_namelen = 0;
1536 msg.msg_control = ctrl;
1537 msg.msg_controllen = sizeof(ctrl);
1542 ret = recvmsg(fd_, &msg, MSG_ERRQUEUE);
1543 VLOG(5) << "AsyncSocket::handleErrMessages(): recvmsg returned " << ret;
1546 if (errno != EAGAIN) {
1547 auto errnoCopy = errno;
1548 LOG(ERROR) << "::recvmsg exited with code " << ret
1549 << ", errno: " << errnoCopy;
1550 AsyncSocketException ex(
1551 AsyncSocketException::INTERNAL_ERROR,
1552 withAddr("recvmsg() failed"),
1554 failErrMessageRead(__func__, ex);
1559 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
1561 cmsg->cmsg_len != 0 &&
1562 errMessageCallback_ != nullptr;
1563 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1564 errMessageCallback_->errMessage(*cmsg);
1567 #endif //MSG_ERRQUEUE
1570 void AsyncSocket::handleRead() noexcept {
1571 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1572 << ", state=" << state_;
1573 assert(state_ == StateEnum::ESTABLISHED);
1574 assert((shutdownFlags_ & SHUT_READ) == 0);
1575 assert(readCallback_ != nullptr);
1576 assert(eventFlags_ & EventHandler::READ);
1579 // - a read attempt would block
1580 // - readCallback_ is uninstalled
1581 // - the number of loop iterations exceeds the optional maximum
1582 // - this AsyncSocket is moved to another EventBase
1584 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1585 // which is why need to check for it here.
1587 // The last bullet point is slightly subtle. readDataAvailable() may also
1588 // detach this socket from this EventBase. However, before
1589 // readDataAvailable() returns another thread may pick it up, attach it to
1590 // a different EventBase, and install another readCallback_. We need to
1591 // exit immediately after readDataAvailable() returns if the eventBase_ has
1592 // changed. (The caller must perform some sort of locking to transfer the
1593 // AsyncSocket between threads properly. This will be sufficient to ensure
1594 // that this thread sees the updated eventBase_ variable after
1595 // readDataAvailable() returns.)
1596 uint16_t numReads = 0;
1597 EventBase* originalEventBase = eventBase_;
1598 while (readCallback_ && eventBase_ == originalEventBase) {
1599 // Get the buffer to read into.
1600 void* buf = nullptr;
1601 size_t buflen = 0, offset = 0;
1603 prepareReadBuffer(&buf, &buflen);
1604 VLOG(5) << "prepareReadBuffer() buf=" << buf << ", buflen=" << buflen;
1605 } catch (const AsyncSocketException& ex) {
1606 return failRead(__func__, ex);
1607 } catch (const std::exception& ex) {
1608 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1609 string("ReadCallback::getReadBuffer() "
1610 "threw exception: ") +
1612 return failRead(__func__, tex);
1614 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1615 "ReadCallback::getReadBuffer() threw "
1616 "non-exception type");
1617 return failRead(__func__, ex);
1619 if (!isBufferMovable_ && (buf == nullptr || buflen == 0)) {
1620 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1621 "ReadCallback::getReadBuffer() returned "
1623 return failRead(__func__, ex);
1627 auto readResult = performRead(&buf, &buflen, &offset);
1628 auto bytesRead = readResult.readReturn;
1629 VLOG(4) << "this=" << this << ", AsyncSocket::handleRead() got "
1630 << bytesRead << " bytes";
1631 if (bytesRead > 0) {
1632 if (!isBufferMovable_) {
1633 readCallback_->readDataAvailable(size_t(bytesRead));
1635 CHECK(kOpenSslModeMoveBufferOwnership);
1636 VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
1637 << "buf=" << buf << ", " << bytesRead << "/" << buflen
1638 << ", offset=" << offset;
1639 auto readBuf = folly::IOBuf::takeOwnership(buf, buflen);
1640 readBuf->trimStart(offset);
1641 readBuf->trimEnd(buflen - offset - bytesRead);
1642 readCallback_->readBufferAvailable(std::move(readBuf));
1645 // Fall through and continue around the loop if the read
1646 // completely filled the available buffer.
1647 // Note that readCallback_ may have been uninstalled or changed inside
1648 // readDataAvailable().
1649 if (size_t(bytesRead) < buflen) {
1652 } else if (bytesRead == READ_BLOCKING) {
1653 // No more data to read right now.
1655 } else if (bytesRead == READ_ERROR) {
1656 readErr_ = READ_ERROR;
1657 if (readResult.exception) {
1658 return failRead(__func__, *readResult.exception);
1660 auto errnoCopy = errno;
1661 AsyncSocketException ex(
1662 AsyncSocketException::INTERNAL_ERROR,
1663 withAddr("recv() failed"),
1665 return failRead(__func__, ex);
1667 assert(bytesRead == READ_EOF);
1668 readErr_ = READ_EOF;
1670 shutdownFlags_ |= SHUT_READ;
1671 if (!updateEventRegistration(0, EventHandler::READ)) {
1672 // we've already been moved into STATE_ERROR
1673 assert(state_ == StateEnum::ERROR);
1674 assert(readCallback_ == nullptr);
1678 ReadCallback* callback = readCallback_;
1679 readCallback_ = nullptr;
1680 callback->readEOF();
1683 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1684 if (readCallback_ != nullptr) {
1685 // We might still have data in the socket.
1686 // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
1687 scheduleImmediateRead();
1695 * This function attempts to write as much data as possible, until no more data
1698 * - If it sends all available data, it unregisters for write events, and stops
1699 * the writeTimeout_.
1701 * - If not all of the data can be sent immediately, it reschedules
1702 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1703 * registered for write events.
1705 void AsyncSocket::handleWrite() noexcept {
1706 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1707 << ", state=" << state_;
1708 DestructorGuard dg(this);
1710 if (state_ == StateEnum::CONNECTING) {
1716 assert(state_ == StateEnum::ESTABLISHED);
1717 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1718 assert(writeReqHead_ != nullptr);
1720 // Loop until we run out of write requests,
1721 // or until this socket is moved to another EventBase.
1722 // (See the comment in handleRead() explaining how this can happen.)
1723 EventBase* originalEventBase = eventBase_;
1724 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1725 auto writeResult = writeReqHead_->performWrite();
1726 if (writeResult.writeReturn < 0) {
1727 if (writeResult.exception) {
1728 return failWrite(__func__, *writeResult.exception);
1730 auto errnoCopy = errno;
1731 AsyncSocketException ex(
1732 AsyncSocketException::INTERNAL_ERROR,
1733 withAddr("writev() failed"),
1735 return failWrite(__func__, ex);
1736 } else if (writeReqHead_->isComplete()) {
1737 // We finished this request
1738 WriteRequest* req = writeReqHead_;
1739 writeReqHead_ = req->getNext();
1741 if (writeReqHead_ == nullptr) {
1742 writeReqTail_ = nullptr;
1743 // This is the last write request.
1744 // Unregister for write events and cancel the send timer
1745 // before we invoke the callback. We have to update the state properly
1746 // before calling the callback, since it may want to detach us from
1748 if (eventFlags_ & EventHandler::WRITE) {
1749 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1750 assert(state_ == StateEnum::ERROR);
1753 // Stop the send timeout
1754 writeTimeout_.cancelTimeout();
1756 assert(!writeTimeout_.isScheduled());
1758 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
1759 // we finish sending the last write request.
1761 // We have to do this before invoking writeSuccess(), since
1762 // writeSuccess() may detach us from our EventBase.
1763 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
1764 assert(connectCallback_ == nullptr);
1765 shutdownFlags_ |= SHUT_WRITE;
1767 if (shutdownFlags_ & SHUT_READ) {
1768 // Reads have already been shutdown. Fully close the socket and
1769 // move to STATE_CLOSED.
1771 // Note: This code currently moves us to STATE_CLOSED even if
1772 // close() hasn't ever been called. This can occur if we have
1773 // received EOF from the peer and shutdownWrite() has been called
1774 // locally. Should we bother staying in STATE_ESTABLISHED in this
1775 // case, until close() is actually called? I can't think of a
1776 // reason why we would need to do so. No other operations besides
1777 // calling close() or destroying the socket can be performed at
1779 assert(readCallback_ == nullptr);
1780 state_ = StateEnum::CLOSED;
1782 ioHandler_.changeHandlerFD(-1);
1786 // Reads are still enabled, so we are only doing a half-shutdown
1787 shutdown(fd_, SHUT_WR);
1792 // Invoke the callback
1793 WriteCallback* callback = req->getCallback();
1796 callback->writeSuccess();
1798 // We'll continue around the loop, trying to write another request
1801 if (bufferCallback_) {
1802 bufferCallback_->onEgressBuffered();
1804 writeReqHead_->consume();
1805 // Stop after a partial write; it's highly likely that a subsequent write
1806 // attempt will just return EAGAIN.
1808 // Ensure that we are registered for write events.
1809 if ((eventFlags_ & EventHandler::WRITE) == 0) {
1810 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1811 assert(state_ == StateEnum::ERROR);
1816 // Reschedule the send timeout, since we have made some write progress.
1817 if (sendTimeout_ > 0) {
1818 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1819 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1820 withAddr("failed to reschedule write timeout"));
1821 return failWrite(__func__, ex);
1827 if (!writeReqHead_ && bufferCallback_) {
1828 bufferCallback_->onEgressBufferCleared();
1832 void AsyncSocket::checkForImmediateRead() noexcept {
1833 // We currently don't attempt to perform optimistic reads in AsyncSocket.
1834 // (However, note that some subclasses do override this method.)
1836 // Simply calling handleRead() here would be bad, as this would call
1837 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
1838 // buffer even though no data may be available. This would waste lots of
1839 // memory, since the buffer will sit around unused until the socket actually
1840 // becomes readable.
1842 // Checking if the socket is readable now also seems like it would probably
1843 // be a pessimism. In most cases it probably wouldn't be readable, and we
1844 // would just waste an extra system call. Even if it is readable, waiting to
1845 // find out from libevent on the next event loop doesn't seem that bad.
1847 // The exception to this is if we have pre-received data. In that case there
1848 // is definitely data available immediately.
1849 if (preReceivedData_ && !preReceivedData_->empty()) {
1854 void AsyncSocket::handleInitialReadWrite() noexcept {
1855 // Our callers should already be holding a DestructorGuard, but grab
1856 // one here just to make sure, in case one of our calling code paths ever
1858 DestructorGuard dg(this);
1859 // If we have a readCallback_, make sure we enable read events. We
1860 // may already be registered for reads if connectSuccess() set
1861 // the read calback.
1862 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
1863 assert(state_ == StateEnum::ESTABLISHED);
1864 assert((shutdownFlags_ & SHUT_READ) == 0);
1865 if (!updateEventRegistration(EventHandler::READ, 0)) {
1866 assert(state_ == StateEnum::ERROR);
1869 checkForImmediateRead();
1870 } else if (readCallback_ == nullptr) {
1871 // Unregister for read events.
1872 updateEventRegistration(0, EventHandler::READ);
1875 // If we have write requests pending, try to send them immediately.
1876 // Since we just finished accepting, there is a very good chance that we can
1877 // write without blocking.
1879 // However, we only process them if EventHandler::WRITE is not already set,
1880 // which means that we're already blocked on a write attempt. (This can
1881 // happen if connectSuccess() called write() before returning.)
1882 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
1883 // Call handleWrite() to perform write processing.
1885 } else if (writeReqHead_ == nullptr) {
1886 // Unregister for write event.
1887 updateEventRegistration(0, EventHandler::WRITE);
1891 void AsyncSocket::handleConnect() noexcept {
1892 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
1893 << ", state=" << state_;
1894 assert(state_ == StateEnum::CONNECTING);
1895 // SHUT_WRITE can never be set while we are still connecting;
1896 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
1898 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1900 // In case we had a connect timeout, cancel the timeout
1901 writeTimeout_.cancelTimeout();
1902 // We don't use a persistent registration when waiting on a connect event,
1903 // so we have been automatically unregistered now. Update eventFlags_ to
1905 assert(eventFlags_ == EventHandler::WRITE);
1906 eventFlags_ = EventHandler::NONE;
1908 // Call getsockopt() to check if the connect succeeded
1910 socklen_t len = sizeof(error);
1911 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
1913 auto errnoCopy = errno;
1914 AsyncSocketException ex(
1915 AsyncSocketException::INTERNAL_ERROR,
1916 withAddr("error calling getsockopt() after connect"),
1918 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1919 << fd_ << " host=" << addr_.describe()
1920 << ") exception:" << ex.what();
1921 return failConnect(__func__, ex);
1925 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1926 "connect failed", error);
1927 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1928 << fd_ << " host=" << addr_.describe()
1929 << ") exception: " << ex.what();
1930 return failConnect(__func__, ex);
1933 // Move into STATE_ESTABLISHED
1934 state_ = StateEnum::ESTABLISHED;
1936 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
1937 // perform, immediately shutdown the write half of the socket.
1938 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
1939 // SHUT_READ shouldn't be set. If close() is called on the socket while we
1940 // are still connecting we just abort the connect rather than waiting for
1942 assert((shutdownFlags_ & SHUT_READ) == 0);
1943 shutdown(fd_, SHUT_WR);
1944 shutdownFlags_ |= SHUT_WRITE;
1947 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
1948 << "successfully connected; state=" << state_;
1950 // Remember the EventBase we are attached to, before we start invoking any
1951 // callbacks (since the callbacks may call detachEventBase()).
1952 EventBase* originalEventBase = eventBase_;
1954 invokeConnectSuccess();
1955 // Note that the connect callback may have changed our state.
1956 // (set or unset the read callback, called write(), closed the socket, etc.)
1957 // The following code needs to handle these situations correctly.
1959 // If the socket has been closed, readCallback_ and writeReqHead_ will
1960 // always be nullptr, so that will prevent us from trying to read or write.
1962 // The main thing to check for is if eventBase_ is still originalEventBase.
1963 // If not, we have been detached from this event base, so we shouldn't
1964 // perform any more operations.
1965 if (eventBase_ != originalEventBase) {
1969 handleInitialReadWrite();
1972 void AsyncSocket::timeoutExpired() noexcept {
1973 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
1974 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
1975 DestructorGuard dg(this);
1976 assert(eventBase_->isInEventBaseThread());
1978 if (state_ == StateEnum::CONNECTING) {
1979 // connect() timed out
1980 // Unregister for I/O events.
1981 if (connectCallback_) {
1982 AsyncSocketException ex(
1983 AsyncSocketException::TIMED_OUT,
1985 "connect timed out after {}ms", connectTimeout_.count()));
1986 failConnect(__func__, ex);
1988 // we faced a connect error without a connect callback, which could
1989 // happen due to TFO.
1990 AsyncSocketException ex(
1991 AsyncSocketException::TIMED_OUT, "write timed out during connection");
1992 failWrite(__func__, ex);
1995 // a normal write operation timed out
1996 AsyncSocketException ex(
1997 AsyncSocketException::TIMED_OUT,
1998 folly::sformat("write timed out after {}ms", sendTimeout_));
1999 failWrite(__func__, ex);
2003 ssize_t AsyncSocket::tfoSendMsg(int fd, struct msghdr* msg, int msg_flags) {
2004 return detail::tfo_sendmsg(fd, msg, msg_flags);
2007 AsyncSocket::WriteResult
2008 AsyncSocket::sendSocketMessage(int fd, struct msghdr* msg, int msg_flags) {
2009 ssize_t totalWritten = 0;
2010 if (state_ == StateEnum::FAST_OPEN) {
2011 sockaddr_storage addr;
2012 auto len = addr_.getAddress(&addr);
2013 msg->msg_name = &addr;
2014 msg->msg_namelen = len;
2015 totalWritten = tfoSendMsg(fd_, msg, msg_flags);
2016 if (totalWritten >= 0) {
2017 tfoFinished_ = true;
2018 state_ = StateEnum::ESTABLISHED;
2019 // We schedule this asynchrously so that we don't end up
2020 // invoking initial read or write while a write is in progress.
2021 scheduleInitialReadWrite();
2022 } else if (errno == EINPROGRESS) {
2023 VLOG(4) << "TFO falling back to connecting";
2024 // A normal sendmsg doesn't return EINPROGRESS, however
2025 // TFO might fallback to connecting if there is no
2027 state_ = StateEnum::CONNECTING;
2029 scheduleConnectTimeout();
2030 registerForConnectEvents();
2031 } catch (const AsyncSocketException& ex) {
2033 WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
2035 // Let's fake it that no bytes were written and return an errno.
2038 } else if (errno == EOPNOTSUPP) {
2039 // Try falling back to connecting.
2040 VLOG(4) << "TFO not supported";
2041 state_ = StateEnum::CONNECTING;
2043 int ret = socketConnect((const sockaddr*)&addr, len);
2045 // connect succeeded immediately
2046 // Treat this like no data was written.
2047 state_ = StateEnum::ESTABLISHED;
2048 scheduleInitialReadWrite();
2050 // If there was no exception during connections,
2051 // we would return that no bytes were written.
2054 } catch (const AsyncSocketException& ex) {
2056 WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
2058 } else if (errno == EAGAIN) {
2059 // Normally sendmsg would indicate that the write would block.
2060 // However in the fast open case, it would indicate that sendmsg
2061 // fell back to a connect. This is a return code from connect()
2062 // instead, and is an error condition indicating no fds available.
2065 std::make_unique<AsyncSocketException>(
2066 AsyncSocketException::UNKNOWN, "No more free local ports"));
2069 totalWritten = ::sendmsg(fd, msg, msg_flags);
2071 return WriteResult(totalWritten);
2074 AsyncSocket::WriteResult AsyncSocket::performWrite(
2078 uint32_t* countWritten,
2079 uint32_t* partialWritten) {
2080 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
2081 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
2082 // (since it may terminate the program if the main program doesn't explicitly
2085 msg.msg_name = nullptr;
2086 msg.msg_namelen = 0;
2087 msg.msg_iov = const_cast<iovec *>(vec);
2088 msg.msg_iovlen = std::min<size_t>(count, kIovMax);
2090 msg.msg_controllen = sendMsgParamCallback_->getAncillaryDataSize(flags);
2091 CHECK_GE(AsyncSocket::SendMsgParamsCallback::maxAncillaryDataSize,
2092 msg.msg_controllen);
2094 if (msg.msg_controllen != 0) {
2095 msg.msg_control = reinterpret_cast<char*>(alloca(msg.msg_controllen));
2096 sendMsgParamCallback_->getAncillaryData(flags, msg.msg_control);
2098 msg.msg_control = nullptr;
2100 int msg_flags = sendMsgParamCallback_->getFlags(flags);
2102 auto writeResult = sendSocketMessage(fd_, &msg, msg_flags);
2103 auto totalWritten = writeResult.writeReturn;
2104 if (totalWritten < 0) {
2105 bool tryAgain = (errno == EAGAIN);
2107 // Apple has a bug where doing a second write on a socket which we
2108 // have opened with TFO causes an ENOTCONN to be thrown. However the
2109 // socket is really connected, so treat ENOTCONN as a EAGAIN until
2110 // this bug is fixed.
2111 tryAgain |= (errno == ENOTCONN);
2113 if (!writeResult.exception && tryAgain) {
2114 // TCP buffer is full; we can't write any more data right now.
2116 *partialWritten = 0;
2117 return WriteResult(0);
2121 *partialWritten = 0;
2125 appBytesWritten_ += totalWritten;
2127 uint32_t bytesWritten;
2129 for (bytesWritten = uint32_t(totalWritten), n = 0; n < count; ++n) {
2130 const iovec* v = vec + n;
2131 if (v->iov_len > bytesWritten) {
2132 // Partial write finished in the middle of this iovec
2134 *partialWritten = bytesWritten;
2135 return WriteResult(totalWritten);
2138 bytesWritten -= uint32_t(v->iov_len);
2141 assert(bytesWritten == 0);
2143 *partialWritten = 0;
2144 return WriteResult(totalWritten);
2148 * Re-register the EventHandler after eventFlags_ has changed.
2150 * If an error occurs, fail() is called to move the socket into the error state
2151 * and call all currently installed callbacks. After an error, the
2152 * AsyncSocket is completely unregistered.
2154 * @return Returns true on succcess, or false on error.
2156 bool AsyncSocket::updateEventRegistration() {
2157 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
2158 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
2159 << ", events=" << std::hex << eventFlags_;
2160 assert(eventBase_->isInEventBaseThread());
2161 if (eventFlags_ == EventHandler::NONE) {
2162 ioHandler_.unregisterHandler();
2166 // Always register for persistent events, so we don't have to re-register
2167 // after being called back.
2168 if (!ioHandler_.registerHandler(
2169 uint16_t(eventFlags_ | EventHandler::PERSIST))) {
2170 eventFlags_ = EventHandler::NONE; // we're not registered after error
2171 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
2172 withAddr("failed to update AsyncSocket event registration"));
2173 fail("updateEventRegistration", ex);
2180 bool AsyncSocket::updateEventRegistration(uint16_t enable,
2182 uint16_t oldFlags = eventFlags_;
2183 eventFlags_ |= enable;
2184 eventFlags_ &= ~disable;
2185 if (eventFlags_ == oldFlags) {
2188 return updateEventRegistration();
2192 void AsyncSocket::startFail() {
2193 // startFail() should only be called once
2194 assert(state_ != StateEnum::ERROR);
2195 assert(getDestructorGuardCount() > 0);
2196 state_ = StateEnum::ERROR;
2197 // Ensure that SHUT_READ and SHUT_WRITE are set,
2198 // so all future attempts to read or write will be rejected
2199 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
2201 if (eventFlags_ != EventHandler::NONE) {
2202 eventFlags_ = EventHandler::NONE;
2203 ioHandler_.unregisterHandler();
2205 writeTimeout_.cancelTimeout();
2208 ioHandler_.changeHandlerFD(-1);
2213 void AsyncSocket::invokeAllErrors(const AsyncSocketException& ex) {
2214 invokeConnectErr(ex);
2217 if (readCallback_) {
2218 ReadCallback* callback = readCallback_;
2219 readCallback_ = nullptr;
2220 callback->readErr(ex);
2224 void AsyncSocket::finishFail() {
2225 assert(state_ == StateEnum::ERROR);
2226 assert(getDestructorGuardCount() > 0);
2228 AsyncSocketException ex(
2229 AsyncSocketException::INTERNAL_ERROR,
2230 withAddr("socket closing after error"));
2231 invokeAllErrors(ex);
2234 void AsyncSocket::finishFail(const AsyncSocketException& ex) {
2235 assert(state_ == StateEnum::ERROR);
2236 assert(getDestructorGuardCount() > 0);
2237 invokeAllErrors(ex);
2240 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
2241 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2242 << state_ << " host=" << addr_.describe()
2243 << "): failed in " << fn << "(): "
2249 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
2250 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2251 << state_ << " host=" << addr_.describe()
2252 << "): failed while connecting in " << fn << "(): "
2256 invokeConnectErr(ex);
2260 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
2261 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2262 << state_ << " host=" << addr_.describe()
2263 << "): failed while reading in " << fn << "(): "
2267 if (readCallback_ != nullptr) {
2268 ReadCallback* callback = readCallback_;
2269 readCallback_ = nullptr;
2270 callback->readErr(ex);
2276 void AsyncSocket::failErrMessageRead(const char* fn,
2277 const AsyncSocketException& ex) {
2278 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2279 << state_ << " host=" << addr_.describe()
2280 << "): failed while reading message in " << fn << "(): "
2284 if (errMessageCallback_ != nullptr) {
2285 ErrMessageCallback* callback = errMessageCallback_;
2286 errMessageCallback_ = nullptr;
2287 callback->errMessageError(ex);
2293 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
2294 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2295 << state_ << " host=" << addr_.describe()
2296 << "): failed while writing in " << fn << "(): "
2300 // Only invoke the first write callback, since the error occurred while
2301 // writing this request. Let any other pending write callbacks be invoked in
2303 if (writeReqHead_ != nullptr) {
2304 WriteRequest* req = writeReqHead_;
2305 writeReqHead_ = req->getNext();
2306 WriteCallback* callback = req->getCallback();
2307 uint32_t bytesWritten = req->getTotalBytesWritten();
2310 callback->writeErr(bytesWritten, ex);
2317 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
2318 size_t bytesWritten,
2319 const AsyncSocketException& ex) {
2320 // This version of failWrite() is used when the failure occurs before
2321 // we've added the callback to writeReqHead_.
2322 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2323 << state_ << " host=" << addr_.describe()
2324 <<"): failed while writing in " << fn << "(): "
2328 if (callback != nullptr) {
2329 callback->writeErr(bytesWritten, ex);
2335 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
2336 // Invoke writeError() on all write callbacks.
2337 // This is used when writes are forcibly shutdown with write requests
2338 // pending, or when an error occurs with writes pending.
2339 while (writeReqHead_ != nullptr) {
2340 WriteRequest* req = writeReqHead_;
2341 writeReqHead_ = req->getNext();
2342 WriteCallback* callback = req->getCallback();
2344 callback->writeErr(req->getTotalBytesWritten(), ex);
2350 void AsyncSocket::invalidState(ConnectCallback* callback) {
2351 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2352 << "): connect() called in invalid state " << state_;
2355 * The invalidState() methods don't use the normal failure mechanisms,
2356 * since we don't know what state we are in. We don't want to call
2357 * startFail()/finishFail() recursively if we are already in the middle of
2361 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
2362 "connect() called with socket in invalid state");
2363 connectEndTime_ = std::chrono::steady_clock::now();
2364 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2366 callback->connectErr(ex);
2369 // We can't use failConnect() here since connectCallback_
2370 // may already be set to another callback. Invoke this ConnectCallback
2371 // here; any other connectCallback_ will be invoked in finishFail()
2374 callback->connectErr(ex);
2380 void AsyncSocket::invalidState(ErrMessageCallback* callback) {
2381 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2382 << "): setErrMessageCB(" << callback
2383 << ") called in invalid state " << state_;
2385 AsyncSocketException ex(
2386 AsyncSocketException::NOT_OPEN,
2387 msgErrQueueSupported
2388 ? "setErrMessageCB() called with socket in invalid state"
2389 : "This platform does not support socket error message notifications");
2390 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2392 callback->errMessageError(ex);
2397 callback->errMessageError(ex);
2403 void AsyncSocket::invokeConnectErr(const AsyncSocketException& ex) {
2404 connectEndTime_ = std::chrono::steady_clock::now();
2405 if (connectCallback_) {
2406 ConnectCallback* callback = connectCallback_;
2407 connectCallback_ = nullptr;
2408 callback->connectErr(ex);
2412 void AsyncSocket::invokeConnectSuccess() {
2413 connectEndTime_ = std::chrono::steady_clock::now();
2414 if (connectCallback_) {
2415 ConnectCallback* callback = connectCallback_;
2416 connectCallback_ = nullptr;
2417 callback->connectSuccess();
2421 void AsyncSocket::invalidState(ReadCallback* callback) {
2422 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2423 << "): setReadCallback(" << callback
2424 << ") called in invalid state " << state_;
2426 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2427 "setReadCallback() called with socket in "
2429 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2431 callback->readErr(ex);
2436 callback->readErr(ex);
2442 void AsyncSocket::invalidState(WriteCallback* callback) {
2443 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2444 << "): write() called in invalid state " << state_;
2446 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2447 withAddr("write() called with socket in invalid state"));
2448 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2450 callback->writeErr(0, ex);
2455 callback->writeErr(0, ex);
2461 void AsyncSocket::doClose() {
2462 if (fd_ == -1) return;
2463 if (shutdownSocketSet_) {
2464 shutdownSocketSet_->close(fd_);
2471 std::ostream& operator << (std::ostream& os,
2472 const AsyncSocket::StateEnum& state) {
2473 os << static_cast<int>(state);
2477 std::string AsyncSocket::withAddr(const std::string& s) {
2478 // Don't use addr_ directly because it may not be initialized
2479 // e.g. if constructed from fd
2480 folly::SocketAddress peer, local;
2482 getPeerAddress(&peer);
2483 getLocalAddress(&local);
2484 } catch (const std::exception&) {
2489 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";
2492 void AsyncSocket::setBufferCallback(BufferCallback* cb) {
2493 bufferCallback_ = cb;