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 AsyncSocket::AsyncSocket()
189 : eventBase_(nullptr),
190 writeTimeout_(this, nullptr),
191 ioHandler_(this, nullptr),
192 immediateReadHandler_(this) {
193 VLOG(5) << "new AsyncSocket()";
197 AsyncSocket::AsyncSocket(EventBase* evb)
199 writeTimeout_(this, evb),
200 ioHandler_(this, evb),
201 immediateReadHandler_(this) {
202 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
206 AsyncSocket::AsyncSocket(EventBase* evb,
207 const folly::SocketAddress& address,
208 uint32_t connectTimeout)
210 connect(nullptr, address, connectTimeout);
213 AsyncSocket::AsyncSocket(EventBase* evb,
214 const std::string& ip,
216 uint32_t connectTimeout)
218 connect(nullptr, ip, port, connectTimeout);
221 AsyncSocket::AsyncSocket(EventBase* evb, int fd)
223 writeTimeout_(this, evb),
224 ioHandler_(this, evb, fd),
225 immediateReadHandler_(this) {
226 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ", fd="
231 state_ = StateEnum::ESTABLISHED;
234 AsyncSocket::AsyncSocket(AsyncSocket::UniquePtr oldAsyncSocket)
235 : AsyncSocket(oldAsyncSocket->getEventBase(), oldAsyncSocket->detachFd()) {
236 preReceivedData_ = std::move(oldAsyncSocket->preReceivedData_);
239 // init() method, since constructor forwarding isn't supported in most
241 void AsyncSocket::init() {
242 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
244 state_ = StateEnum::UNINIT;
245 eventFlags_ = EventHandler::NONE;
248 maxReadsPerEvent_ = 16;
249 connectCallback_ = nullptr;
250 errMessageCallback_ = nullptr;
251 readCallback_ = nullptr;
252 writeReqHead_ = nullptr;
253 writeReqTail_ = nullptr;
254 shutdownSocketSet_ = nullptr;
255 appBytesWritten_ = 0;
256 appBytesReceived_ = 0;
259 AsyncSocket::~AsyncSocket() {
260 VLOG(7) << "actual destruction of AsyncSocket(this=" << this
261 << ", evb=" << eventBase_ << ", fd=" << fd_
262 << ", state=" << state_ << ")";
265 void AsyncSocket::destroy() {
266 VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
267 << ", fd=" << fd_ << ", state=" << state_;
268 // When destroy is called, close the socket immediately
271 // Then call DelayedDestruction::destroy() to take care of
272 // whether or not we need immediate or delayed destruction
273 DelayedDestruction::destroy();
276 int AsyncSocket::detachFd() {
277 VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
278 << ", evb=" << eventBase_ << ", state=" << state_
279 << ", events=" << std::hex << eventFlags_ << ")";
280 // Extract the fd, and set fd_ to -1 first, so closeNow() won't
281 // actually close the descriptor.
282 if (shutdownSocketSet_) {
283 shutdownSocketSet_->remove(fd_);
287 // Call closeNow() to invoke all pending callbacks with an error.
289 // Update the EventHandler to stop using this fd.
290 // This can only be done after closeNow() unregisters the handler.
291 ioHandler_.changeHandlerFD(-1);
295 const folly::SocketAddress& AsyncSocket::anyAddress() {
296 static const folly::SocketAddress anyAddress =
297 folly::SocketAddress("0.0.0.0", 0);
301 void AsyncSocket::setShutdownSocketSet(ShutdownSocketSet* newSS) {
302 if (shutdownSocketSet_ == newSS) {
305 if (shutdownSocketSet_ && fd_ != -1) {
306 shutdownSocketSet_->remove(fd_);
308 shutdownSocketSet_ = newSS;
309 if (shutdownSocketSet_ && fd_ != -1) {
310 shutdownSocketSet_->add(fd_);
314 void AsyncSocket::setCloseOnExec() {
315 int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
317 auto errnoCopy = errno;
318 throw AsyncSocketException(
319 AsyncSocketException::INTERNAL_ERROR,
320 withAddr("failed to set close-on-exec flag"),
325 void AsyncSocket::connect(ConnectCallback* callback,
326 const folly::SocketAddress& address,
328 const OptionMap &options,
329 const folly::SocketAddress& bindAddr) noexcept {
330 DestructorGuard dg(this);
331 assert(eventBase_->isInEventBaseThread());
335 // Make sure we're in the uninitialized state
336 if (state_ != StateEnum::UNINIT) {
337 return invalidState(callback);
340 connectTimeout_ = std::chrono::milliseconds(timeout);
341 connectStartTime_ = std::chrono::steady_clock::now();
342 // Make connect end time at least >= connectStartTime.
343 connectEndTime_ = connectStartTime_;
346 state_ = StateEnum::CONNECTING;
347 connectCallback_ = callback;
349 sockaddr_storage addrStorage;
350 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
354 // Technically the first parameter should actually be a protocol family
355 // constant (PF_xxx) rather than an address family (AF_xxx), but the
356 // distinction is mainly just historical. In pretty much all
357 // implementations the PF_foo and AF_foo constants are identical.
358 fd_ = fsp::socket(address.getFamily(), SOCK_STREAM, 0);
360 auto errnoCopy = errno;
361 throw AsyncSocketException(
362 AsyncSocketException::INTERNAL_ERROR,
363 withAddr("failed to create socket"),
366 if (shutdownSocketSet_) {
367 shutdownSocketSet_->add(fd_);
369 ioHandler_.changeHandlerFD(fd_);
373 // Put the socket in non-blocking mode
374 int flags = fcntl(fd_, F_GETFL, 0);
376 auto errnoCopy = errno;
377 throw AsyncSocketException(
378 AsyncSocketException::INTERNAL_ERROR,
379 withAddr("failed to get socket flags"),
382 int rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
384 auto errnoCopy = errno;
385 throw AsyncSocketException(
386 AsyncSocketException::INTERNAL_ERROR,
387 withAddr("failed to put socket in non-blocking mode"),
391 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
392 // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
393 rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
395 auto errnoCopy = errno;
396 throw AsyncSocketException(
397 AsyncSocketException::INTERNAL_ERROR,
398 "failed to enable F_SETNOSIGPIPE on socket",
403 // By default, turn on TCP_NODELAY
404 // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
405 // setNoDelay() will log an error message if it fails.
406 if (address.getFamily() != AF_UNIX) {
407 (void)setNoDelay(true);
410 VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
411 << ", fd=" << fd_ << ", host=" << address.describe().c_str();
414 if (bindAddr != anyAddress()) {
416 if (setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
417 auto errnoCopy = errno;
419 throw AsyncSocketException(
420 AsyncSocketException::NOT_OPEN,
421 "failed to setsockopt prior to bind on " + bindAddr.describe(),
425 bindAddr.getAddress(&addrStorage);
427 if (bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
428 auto errnoCopy = errno;
430 throw AsyncSocketException(
431 AsyncSocketException::NOT_OPEN,
432 "failed to bind to async socket: " + bindAddr.describe(),
437 // Apply the additional options if any.
438 for (const auto& opt: options) {
439 rv = opt.first.apply(fd_, opt.second);
441 auto errnoCopy = errno;
442 throw AsyncSocketException(
443 AsyncSocketException::INTERNAL_ERROR,
444 withAddr("failed to set socket option"),
449 // Perform the connect()
450 address.getAddress(&addrStorage);
453 state_ = StateEnum::FAST_OPEN;
454 tfoAttempted_ = true;
456 if (socketConnect(saddr, addr_.getActualSize()) < 0) {
461 // If we're still here the connect() succeeded immediately.
462 // Fall through to call the callback outside of this try...catch block
463 } catch (const AsyncSocketException& ex) {
464 return failConnect(__func__, ex);
465 } catch (const std::exception& ex) {
466 // shouldn't happen, but handle it just in case
467 VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
468 << "): unexpected " << typeid(ex).name() << " exception: "
470 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
471 withAddr(string("unexpected exception: ") +
473 return failConnect(__func__, tex);
476 // The connection succeeded immediately
477 // The read callback may not have been set yet, and no writes may be pending
478 // yet, so we don't have to register for any events at the moment.
479 VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
480 assert(errMessageCallback_ == nullptr);
481 assert(readCallback_ == nullptr);
482 assert(writeReqHead_ == nullptr);
483 if (state_ != StateEnum::FAST_OPEN) {
484 state_ = StateEnum::ESTABLISHED;
486 invokeConnectSuccess();
489 int AsyncSocket::socketConnect(const struct sockaddr* saddr, socklen_t len) {
491 if (noTransparentTls_) {
492 // Ignore return value, errors are ok
493 setsockopt(fd_, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0);
496 int rv = fsp::connect(fd_, saddr, len);
498 auto errnoCopy = errno;
499 if (errnoCopy == EINPROGRESS) {
500 scheduleConnectTimeout();
501 registerForConnectEvents();
503 throw AsyncSocketException(
504 AsyncSocketException::NOT_OPEN,
505 "connect failed (immediately)",
512 void AsyncSocket::scheduleConnectTimeout() {
513 // Connection in progress.
514 auto timeout = connectTimeout_.count();
516 // Start a timer in case the connection takes too long.
517 if (!writeTimeout_.scheduleTimeout(uint32_t(timeout))) {
518 throw AsyncSocketException(
519 AsyncSocketException::INTERNAL_ERROR,
520 withAddr("failed to schedule AsyncSocket connect timeout"));
525 void AsyncSocket::registerForConnectEvents() {
526 // Register for write events, so we'll
527 // be notified when the connection finishes/fails.
528 // Note that we don't register for a persistent event here.
529 assert(eventFlags_ == EventHandler::NONE);
530 eventFlags_ = EventHandler::WRITE;
531 if (!ioHandler_.registerHandler(eventFlags_)) {
532 throw AsyncSocketException(
533 AsyncSocketException::INTERNAL_ERROR,
534 withAddr("failed to register AsyncSocket connect handler"));
538 void AsyncSocket::connect(ConnectCallback* callback,
539 const string& ip, uint16_t port,
541 const OptionMap &options) noexcept {
542 DestructorGuard dg(this);
544 connectCallback_ = callback;
545 connect(callback, folly::SocketAddress(ip, port), timeout, options);
546 } catch (const std::exception& ex) {
547 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
549 return failConnect(__func__, tex);
553 void AsyncSocket::cancelConnect() {
554 connectCallback_ = nullptr;
555 if (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN) {
560 void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
561 sendTimeout_ = milliseconds;
562 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
564 // If we are currently pending on write requests, immediately update
565 // writeTimeout_ with the new value.
566 if ((eventFlags_ & EventHandler::WRITE) &&
567 (state_ != StateEnum::CONNECTING && state_ != StateEnum::FAST_OPEN)) {
568 assert(state_ == StateEnum::ESTABLISHED);
569 assert((shutdownFlags_ & SHUT_WRITE) == 0);
570 if (sendTimeout_ > 0) {
571 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
572 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
573 withAddr("failed to reschedule send timeout in setSendTimeout"));
574 return failWrite(__func__, ex);
577 writeTimeout_.cancelTimeout();
582 void AsyncSocket::setErrMessageCB(ErrMessageCallback* callback) {
583 VLOG(6) << "AsyncSocket::setErrMessageCB() this=" << this
584 << ", fd=" << fd_ << ", callback=" << callback
585 << ", state=" << state_;
587 // Short circuit if callback is the same as the existing timestampCallback_.
588 if (callback == errMessageCallback_) {
592 if (!msgErrQueueSupported) {
593 // Per-socket error message queue is not supported on this platform.
594 return invalidState(callback);
597 DestructorGuard dg(this);
598 assert(eventBase_->isInEventBaseThread());
600 switch ((StateEnum)state_) {
601 case StateEnum::CONNECTING:
602 case StateEnum::FAST_OPEN:
603 case StateEnum::ESTABLISHED: {
604 errMessageCallback_ = callback;
607 case StateEnum::CLOSED:
608 case StateEnum::ERROR:
609 // We should never reach here. SHUT_READ should always be set
610 // if we are in STATE_CLOSED or STATE_ERROR.
612 return invalidState(callback);
613 case StateEnum::UNINIT:
614 // We do not allow setReadCallback() to be called before we start
616 return invalidState(callback);
619 // We don't put a default case in the switch statement, so that the compiler
620 // will warn us to update the switch statement if a new state is added.
621 return invalidState(callback);
624 AsyncSocket::ErrMessageCallback* AsyncSocket::getErrMessageCallback() const {
625 return errMessageCallback_;
628 void AsyncSocket::setReadCB(ReadCallback *callback) {
629 VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
630 << ", callback=" << callback << ", state=" << state_;
632 // Short circuit if callback is the same as the existing readCallback_.
634 // Note that this is needed for proper functioning during some cleanup cases.
635 // During cleanup we allow setReadCallback(nullptr) to be called even if the
636 // read callback is already unset and we have been detached from an event
637 // base. This check prevents us from asserting
638 // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
639 if (callback == readCallback_) {
643 /* We are removing a read callback */
644 if (callback == nullptr &&
645 immediateReadHandler_.isLoopCallbackScheduled()) {
646 immediateReadHandler_.cancelLoopCallback();
649 if (shutdownFlags_ & SHUT_READ) {
650 // Reads have already been shut down on this socket.
652 // Allow setReadCallback(nullptr) to be called in this case, but don't
653 // allow a new callback to be set.
655 // For example, setReadCallback(nullptr) can happen after an error if we
656 // invoke some other error callback before invoking readError(). The other
657 // error callback that is invoked first may go ahead and clear the read
658 // callback before we get a chance to invoke readError().
659 if (callback != nullptr) {
660 return invalidState(callback);
662 assert((eventFlags_ & EventHandler::READ) == 0);
663 readCallback_ = nullptr;
667 DestructorGuard dg(this);
668 assert(eventBase_->isInEventBaseThread());
670 switch ((StateEnum)state_) {
671 case StateEnum::CONNECTING:
672 case StateEnum::FAST_OPEN:
673 // For convenience, we allow the read callback to be set while we are
674 // still connecting. We just store the callback for now. Once the
675 // connection completes we'll register for read events.
676 readCallback_ = callback;
678 case StateEnum::ESTABLISHED:
680 readCallback_ = callback;
681 uint16_t oldFlags = eventFlags_;
683 eventFlags_ |= EventHandler::READ;
685 eventFlags_ &= ~EventHandler::READ;
688 // Update our registration if our flags have changed
689 if (eventFlags_ != oldFlags) {
690 // We intentionally ignore the return value here.
691 // updateEventRegistration() will move us into the error state if it
692 // fails, and we don't need to do anything else here afterwards.
693 (void)updateEventRegistration();
697 checkForImmediateRead();
701 case StateEnum::CLOSED:
702 case StateEnum::ERROR:
703 // We should never reach here. SHUT_READ should always be set
704 // if we are in STATE_CLOSED or STATE_ERROR.
706 return invalidState(callback);
707 case StateEnum::UNINIT:
708 // We do not allow setReadCallback() to be called before we start
710 return invalidState(callback);
713 // We don't put a default case in the switch statement, so that the compiler
714 // will warn us to update the switch statement if a new state is added.
715 return invalidState(callback);
718 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
719 return readCallback_;
722 void AsyncSocket::write(WriteCallback* callback,
723 const void* buf, size_t bytes, WriteFlags flags) {
725 op.iov_base = const_cast<void*>(buf);
727 writeImpl(callback, &op, 1, unique_ptr<IOBuf>(), flags);
730 void AsyncSocket::writev(WriteCallback* callback,
734 writeImpl(callback, vec, count, unique_ptr<IOBuf>(), flags);
737 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
739 constexpr size_t kSmallSizeMax = 64;
740 size_t count = buf->countChainElements();
741 if (count <= kSmallSizeMax) {
742 // suppress "warning: variable length array 'vec' is used [-Wvla]"
744 FOLLY_GCC_DISABLE_WARNING(vla);
745 iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA, count, kSmallSizeMax)];
748 writeChainImpl(callback, vec, count, std::move(buf), flags);
750 iovec* vec = new iovec[count];
751 writeChainImpl(callback, vec, count, std::move(buf), flags);
756 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
757 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
758 size_t veclen = buf->fillIov(vec, count);
759 writeImpl(callback, vec, veclen, std::move(buf), flags);
762 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
763 size_t count, unique_ptr<IOBuf>&& buf,
765 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
766 << ", callback=" << callback << ", count=" << count
767 << ", state=" << state_;
768 DestructorGuard dg(this);
769 unique_ptr<IOBuf>ioBuf(std::move(buf));
770 assert(eventBase_->isInEventBaseThread());
772 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
773 // No new writes may be performed after the write side of the socket has
776 // We could just call callback->writeError() here to fail just this write.
777 // However, fail hard and use invalidState() to fail all outstanding
778 // callbacks and move the socket into the error state. There's most likely
779 // a bug in the caller's code, so we abort everything rather than trying to
780 // proceed as best we can.
781 return invalidState(callback);
784 uint32_t countWritten = 0;
785 uint32_t partialWritten = 0;
786 ssize_t bytesWritten = 0;
787 bool mustRegister = false;
788 if ((state_ == StateEnum::ESTABLISHED || state_ == StateEnum::FAST_OPEN) &&
790 if (writeReqHead_ == nullptr) {
791 // If we are established and there are no other writes pending,
792 // we can attempt to perform the write immediately.
793 assert(writeReqTail_ == nullptr);
794 assert((eventFlags_ & EventHandler::WRITE) == 0);
796 auto writeResult = performWrite(
797 vec, uint32_t(count), flags, &countWritten, &partialWritten);
798 bytesWritten = writeResult.writeReturn;
799 if (bytesWritten < 0) {
800 auto errnoCopy = errno;
801 if (writeResult.exception) {
802 return failWrite(__func__, callback, 0, *writeResult.exception);
804 AsyncSocketException ex(
805 AsyncSocketException::INTERNAL_ERROR,
806 withAddr("writev failed"),
808 return failWrite(__func__, callback, 0, ex);
809 } else if (countWritten == count) {
810 // We successfully wrote everything.
811 // Invoke the callback and return.
813 callback->writeSuccess();
816 } else { // continue writing the next writeReq
817 if (bufferCallback_) {
818 bufferCallback_->onEgressBuffered();
822 // Writes might put the socket back into connecting state
823 // if TFO is enabled, and using TFO fails.
824 // This means that write timeouts would not be active, however
825 // connect timeouts would affect this stage.
829 } else if (!connecting()) {
830 // Invalid state for writing
831 return invalidState(callback);
834 // Create a new WriteRequest to add to the queue
837 req = BytesWriteRequest::newRequest(
841 uint32_t(count - countWritten),
843 uint32_t(bytesWritten),
846 } catch (const std::exception& ex) {
847 // we mainly expect to catch std::bad_alloc here
848 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
849 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
850 return failWrite(__func__, callback, size_t(bytesWritten), tex);
853 if (writeReqTail_ == nullptr) {
854 assert(writeReqHead_ == nullptr);
855 writeReqHead_ = writeReqTail_ = req;
857 writeReqTail_->append(req);
861 // Register for write events if are established and not currently
862 // waiting on write events
864 assert(state_ == StateEnum::ESTABLISHED);
865 assert((eventFlags_ & EventHandler::WRITE) == 0);
866 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
867 assert(state_ == StateEnum::ERROR);
870 if (sendTimeout_ > 0) {
871 // Schedule a timeout to fire if the write takes too long.
872 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
873 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
874 withAddr("failed to schedule send timeout"));
875 return failWrite(__func__, ex);
881 void AsyncSocket::writeRequest(WriteRequest* req) {
882 if (writeReqTail_ == nullptr) {
883 assert(writeReqHead_ == nullptr);
884 writeReqHead_ = writeReqTail_ = req;
887 writeReqTail_->append(req);
892 void AsyncSocket::close() {
893 VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
894 << ", state=" << state_ << ", shutdownFlags="
895 << std::hex << (int) shutdownFlags_;
897 // close() is only different from closeNow() when there are pending writes
898 // that need to drain before we can close. In all other cases, just call
901 // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
902 // STATE_ERROR if close() is invoked while a previous closeNow() or failure
903 // is still running. (e.g., If there are multiple pending writes, and we
904 // call writeError() on the first one, it may call close(). In this case we
905 // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
906 // writes will still be in the queue.)
908 // We only need to drain pending writes if we are still in STATE_CONNECTING
909 // or STATE_ESTABLISHED
910 if ((writeReqHead_ == nullptr) ||
911 !(state_ == StateEnum::CONNECTING ||
912 state_ == StateEnum::ESTABLISHED)) {
917 // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
918 // destroyed until close() returns.
919 DestructorGuard dg(this);
920 assert(eventBase_->isInEventBaseThread());
922 // Since there are write requests pending, we have to set the
923 // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
924 // connect finishes and we finish writing these requests.
926 // Set SHUT_READ to indicate that reads are shut down, and set the
927 // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
928 // pending writes complete.
929 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
931 // If a read callback is set, invoke readEOF() immediately to inform it that
932 // the socket has been closed and no more data can be read.
934 // Disable reads if they are enabled
935 if (!updateEventRegistration(0, EventHandler::READ)) {
936 // We're now in the error state; callbacks have been cleaned up
937 assert(state_ == StateEnum::ERROR);
938 assert(readCallback_ == nullptr);
940 ReadCallback* callback = readCallback_;
941 readCallback_ = nullptr;
947 void AsyncSocket::closeNow() {
948 VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
949 << ", state=" << state_ << ", shutdownFlags="
950 << std::hex << (int) shutdownFlags_;
951 DestructorGuard dg(this);
952 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
955 case StateEnum::ESTABLISHED:
956 case StateEnum::CONNECTING:
957 case StateEnum::FAST_OPEN: {
958 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
959 state_ = StateEnum::CLOSED;
961 // If the write timeout was set, cancel it.
962 writeTimeout_.cancelTimeout();
964 // If we are registered for I/O events, unregister.
965 if (eventFlags_ != EventHandler::NONE) {
966 eventFlags_ = EventHandler::NONE;
967 if (!updateEventRegistration()) {
968 // We will have been moved into the error state.
969 assert(state_ == StateEnum::ERROR);
974 if (immediateReadHandler_.isLoopCallbackScheduled()) {
975 immediateReadHandler_.cancelLoopCallback();
979 ioHandler_.changeHandlerFD(-1);
983 invokeConnectErr(socketClosedLocallyEx);
985 failAllWrites(socketClosedLocallyEx);
988 ReadCallback* callback = readCallback_;
989 readCallback_ = nullptr;
994 case StateEnum::CLOSED:
995 // Do nothing. It's possible that we are being called recursively
996 // from inside a callback that we invoked inside another call to close()
997 // that is still running.
999 case StateEnum::ERROR:
1000 // Do nothing. The error handling code has performed (or is performing)
1003 case StateEnum::UNINIT:
1004 assert(eventFlags_ == EventHandler::NONE);
1005 assert(connectCallback_ == nullptr);
1006 assert(readCallback_ == nullptr);
1007 assert(writeReqHead_ == nullptr);
1008 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1009 state_ = StateEnum::CLOSED;
1013 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
1014 << ") called in unknown state " << state_;
1017 void AsyncSocket::closeWithReset() {
1018 // Enable SO_LINGER, with the linger timeout set to 0.
1019 // This will trigger a TCP reset when we close the socket.
1021 struct linger optLinger = {1, 0};
1022 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
1023 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
1024 << "on " << fd_ << ": errno=" << errno;
1028 // Then let closeNow() take care of the rest
1032 void AsyncSocket::shutdownWrite() {
1033 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
1034 << ", state=" << state_ << ", shutdownFlags="
1035 << std::hex << (int) shutdownFlags_;
1037 // If there are no pending writes, shutdownWrite() is identical to
1038 // shutdownWriteNow().
1039 if (writeReqHead_ == nullptr) {
1044 assert(eventBase_->isInEventBaseThread());
1046 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
1047 // shutdown will be performed once all writes complete.
1048 shutdownFlags_ |= SHUT_WRITE_PENDING;
1051 void AsyncSocket::shutdownWriteNow() {
1052 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
1053 << ", fd=" << fd_ << ", state=" << state_
1054 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
1056 if (shutdownFlags_ & SHUT_WRITE) {
1057 // Writes are already shutdown; nothing else to do.
1061 // If SHUT_READ is already set, just call closeNow() to completely
1062 // close the socket. This can happen if close() was called with writes
1063 // pending, and then shutdownWriteNow() is called before all pending writes
1065 if (shutdownFlags_ & SHUT_READ) {
1070 DestructorGuard dg(this);
1071 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
1073 switch (static_cast<StateEnum>(state_)) {
1074 case StateEnum::ESTABLISHED:
1076 shutdownFlags_ |= SHUT_WRITE;
1078 // If the write timeout was set, cancel it.
1079 writeTimeout_.cancelTimeout();
1081 // If we are registered for write events, unregister.
1082 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1083 // We will have been moved into the error state.
1084 assert(state_ == StateEnum::ERROR);
1088 // Shutdown writes on the file descriptor
1089 shutdown(fd_, SHUT_WR);
1091 // Immediately fail all write requests
1092 failAllWrites(socketShutdownForWritesEx);
1095 case StateEnum::CONNECTING:
1097 // Set the SHUT_WRITE_PENDING flag.
1098 // When the connection completes, it will check this flag,
1099 // shutdown the write half of the socket, and then set SHUT_WRITE.
1100 shutdownFlags_ |= SHUT_WRITE_PENDING;
1102 // Immediately fail all write requests
1103 failAllWrites(socketShutdownForWritesEx);
1106 case StateEnum::UNINIT:
1107 // Callers normally shouldn't call shutdownWriteNow() before the socket
1108 // even starts connecting. Nonetheless, go ahead and set
1109 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
1110 // immediately shut down the write side of the socket.
1111 shutdownFlags_ |= SHUT_WRITE_PENDING;
1113 case StateEnum::FAST_OPEN:
1114 // In fast open state we haven't call connected yet, and if we shutdown
1115 // the writes, we will never try to call connect, so shut everything down
1116 shutdownFlags_ |= SHUT_WRITE;
1117 // Immediately fail all write requests
1118 failAllWrites(socketShutdownForWritesEx);
1120 case StateEnum::CLOSED:
1121 case StateEnum::ERROR:
1122 // We should never get here. SHUT_WRITE should always be set
1123 // in STATE_CLOSED and STATE_ERROR.
1124 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
1125 << ", fd=" << fd_ << ") in unexpected state " << state_
1126 << " with SHUT_WRITE not set ("
1127 << std::hex << (int) shutdownFlags_ << ")";
1132 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
1133 << fd_ << ") called in unknown state " << state_;
1136 bool AsyncSocket::readable() const {
1140 struct pollfd fds[1];
1142 fds[0].events = POLLIN;
1144 int rc = poll(fds, 1, 0);
1148 bool AsyncSocket::isPending() const {
1149 return ioHandler_.isPending();
1152 bool AsyncSocket::hangup() const {
1154 // sanity check, no one should ask for hangup if we are not connected.
1158 #ifdef POLLRDHUP // Linux-only
1159 struct pollfd fds[1];
1161 fds[0].events = POLLRDHUP|POLLHUP;
1164 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1170 bool AsyncSocket::good() const {
1172 (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN ||
1173 state_ == StateEnum::ESTABLISHED) &&
1174 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1177 bool AsyncSocket::error() const {
1178 return (state_ == StateEnum::ERROR);
1181 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1182 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1183 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1184 << ", state=" << state_ << ", events="
1185 << std::hex << eventFlags_ << ")";
1186 assert(eventBase_ == nullptr);
1187 assert(eventBase->isInEventBaseThread());
1189 eventBase_ = eventBase;
1190 ioHandler_.attachEventBase(eventBase);
1191 writeTimeout_.attachEventBase(eventBase);
1193 evbChangeCb_->evbAttached(this);
1197 void AsyncSocket::detachEventBase() {
1198 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1199 << ", old evb=" << eventBase_ << ", state=" << state_
1200 << ", events=" << std::hex << eventFlags_ << ")";
1201 assert(eventBase_ != nullptr);
1202 assert(eventBase_->isInEventBaseThread());
1204 eventBase_ = nullptr;
1205 ioHandler_.detachEventBase();
1206 writeTimeout_.detachEventBase();
1208 evbChangeCb_->evbDetached(this);
1212 bool AsyncSocket::isDetachable() const {
1213 DCHECK(eventBase_ != nullptr);
1214 DCHECK(eventBase_->isInEventBaseThread());
1216 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1219 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1220 if (!localAddr_.isInitialized()) {
1221 localAddr_.setFromLocalAddress(fd_);
1223 *address = localAddr_;
1226 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1227 if (!addr_.isInitialized()) {
1228 addr_.setFromPeerAddress(fd_);
1233 bool AsyncSocket::getTFOSucceded() const {
1234 return detail::tfo_succeeded(fd_);
1237 int AsyncSocket::setNoDelay(bool noDelay) {
1239 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1240 << this << "(state=" << state_ << ")";
1245 int value = noDelay ? 1 : 0;
1246 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1247 int errnoCopy = errno;
1248 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1249 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1250 << strerror(errnoCopy);
1257 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1259 #ifndef TCP_CONGESTION
1260 #define TCP_CONGESTION 13
1264 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1265 << "socket " << this << "(state=" << state_ << ")";
1275 socklen_t(cname.length() + 1)) != 0) {
1276 int errnoCopy = errno;
1277 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1278 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1279 << strerror(errnoCopy);
1286 int AsyncSocket::setQuickAck(bool quickack) {
1289 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1290 << this << "(state=" << state_ << ")";
1295 #ifdef TCP_QUICKACK // Linux-only
1296 int value = quickack ? 1 : 0;
1297 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1298 int errnoCopy = errno;
1299 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1300 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1301 << strerror(errnoCopy);
1311 int AsyncSocket::setSendBufSize(size_t bufsize) {
1313 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1314 << this << "(state=" << state_ << ")";
1318 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1319 int errnoCopy = errno;
1320 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1321 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1322 << strerror(errnoCopy);
1329 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1331 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1332 << this << "(state=" << state_ << ")";
1336 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1337 int errnoCopy = errno;
1338 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1339 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1340 << strerror(errnoCopy);
1347 int AsyncSocket::setTCPProfile(int profd) {
1349 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1350 << this << "(state=" << state_ << ")";
1354 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1355 int errnoCopy = errno;
1356 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1357 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1358 << strerror(errnoCopy);
1365 void AsyncSocket::ioReady(uint16_t events) noexcept {
1366 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd" << fd_
1367 << ", events=" << std::hex << events << ", state=" << state_;
1368 DestructorGuard dg(this);
1369 assert(events & EventHandler::READ_WRITE);
1370 assert(eventBase_->isInEventBaseThread());
1372 uint16_t relevantEvents = uint16_t(events & EventHandler::READ_WRITE);
1373 EventBase* originalEventBase = eventBase_;
1374 // If we got there it means that either EventHandler::READ or
1375 // EventHandler::WRITE is set. Any of these flags can
1376 // indicate that there are messages available in the socket
1377 // error message queue.
1378 handleErrMessages();
1380 // Return now if handleErrMessages() detached us from our EventBase
1381 if (eventBase_ != originalEventBase) {
1385 if (relevantEvents == EventHandler::READ) {
1387 } else if (relevantEvents == EventHandler::WRITE) {
1389 } else if (relevantEvents == EventHandler::READ_WRITE) {
1390 // If both read and write events are ready, process writes first.
1393 // Return now if handleWrite() detached us from our EventBase
1394 if (eventBase_ != originalEventBase) {
1398 // Only call handleRead() if a read callback is still installed.
1399 // (It's possible that the read callback was uninstalled during
1401 if (readCallback_) {
1405 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1406 << std::hex << events << "(this=" << this << ")";
1411 AsyncSocket::ReadResult
1412 AsyncSocket::performRead(void** buf, size_t* buflen, size_t* /* offset */) {
1413 VLOG(5) << "AsyncSocket::performRead() this=" << this << ", buf=" << *buf
1414 << ", buflen=" << *buflen;
1416 if (preReceivedData_ && !preReceivedData_->empty()) {
1417 VLOG(5) << "AsyncSocket::performRead() this=" << this
1418 << ", reading pre-received data";
1420 io::Cursor cursor(preReceivedData_.get());
1421 auto len = cursor.pullAtMost(*buf, *buflen);
1424 queue.append(std::move(preReceivedData_));
1425 queue.trimStart(len);
1426 preReceivedData_ = queue.move();
1428 appBytesReceived_ += len;
1429 return ReadResult(len);
1432 ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT);
1434 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1435 // No more data to read right now.
1436 return ReadResult(READ_BLOCKING);
1438 return ReadResult(READ_ERROR);
1441 appBytesReceived_ += bytes;
1442 return ReadResult(bytes);
1446 void AsyncSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1447 // no matter what, buffer should be preapared for non-ssl socket
1448 CHECK(readCallback_);
1449 readCallback_->getReadBuffer(buf, buflen);
1452 void AsyncSocket::handleErrMessages() noexcept {
1453 // This method has non-empty implementation only for platforms
1454 // supporting per-socket error queues.
1455 VLOG(5) << "AsyncSocket::handleErrMessages() this=" << this << ", fd=" << fd_
1456 << ", state=" << state_;
1457 if (errMessageCallback_ == nullptr) {
1458 VLOG(7) << "AsyncSocket::handleErrMessages(): "
1459 << "no callback installed - exiting.";
1469 entry.iov_base = &data;
1470 entry.iov_len = sizeof(data);
1471 msg.msg_iov = &entry;
1473 msg.msg_name = nullptr;
1474 msg.msg_namelen = 0;
1475 msg.msg_control = ctrl;
1476 msg.msg_controllen = sizeof(ctrl);
1481 ret = recvmsg(fd_, &msg, MSG_ERRQUEUE);
1482 VLOG(5) << "AsyncSocket::handleErrMessages(): recvmsg returned " << ret;
1485 if (errno != EAGAIN) {
1486 auto errnoCopy = errno;
1487 LOG(ERROR) << "::recvmsg exited with code " << ret
1488 << ", errno: " << errnoCopy;
1489 AsyncSocketException ex(
1490 AsyncSocketException::INTERNAL_ERROR,
1491 withAddr("recvmsg() failed"),
1493 failErrMessageRead(__func__, ex);
1498 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
1499 cmsg != nullptr && cmsg->cmsg_len != 0;
1500 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1501 errMessageCallback_->errMessage(*cmsg);
1504 #endif //MSG_ERRQUEUE
1507 void AsyncSocket::handleRead() noexcept {
1508 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1509 << ", state=" << state_;
1510 assert(state_ == StateEnum::ESTABLISHED);
1511 assert((shutdownFlags_ & SHUT_READ) == 0);
1512 assert(readCallback_ != nullptr);
1513 assert(eventFlags_ & EventHandler::READ);
1516 // - a read attempt would block
1517 // - readCallback_ is uninstalled
1518 // - the number of loop iterations exceeds the optional maximum
1519 // - this AsyncSocket is moved to another EventBase
1521 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1522 // which is why need to check for it here.
1524 // The last bullet point is slightly subtle. readDataAvailable() may also
1525 // detach this socket from this EventBase. However, before
1526 // readDataAvailable() returns another thread may pick it up, attach it to
1527 // a different EventBase, and install another readCallback_. We need to
1528 // exit immediately after readDataAvailable() returns if the eventBase_ has
1529 // changed. (The caller must perform some sort of locking to transfer the
1530 // AsyncSocket between threads properly. This will be sufficient to ensure
1531 // that this thread sees the updated eventBase_ variable after
1532 // readDataAvailable() returns.)
1533 uint16_t numReads = 0;
1534 EventBase* originalEventBase = eventBase_;
1535 while (readCallback_ && eventBase_ == originalEventBase) {
1536 // Get the buffer to read into.
1537 void* buf = nullptr;
1538 size_t buflen = 0, offset = 0;
1540 prepareReadBuffer(&buf, &buflen);
1541 VLOG(5) << "prepareReadBuffer() buf=" << buf << ", buflen=" << buflen;
1542 } catch (const AsyncSocketException& ex) {
1543 return failRead(__func__, ex);
1544 } catch (const std::exception& ex) {
1545 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1546 string("ReadCallback::getReadBuffer() "
1547 "threw exception: ") +
1549 return failRead(__func__, tex);
1551 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1552 "ReadCallback::getReadBuffer() threw "
1553 "non-exception type");
1554 return failRead(__func__, ex);
1556 if (!isBufferMovable_ && (buf == nullptr || buflen == 0)) {
1557 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1558 "ReadCallback::getReadBuffer() returned "
1560 return failRead(__func__, ex);
1564 auto readResult = performRead(&buf, &buflen, &offset);
1565 auto bytesRead = readResult.readReturn;
1566 VLOG(4) << "this=" << this << ", AsyncSocket::handleRead() got "
1567 << bytesRead << " bytes";
1568 if (bytesRead > 0) {
1569 if (!isBufferMovable_) {
1570 readCallback_->readDataAvailable(size_t(bytesRead));
1572 CHECK(kOpenSslModeMoveBufferOwnership);
1573 VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
1574 << "buf=" << buf << ", " << bytesRead << "/" << buflen
1575 << ", offset=" << offset;
1576 auto readBuf = folly::IOBuf::takeOwnership(buf, buflen);
1577 readBuf->trimStart(offset);
1578 readBuf->trimEnd(buflen - offset - bytesRead);
1579 readCallback_->readBufferAvailable(std::move(readBuf));
1582 // Fall through and continue around the loop if the read
1583 // completely filled the available buffer.
1584 // Note that readCallback_ may have been uninstalled or changed inside
1585 // readDataAvailable().
1586 if (size_t(bytesRead) < buflen) {
1589 } else if (bytesRead == READ_BLOCKING) {
1590 // No more data to read right now.
1592 } else if (bytesRead == READ_ERROR) {
1593 readErr_ = READ_ERROR;
1594 if (readResult.exception) {
1595 return failRead(__func__, *readResult.exception);
1597 auto errnoCopy = errno;
1598 AsyncSocketException ex(
1599 AsyncSocketException::INTERNAL_ERROR,
1600 withAddr("recv() failed"),
1602 return failRead(__func__, ex);
1604 assert(bytesRead == READ_EOF);
1605 readErr_ = READ_EOF;
1607 shutdownFlags_ |= SHUT_READ;
1608 if (!updateEventRegistration(0, EventHandler::READ)) {
1609 // we've already been moved into STATE_ERROR
1610 assert(state_ == StateEnum::ERROR);
1611 assert(readCallback_ == nullptr);
1615 ReadCallback* callback = readCallback_;
1616 readCallback_ = nullptr;
1617 callback->readEOF();
1620 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1621 if (readCallback_ != nullptr) {
1622 // We might still have data in the socket.
1623 // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
1624 scheduleImmediateRead();
1632 * This function attempts to write as much data as possible, until no more data
1635 * - If it sends all available data, it unregisters for write events, and stops
1636 * the writeTimeout_.
1638 * - If not all of the data can be sent immediately, it reschedules
1639 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1640 * registered for write events.
1642 void AsyncSocket::handleWrite() noexcept {
1643 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1644 << ", state=" << state_;
1645 DestructorGuard dg(this);
1647 if (state_ == StateEnum::CONNECTING) {
1653 assert(state_ == StateEnum::ESTABLISHED);
1654 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1655 assert(writeReqHead_ != nullptr);
1657 // Loop until we run out of write requests,
1658 // or until this socket is moved to another EventBase.
1659 // (See the comment in handleRead() explaining how this can happen.)
1660 EventBase* originalEventBase = eventBase_;
1661 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1662 auto writeResult = writeReqHead_->performWrite();
1663 if (writeResult.writeReturn < 0) {
1664 if (writeResult.exception) {
1665 return failWrite(__func__, *writeResult.exception);
1667 auto errnoCopy = errno;
1668 AsyncSocketException ex(
1669 AsyncSocketException::INTERNAL_ERROR,
1670 withAddr("writev() failed"),
1672 return failWrite(__func__, ex);
1673 } else if (writeReqHead_->isComplete()) {
1674 // We finished this request
1675 WriteRequest* req = writeReqHead_;
1676 writeReqHead_ = req->getNext();
1678 if (writeReqHead_ == nullptr) {
1679 writeReqTail_ = nullptr;
1680 // This is the last write request.
1681 // Unregister for write events and cancel the send timer
1682 // before we invoke the callback. We have to update the state properly
1683 // before calling the callback, since it may want to detach us from
1685 if (eventFlags_ & EventHandler::WRITE) {
1686 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1687 assert(state_ == StateEnum::ERROR);
1690 // Stop the send timeout
1691 writeTimeout_.cancelTimeout();
1693 assert(!writeTimeout_.isScheduled());
1695 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
1696 // we finish sending the last write request.
1698 // We have to do this before invoking writeSuccess(), since
1699 // writeSuccess() may detach us from our EventBase.
1700 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
1701 assert(connectCallback_ == nullptr);
1702 shutdownFlags_ |= SHUT_WRITE;
1704 if (shutdownFlags_ & SHUT_READ) {
1705 // Reads have already been shutdown. Fully close the socket and
1706 // move to STATE_CLOSED.
1708 // Note: This code currently moves us to STATE_CLOSED even if
1709 // close() hasn't ever been called. This can occur if we have
1710 // received EOF from the peer and shutdownWrite() has been called
1711 // locally. Should we bother staying in STATE_ESTABLISHED in this
1712 // case, until close() is actually called? I can't think of a
1713 // reason why we would need to do so. No other operations besides
1714 // calling close() or destroying the socket can be performed at
1716 assert(readCallback_ == nullptr);
1717 state_ = StateEnum::CLOSED;
1719 ioHandler_.changeHandlerFD(-1);
1723 // Reads are still enabled, so we are only doing a half-shutdown
1724 shutdown(fd_, SHUT_WR);
1729 // Invoke the callback
1730 WriteCallback* callback = req->getCallback();
1733 callback->writeSuccess();
1735 // We'll continue around the loop, trying to write another request
1738 if (bufferCallback_) {
1739 bufferCallback_->onEgressBuffered();
1741 writeReqHead_->consume();
1742 // Stop after a partial write; it's highly likely that a subsequent write
1743 // attempt will just return EAGAIN.
1745 // Ensure that we are registered for write events.
1746 if ((eventFlags_ & EventHandler::WRITE) == 0) {
1747 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1748 assert(state_ == StateEnum::ERROR);
1753 // Reschedule the send timeout, since we have made some write progress.
1754 if (sendTimeout_ > 0) {
1755 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1756 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1757 withAddr("failed to reschedule write timeout"));
1758 return failWrite(__func__, ex);
1764 if (!writeReqHead_ && bufferCallback_) {
1765 bufferCallback_->onEgressBufferCleared();
1769 void AsyncSocket::checkForImmediateRead() noexcept {
1770 // We currently don't attempt to perform optimistic reads in AsyncSocket.
1771 // (However, note that some subclasses do override this method.)
1773 // Simply calling handleRead() here would be bad, as this would call
1774 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
1775 // buffer even though no data may be available. This would waste lots of
1776 // memory, since the buffer will sit around unused until the socket actually
1777 // becomes readable.
1779 // Checking if the socket is readable now also seems like it would probably
1780 // be a pessimism. In most cases it probably wouldn't be readable, and we
1781 // would just waste an extra system call. Even if it is readable, waiting to
1782 // find out from libevent on the next event loop doesn't seem that bad.
1784 // The exception to this is if we have pre-received data. In that case there
1785 // is definitely data available immediately.
1786 if (preReceivedData_ && !preReceivedData_->empty()) {
1791 void AsyncSocket::handleInitialReadWrite() noexcept {
1792 // Our callers should already be holding a DestructorGuard, but grab
1793 // one here just to make sure, in case one of our calling code paths ever
1795 DestructorGuard dg(this);
1796 // If we have a readCallback_, make sure we enable read events. We
1797 // may already be registered for reads if connectSuccess() set
1798 // the read calback.
1799 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
1800 assert(state_ == StateEnum::ESTABLISHED);
1801 assert((shutdownFlags_ & SHUT_READ) == 0);
1802 if (!updateEventRegistration(EventHandler::READ, 0)) {
1803 assert(state_ == StateEnum::ERROR);
1806 checkForImmediateRead();
1807 } else if (readCallback_ == nullptr) {
1808 // Unregister for read events.
1809 updateEventRegistration(0, EventHandler::READ);
1812 // If we have write requests pending, try to send them immediately.
1813 // Since we just finished accepting, there is a very good chance that we can
1814 // write without blocking.
1816 // However, we only process them if EventHandler::WRITE is not already set,
1817 // which means that we're already blocked on a write attempt. (This can
1818 // happen if connectSuccess() called write() before returning.)
1819 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
1820 // Call handleWrite() to perform write processing.
1822 } else if (writeReqHead_ == nullptr) {
1823 // Unregister for write event.
1824 updateEventRegistration(0, EventHandler::WRITE);
1828 void AsyncSocket::handleConnect() noexcept {
1829 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
1830 << ", state=" << state_;
1831 assert(state_ == StateEnum::CONNECTING);
1832 // SHUT_WRITE can never be set while we are still connecting;
1833 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
1835 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1837 // In case we had a connect timeout, cancel the timeout
1838 writeTimeout_.cancelTimeout();
1839 // We don't use a persistent registration when waiting on a connect event,
1840 // so we have been automatically unregistered now. Update eventFlags_ to
1842 assert(eventFlags_ == EventHandler::WRITE);
1843 eventFlags_ = EventHandler::NONE;
1845 // Call getsockopt() to check if the connect succeeded
1847 socklen_t len = sizeof(error);
1848 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
1850 auto errnoCopy = errno;
1851 AsyncSocketException ex(
1852 AsyncSocketException::INTERNAL_ERROR,
1853 withAddr("error calling getsockopt() after connect"),
1855 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1856 << fd_ << " host=" << addr_.describe()
1857 << ") exception:" << ex.what();
1858 return failConnect(__func__, ex);
1862 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1863 "connect failed", error);
1864 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1865 << fd_ << " host=" << addr_.describe()
1866 << ") exception: " << ex.what();
1867 return failConnect(__func__, ex);
1870 // Move into STATE_ESTABLISHED
1871 state_ = StateEnum::ESTABLISHED;
1873 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
1874 // perform, immediately shutdown the write half of the socket.
1875 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
1876 // SHUT_READ shouldn't be set. If close() is called on the socket while we
1877 // are still connecting we just abort the connect rather than waiting for
1879 assert((shutdownFlags_ & SHUT_READ) == 0);
1880 shutdown(fd_, SHUT_WR);
1881 shutdownFlags_ |= SHUT_WRITE;
1884 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
1885 << "successfully connected; state=" << state_;
1887 // Remember the EventBase we are attached to, before we start invoking any
1888 // callbacks (since the callbacks may call detachEventBase()).
1889 EventBase* originalEventBase = eventBase_;
1891 invokeConnectSuccess();
1892 // Note that the connect callback may have changed our state.
1893 // (set or unset the read callback, called write(), closed the socket, etc.)
1894 // The following code needs to handle these situations correctly.
1896 // If the socket has been closed, readCallback_ and writeReqHead_ will
1897 // always be nullptr, so that will prevent us from trying to read or write.
1899 // The main thing to check for is if eventBase_ is still originalEventBase.
1900 // If not, we have been detached from this event base, so we shouldn't
1901 // perform any more operations.
1902 if (eventBase_ != originalEventBase) {
1906 handleInitialReadWrite();
1909 void AsyncSocket::timeoutExpired() noexcept {
1910 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
1911 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
1912 DestructorGuard dg(this);
1913 assert(eventBase_->isInEventBaseThread());
1915 if (state_ == StateEnum::CONNECTING) {
1916 // connect() timed out
1917 // Unregister for I/O events.
1918 if (connectCallback_) {
1919 AsyncSocketException ex(
1920 AsyncSocketException::TIMED_OUT,
1922 "connect timed out after {}ms", connectTimeout_.count()));
1923 failConnect(__func__, ex);
1925 // we faced a connect error without a connect callback, which could
1926 // happen due to TFO.
1927 AsyncSocketException ex(
1928 AsyncSocketException::TIMED_OUT, "write timed out during connection");
1929 failWrite(__func__, ex);
1932 // a normal write operation timed out
1933 AsyncSocketException ex(
1934 AsyncSocketException::TIMED_OUT,
1935 folly::sformat("write timed out after {}ms", sendTimeout_));
1936 failWrite(__func__, ex);
1940 ssize_t AsyncSocket::tfoSendMsg(int fd, struct msghdr* msg, int msg_flags) {
1941 return detail::tfo_sendmsg(fd, msg, msg_flags);
1944 AsyncSocket::WriteResult
1945 AsyncSocket::sendSocketMessage(int fd, struct msghdr* msg, int msg_flags) {
1946 ssize_t totalWritten = 0;
1947 if (state_ == StateEnum::FAST_OPEN) {
1948 sockaddr_storage addr;
1949 auto len = addr_.getAddress(&addr);
1950 msg->msg_name = &addr;
1951 msg->msg_namelen = len;
1952 totalWritten = tfoSendMsg(fd_, msg, msg_flags);
1953 if (totalWritten >= 0) {
1954 tfoFinished_ = true;
1955 state_ = StateEnum::ESTABLISHED;
1956 // We schedule this asynchrously so that we don't end up
1957 // invoking initial read or write while a write is in progress.
1958 scheduleInitialReadWrite();
1959 } else if (errno == EINPROGRESS) {
1960 VLOG(4) << "TFO falling back to connecting";
1961 // A normal sendmsg doesn't return EINPROGRESS, however
1962 // TFO might fallback to connecting if there is no
1964 state_ = StateEnum::CONNECTING;
1966 scheduleConnectTimeout();
1967 registerForConnectEvents();
1968 } catch (const AsyncSocketException& ex) {
1970 WRITE_ERROR, folly::make_unique<AsyncSocketException>(ex));
1972 // Let's fake it that no bytes were written and return an errno.
1975 } else if (errno == EOPNOTSUPP) {
1976 // Try falling back to connecting.
1977 VLOG(4) << "TFO not supported";
1978 state_ = StateEnum::CONNECTING;
1980 int ret = socketConnect((const sockaddr*)&addr, len);
1982 // connect succeeded immediately
1983 // Treat this like no data was written.
1984 state_ = StateEnum::ESTABLISHED;
1985 scheduleInitialReadWrite();
1987 // If there was no exception during connections,
1988 // we would return that no bytes were written.
1991 } catch (const AsyncSocketException& ex) {
1993 WRITE_ERROR, folly::make_unique<AsyncSocketException>(ex));
1995 } else if (errno == EAGAIN) {
1996 // Normally sendmsg would indicate that the write would block.
1997 // However in the fast open case, it would indicate that sendmsg
1998 // fell back to a connect. This is a return code from connect()
1999 // instead, and is an error condition indicating no fds available.
2002 folly::make_unique<AsyncSocketException>(
2003 AsyncSocketException::UNKNOWN, "No more free local ports"));
2006 totalWritten = ::sendmsg(fd, msg, msg_flags);
2008 return WriteResult(totalWritten);
2011 AsyncSocket::WriteResult AsyncSocket::performWrite(
2015 uint32_t* countWritten,
2016 uint32_t* partialWritten) {
2017 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
2018 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
2019 // (since it may terminate the program if the main program doesn't explicitly
2022 msg.msg_name = nullptr;
2023 msg.msg_namelen = 0;
2024 msg.msg_iov = const_cast<iovec *>(vec);
2025 msg.msg_iovlen = std::min<size_t>(count, kIovMax);
2026 msg.msg_control = nullptr;
2027 msg.msg_controllen = 0;
2030 int msg_flags = MSG_DONTWAIT;
2032 #ifdef MSG_NOSIGNAL // Linux-only
2033 msg_flags |= MSG_NOSIGNAL;
2034 if (isSet(flags, WriteFlags::CORK)) {
2035 // MSG_MORE tells the kernel we have more data to send, so wait for us to
2036 // give it the rest of the data rather than immediately sending a partial
2037 // frame, even when TCP_NODELAY is enabled.
2038 msg_flags |= MSG_MORE;
2041 if (isSet(flags, WriteFlags::EOR)) {
2042 // marks that this is the last byte of a record (response)
2043 msg_flags |= MSG_EOR;
2045 auto writeResult = sendSocketMessage(fd_, &msg, msg_flags);
2046 auto totalWritten = writeResult.writeReturn;
2047 if (totalWritten < 0) {
2048 bool tryAgain = (errno == EAGAIN);
2050 // Apple has a bug where doing a second write on a socket which we
2051 // have opened with TFO causes an ENOTCONN to be thrown. However the
2052 // socket is really connected, so treat ENOTCONN as a EAGAIN until
2053 // this bug is fixed.
2054 tryAgain |= (errno == ENOTCONN);
2056 if (!writeResult.exception && tryAgain) {
2057 // TCP buffer is full; we can't write any more data right now.
2059 *partialWritten = 0;
2060 return WriteResult(0);
2064 *partialWritten = 0;
2068 appBytesWritten_ += totalWritten;
2070 uint32_t bytesWritten;
2072 for (bytesWritten = uint32_t(totalWritten), n = 0; n < count; ++n) {
2073 const iovec* v = vec + n;
2074 if (v->iov_len > bytesWritten) {
2075 // Partial write finished in the middle of this iovec
2077 *partialWritten = bytesWritten;
2078 return WriteResult(totalWritten);
2081 bytesWritten -= uint32_t(v->iov_len);
2084 assert(bytesWritten == 0);
2086 *partialWritten = 0;
2087 return WriteResult(totalWritten);
2091 * Re-register the EventHandler after eventFlags_ has changed.
2093 * If an error occurs, fail() is called to move the socket into the error state
2094 * and call all currently installed callbacks. After an error, the
2095 * AsyncSocket is completely unregistered.
2097 * @return Returns true on succcess, or false on error.
2099 bool AsyncSocket::updateEventRegistration() {
2100 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
2101 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
2102 << ", events=" << std::hex << eventFlags_;
2103 assert(eventBase_->isInEventBaseThread());
2104 if (eventFlags_ == EventHandler::NONE) {
2105 ioHandler_.unregisterHandler();
2109 // Always register for persistent events, so we don't have to re-register
2110 // after being called back.
2111 if (!ioHandler_.registerHandler(
2112 uint16_t(eventFlags_ | EventHandler::PERSIST))) {
2113 eventFlags_ = EventHandler::NONE; // we're not registered after error
2114 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
2115 withAddr("failed to update AsyncSocket event registration"));
2116 fail("updateEventRegistration", ex);
2123 bool AsyncSocket::updateEventRegistration(uint16_t enable,
2125 uint16_t oldFlags = eventFlags_;
2126 eventFlags_ |= enable;
2127 eventFlags_ &= ~disable;
2128 if (eventFlags_ == oldFlags) {
2131 return updateEventRegistration();
2135 void AsyncSocket::startFail() {
2136 // startFail() should only be called once
2137 assert(state_ != StateEnum::ERROR);
2138 assert(getDestructorGuardCount() > 0);
2139 state_ = StateEnum::ERROR;
2140 // Ensure that SHUT_READ and SHUT_WRITE are set,
2141 // so all future attempts to read or write will be rejected
2142 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
2144 if (eventFlags_ != EventHandler::NONE) {
2145 eventFlags_ = EventHandler::NONE;
2146 ioHandler_.unregisterHandler();
2148 writeTimeout_.cancelTimeout();
2151 ioHandler_.changeHandlerFD(-1);
2156 void AsyncSocket::invokeAllErrors(const AsyncSocketException& ex) {
2157 invokeConnectErr(ex);
2160 if (readCallback_) {
2161 ReadCallback* callback = readCallback_;
2162 readCallback_ = nullptr;
2163 callback->readErr(ex);
2167 void AsyncSocket::finishFail() {
2168 assert(state_ == StateEnum::ERROR);
2169 assert(getDestructorGuardCount() > 0);
2171 AsyncSocketException ex(
2172 AsyncSocketException::INTERNAL_ERROR,
2173 withAddr("socket closing after error"));
2174 invokeAllErrors(ex);
2177 void AsyncSocket::finishFail(const AsyncSocketException& ex) {
2178 assert(state_ == StateEnum::ERROR);
2179 assert(getDestructorGuardCount() > 0);
2180 invokeAllErrors(ex);
2183 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
2184 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2185 << state_ << " host=" << addr_.describe()
2186 << "): failed in " << fn << "(): "
2192 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
2193 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2194 << state_ << " host=" << addr_.describe()
2195 << "): failed while connecting in " << fn << "(): "
2199 invokeConnectErr(ex);
2203 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
2204 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2205 << state_ << " host=" << addr_.describe()
2206 << "): failed while reading in " << fn << "(): "
2210 if (readCallback_ != nullptr) {
2211 ReadCallback* callback = readCallback_;
2212 readCallback_ = nullptr;
2213 callback->readErr(ex);
2219 void AsyncSocket::failErrMessageRead(const char* fn,
2220 const AsyncSocketException& ex) {
2221 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2222 << state_ << " host=" << addr_.describe()
2223 << "): failed while reading message in " << fn << "(): "
2227 if (errMessageCallback_ != nullptr) {
2228 ErrMessageCallback* callback = errMessageCallback_;
2229 errMessageCallback_ = nullptr;
2230 callback->errMessageError(ex);
2236 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
2237 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2238 << state_ << " host=" << addr_.describe()
2239 << "): failed while writing in " << fn << "(): "
2243 // Only invoke the first write callback, since the error occurred while
2244 // writing this request. Let any other pending write callbacks be invoked in
2246 if (writeReqHead_ != nullptr) {
2247 WriteRequest* req = writeReqHead_;
2248 writeReqHead_ = req->getNext();
2249 WriteCallback* callback = req->getCallback();
2250 uint32_t bytesWritten = req->getTotalBytesWritten();
2253 callback->writeErr(bytesWritten, ex);
2260 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
2261 size_t bytesWritten,
2262 const AsyncSocketException& ex) {
2263 // This version of failWrite() is used when the failure occurs before
2264 // we've added the callback to writeReqHead_.
2265 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2266 << state_ << " host=" << addr_.describe()
2267 <<"): failed while writing in " << fn << "(): "
2271 if (callback != nullptr) {
2272 callback->writeErr(bytesWritten, ex);
2278 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
2279 // Invoke writeError() on all write callbacks.
2280 // This is used when writes are forcibly shutdown with write requests
2281 // pending, or when an error occurs with writes pending.
2282 while (writeReqHead_ != nullptr) {
2283 WriteRequest* req = writeReqHead_;
2284 writeReqHead_ = req->getNext();
2285 WriteCallback* callback = req->getCallback();
2287 callback->writeErr(req->getTotalBytesWritten(), ex);
2293 void AsyncSocket::invalidState(ConnectCallback* callback) {
2294 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2295 << "): connect() called in invalid state " << state_;
2298 * The invalidState() methods don't use the normal failure mechanisms,
2299 * since we don't know what state we are in. We don't want to call
2300 * startFail()/finishFail() recursively if we are already in the middle of
2304 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
2305 "connect() called with socket in invalid state");
2306 connectEndTime_ = std::chrono::steady_clock::now();
2307 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2309 callback->connectErr(ex);
2312 // We can't use failConnect() here since connectCallback_
2313 // may already be set to another callback. Invoke this ConnectCallback
2314 // here; any other connectCallback_ will be invoked in finishFail()
2317 callback->connectErr(ex);
2323 void AsyncSocket::invalidState(ErrMessageCallback* callback) {
2324 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2325 << "): setErrMessageCB(" << callback
2326 << ") called in invalid state " << state_;
2328 AsyncSocketException ex(
2329 AsyncSocketException::NOT_OPEN,
2330 msgErrQueueSupported
2331 ? "setErrMessageCB() called with socket in invalid state"
2332 : "This platform does not support socket error message notifications");
2333 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2335 callback->errMessageError(ex);
2340 callback->errMessageError(ex);
2346 void AsyncSocket::invokeConnectErr(const AsyncSocketException& ex) {
2347 connectEndTime_ = std::chrono::steady_clock::now();
2348 if (connectCallback_) {
2349 ConnectCallback* callback = connectCallback_;
2350 connectCallback_ = nullptr;
2351 callback->connectErr(ex);
2355 void AsyncSocket::invokeConnectSuccess() {
2356 connectEndTime_ = std::chrono::steady_clock::now();
2357 if (connectCallback_) {
2358 ConnectCallback* callback = connectCallback_;
2359 connectCallback_ = nullptr;
2360 callback->connectSuccess();
2364 void AsyncSocket::invalidState(ReadCallback* callback) {
2365 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2366 << "): setReadCallback(" << callback
2367 << ") called in invalid state " << state_;
2369 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2370 "setReadCallback() called with socket in "
2372 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2374 callback->readErr(ex);
2379 callback->readErr(ex);
2385 void AsyncSocket::invalidState(WriteCallback* callback) {
2386 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2387 << "): write() called in invalid state " << state_;
2389 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2390 withAddr("write() called with socket in invalid state"));
2391 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2393 callback->writeErr(0, ex);
2398 callback->writeErr(0, ex);
2404 void AsyncSocket::doClose() {
2405 if (fd_ == -1) return;
2406 if (shutdownSocketSet_) {
2407 shutdownSocketSet_->close(fd_);
2414 std::ostream& operator << (std::ostream& os,
2415 const AsyncSocket::StateEnum& state) {
2416 os << static_cast<int>(state);
2420 std::string AsyncSocket::withAddr(const std::string& s) {
2421 // Don't use addr_ directly because it may not be initialized
2422 // e.g. if constructed from fd
2423 folly::SocketAddress peer, local;
2425 getPeerAddress(&peer);
2426 getLocalAddress(&local);
2427 } catch (const std::exception&) {
2432 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";
2435 void AsyncSocket::setBufferCallback(BufferCallback* cb) {
2436 bufferCallback_ = cb;