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/SocketAddress.h>
21 #include <folly/io/IOBuf.h>
22 #include <folly/Portability.h>
23 #include <folly/portability/Fcntl.h>
24 #include <folly/portability/Sockets.h>
25 #include <folly/portability/SysUio.h>
26 #include <folly/portability/Unistd.h>
28 #include <boost/preprocessor/control/if.hpp>
31 #include <sys/types.h>
35 using std::unique_ptr;
37 namespace fsp = folly::portability::sockets;
41 static constexpr bool msgErrQueueSupported =
46 #endif // MSG_ERRQUEUE
48 // static members initializers
49 const AsyncSocket::OptionMap AsyncSocket::emptyOptionMap;
51 const AsyncSocketException socketClosedLocallyEx(
52 AsyncSocketException::END_OF_FILE, "socket closed locally");
53 const AsyncSocketException socketShutdownForWritesEx(
54 AsyncSocketException::END_OF_FILE, "socket shutdown for writes");
56 // TODO: It might help performance to provide a version of BytesWriteRequest that
57 // users could derive from, so we can avoid the extra allocation for each call
58 // to write()/writev(). We could templatize TFramedAsyncChannel just like the
59 // protocols are currently templatized for transports.
61 // We would need the version for external users where they provide the iovec
62 // storage space, and only our internal version would allocate it at the end of
65 /* The default WriteRequest implementation, used for write(), writev() and
68 * A new BytesWriteRequest operation is allocated on the heap for all write
69 * operations that cannot be completed immediately.
71 class AsyncSocket::BytesWriteRequest : public AsyncSocket::WriteRequest {
73 static BytesWriteRequest* newRequest(AsyncSocket* socket,
74 WriteCallback* callback,
77 uint32_t partialWritten,
78 uint32_t bytesWritten,
79 unique_ptr<IOBuf>&& ioBuf,
82 // Since we put a variable size iovec array at the end
83 // of each BytesWriteRequest, we have to manually allocate the memory.
84 void* buf = malloc(sizeof(BytesWriteRequest) +
85 (opCount * sizeof(struct iovec)));
87 throw std::bad_alloc();
90 return new(buf) BytesWriteRequest(socket, callback, ops, opCount,
91 partialWritten, bytesWritten,
92 std::move(ioBuf), flags);
95 void destroy() override {
96 this->~BytesWriteRequest();
100 WriteResult performWrite() override {
101 WriteFlags writeFlags = flags_;
102 if (getNext() != nullptr) {
103 writeFlags |= WriteFlags::CORK;
105 auto writeResult = socket_->performWrite(
106 getOps(), getOpCount(), writeFlags, &opsWritten_, &partialBytes_);
107 bytesWritten_ = writeResult.writeReturn > 0 ? writeResult.writeReturn : 0;
111 bool isComplete() override {
112 return opsWritten_ == getOpCount();
115 void consume() override {
116 // Advance opIndex_ forward by opsWritten_
117 opIndex_ += opsWritten_;
118 assert(opIndex_ < opCount_);
120 // If we've finished writing any IOBufs, release them
122 for (uint32_t i = opsWritten_; i != 0; --i) {
124 ioBuf_ = ioBuf_->pop();
128 // Move partialBytes_ forward into the current iovec buffer
129 struct iovec* currentOp = writeOps_ + opIndex_;
130 assert((partialBytes_ < currentOp->iov_len) || (currentOp->iov_len == 0));
131 currentOp->iov_base =
132 reinterpret_cast<uint8_t*>(currentOp->iov_base) + partialBytes_;
133 currentOp->iov_len -= partialBytes_;
135 // Increment the totalBytesWritten_ count by bytesWritten_;
136 assert(bytesWritten_ >= 0);
137 totalBytesWritten_ += uint32_t(bytesWritten_);
141 BytesWriteRequest(AsyncSocket* socket,
142 WriteCallback* callback,
143 const struct iovec* ops,
145 uint32_t partialBytes,
146 uint32_t bytesWritten,
147 unique_ptr<IOBuf>&& ioBuf,
149 : AsyncSocket::WriteRequest(socket, callback)
153 , ioBuf_(std::move(ioBuf))
155 , partialBytes_(partialBytes)
156 , bytesWritten_(bytesWritten) {
157 memcpy(writeOps_, ops, sizeof(*ops) * opCount_);
160 // private destructor, to ensure callers use destroy()
161 ~BytesWriteRequest() override = default;
163 const struct iovec* getOps() const {
164 assert(opCount_ > opIndex_);
165 return writeOps_ + opIndex_;
168 uint32_t getOpCount() const {
169 assert(opCount_ > opIndex_);
170 return opCount_ - opIndex_;
173 uint32_t opCount_; ///< number of entries in writeOps_
174 uint32_t opIndex_; ///< current index into writeOps_
175 WriteFlags flags_; ///< set for WriteFlags
176 unique_ptr<IOBuf> ioBuf_; ///< underlying IOBuf, or nullptr if N/A
178 // for consume(), how much we wrote on the last write
179 uint32_t opsWritten_; ///< complete ops written
180 uint32_t partialBytes_; ///< partial bytes of incomplete op written
181 ssize_t bytesWritten_; ///< bytes written altogether
183 struct iovec writeOps_[]; ///< write operation(s) list
186 AsyncSocket::AsyncSocket()
187 : eventBase_(nullptr),
188 writeTimeout_(this, nullptr),
189 ioHandler_(this, nullptr),
190 immediateReadHandler_(this) {
191 VLOG(5) << "new AsyncSocket()";
195 AsyncSocket::AsyncSocket(EventBase* evb)
197 writeTimeout_(this, evb),
198 ioHandler_(this, evb),
199 immediateReadHandler_(this) {
200 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
204 AsyncSocket::AsyncSocket(EventBase* evb,
205 const folly::SocketAddress& address,
206 uint32_t connectTimeout)
208 connect(nullptr, address, connectTimeout);
211 AsyncSocket::AsyncSocket(EventBase* evb,
212 const std::string& ip,
214 uint32_t connectTimeout)
216 connect(nullptr, ip, port, connectTimeout);
219 AsyncSocket::AsyncSocket(EventBase* evb, int fd)
221 writeTimeout_(this, evb),
222 ioHandler_(this, evb, fd),
223 immediateReadHandler_(this) {
224 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ", fd="
229 state_ = StateEnum::ESTABLISHED;
232 // init() method, since constructor forwarding isn't supported in most
234 void AsyncSocket::init() {
235 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
237 state_ = StateEnum::UNINIT;
238 eventFlags_ = EventHandler::NONE;
241 maxReadsPerEvent_ = 16;
242 connectCallback_ = nullptr;
243 errMessageCallback_ = nullptr;
244 readCallback_ = nullptr;
245 writeReqHead_ = nullptr;
246 writeReqTail_ = nullptr;
247 shutdownSocketSet_ = nullptr;
248 appBytesWritten_ = 0;
249 appBytesReceived_ = 0;
252 AsyncSocket::~AsyncSocket() {
253 VLOG(7) << "actual destruction of AsyncSocket(this=" << this
254 << ", evb=" << eventBase_ << ", fd=" << fd_
255 << ", state=" << state_ << ")";
258 void AsyncSocket::destroy() {
259 VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
260 << ", fd=" << fd_ << ", state=" << state_;
261 // When destroy is called, close the socket immediately
264 // Then call DelayedDestruction::destroy() to take care of
265 // whether or not we need immediate or delayed destruction
266 DelayedDestruction::destroy();
269 int AsyncSocket::detachFd() {
270 VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
271 << ", evb=" << eventBase_ << ", state=" << state_
272 << ", events=" << std::hex << eventFlags_ << ")";
273 // Extract the fd, and set fd_ to -1 first, so closeNow() won't
274 // actually close the descriptor.
275 if (shutdownSocketSet_) {
276 shutdownSocketSet_->remove(fd_);
280 // Call closeNow() to invoke all pending callbacks with an error.
282 // Update the EventHandler to stop using this fd.
283 // This can only be done after closeNow() unregisters the handler.
284 ioHandler_.changeHandlerFD(-1);
288 const folly::SocketAddress& AsyncSocket::anyAddress() {
289 static const folly::SocketAddress anyAddress =
290 folly::SocketAddress("0.0.0.0", 0);
294 void AsyncSocket::setShutdownSocketSet(ShutdownSocketSet* newSS) {
295 if (shutdownSocketSet_ == newSS) {
298 if (shutdownSocketSet_ && fd_ != -1) {
299 shutdownSocketSet_->remove(fd_);
301 shutdownSocketSet_ = newSS;
302 if (shutdownSocketSet_ && fd_ != -1) {
303 shutdownSocketSet_->add(fd_);
307 void AsyncSocket::setCloseOnExec() {
308 int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
310 auto errnoCopy = errno;
311 throw AsyncSocketException(
312 AsyncSocketException::INTERNAL_ERROR,
313 withAddr("failed to set close-on-exec flag"),
318 void AsyncSocket::connect(ConnectCallback* callback,
319 const folly::SocketAddress& address,
321 const OptionMap &options,
322 const folly::SocketAddress& bindAddr) noexcept {
323 DestructorGuard dg(this);
324 assert(eventBase_->isInEventBaseThread());
328 // Make sure we're in the uninitialized state
329 if (state_ != StateEnum::UNINIT) {
330 return invalidState(callback);
333 connectTimeout_ = std::chrono::milliseconds(timeout);
334 connectStartTime_ = std::chrono::steady_clock::now();
335 // Make connect end time at least >= connectStartTime.
336 connectEndTime_ = connectStartTime_;
339 state_ = StateEnum::CONNECTING;
340 connectCallback_ = callback;
342 sockaddr_storage addrStorage;
343 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
347 // Technically the first parameter should actually be a protocol family
348 // constant (PF_xxx) rather than an address family (AF_xxx), but the
349 // distinction is mainly just historical. In pretty much all
350 // implementations the PF_foo and AF_foo constants are identical.
351 fd_ = fsp::socket(address.getFamily(), SOCK_STREAM, 0);
353 auto errnoCopy = errno;
354 throw AsyncSocketException(
355 AsyncSocketException::INTERNAL_ERROR,
356 withAddr("failed to create socket"),
359 if (shutdownSocketSet_) {
360 shutdownSocketSet_->add(fd_);
362 ioHandler_.changeHandlerFD(fd_);
366 // Put the socket in non-blocking mode
367 int flags = fcntl(fd_, F_GETFL, 0);
369 auto errnoCopy = errno;
370 throw AsyncSocketException(
371 AsyncSocketException::INTERNAL_ERROR,
372 withAddr("failed to get socket flags"),
375 int rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
377 auto errnoCopy = errno;
378 throw AsyncSocketException(
379 AsyncSocketException::INTERNAL_ERROR,
380 withAddr("failed to put socket in non-blocking mode"),
384 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
385 // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
386 rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
388 auto errnoCopy = errno;
389 throw AsyncSocketException(
390 AsyncSocketException::INTERNAL_ERROR,
391 "failed to enable F_SETNOSIGPIPE on socket",
396 // By default, turn on TCP_NODELAY
397 // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
398 // setNoDelay() will log an error message if it fails.
399 if (address.getFamily() != AF_UNIX) {
400 (void)setNoDelay(true);
403 VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
404 << ", fd=" << fd_ << ", host=" << address.describe().c_str();
407 if (bindAddr != anyAddress()) {
409 if (setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
410 auto errnoCopy = errno;
412 throw AsyncSocketException(
413 AsyncSocketException::NOT_OPEN,
414 "failed to setsockopt prior to bind on " + bindAddr.describe(),
418 bindAddr.getAddress(&addrStorage);
420 if (bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
421 auto errnoCopy = errno;
423 throw AsyncSocketException(
424 AsyncSocketException::NOT_OPEN,
425 "failed to bind to async socket: " + bindAddr.describe(),
430 // Apply the additional options if any.
431 for (const auto& opt: options) {
432 rv = opt.first.apply(fd_, opt.second);
434 auto errnoCopy = errno;
435 throw AsyncSocketException(
436 AsyncSocketException::INTERNAL_ERROR,
437 withAddr("failed to set socket option"),
442 // Perform the connect()
443 address.getAddress(&addrStorage);
446 state_ = StateEnum::FAST_OPEN;
447 tfoAttempted_ = true;
449 if (socketConnect(saddr, addr_.getActualSize()) < 0) {
454 // If we're still here the connect() succeeded immediately.
455 // Fall through to call the callback outside of this try...catch block
456 } catch (const AsyncSocketException& ex) {
457 return failConnect(__func__, ex);
458 } catch (const std::exception& ex) {
459 // shouldn't happen, but handle it just in case
460 VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
461 << "): unexpected " << typeid(ex).name() << " exception: "
463 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
464 withAddr(string("unexpected exception: ") +
466 return failConnect(__func__, tex);
469 // The connection succeeded immediately
470 // The read callback may not have been set yet, and no writes may be pending
471 // yet, so we don't have to register for any events at the moment.
472 VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
473 assert(errMessageCallback_ == nullptr);
474 assert(readCallback_ == nullptr);
475 assert(writeReqHead_ == nullptr);
476 if (state_ != StateEnum::FAST_OPEN) {
477 state_ = StateEnum::ESTABLISHED;
479 invokeConnectSuccess();
482 int AsyncSocket::socketConnect(const struct sockaddr* saddr, socklen_t len) {
484 if (noTransparentTls_) {
485 // Ignore return value, errors are ok
486 setsockopt(fd_, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0);
489 int rv = fsp::connect(fd_, saddr, len);
491 auto errnoCopy = errno;
492 if (errnoCopy == EINPROGRESS) {
493 scheduleConnectTimeout();
494 registerForConnectEvents();
496 throw AsyncSocketException(
497 AsyncSocketException::NOT_OPEN,
498 "connect failed (immediately)",
505 void AsyncSocket::scheduleConnectTimeout() {
506 // Connection in progress.
507 auto timeout = connectTimeout_.count();
509 // Start a timer in case the connection takes too long.
510 if (!writeTimeout_.scheduleTimeout(uint32_t(timeout))) {
511 throw AsyncSocketException(
512 AsyncSocketException::INTERNAL_ERROR,
513 withAddr("failed to schedule AsyncSocket connect timeout"));
518 void AsyncSocket::registerForConnectEvents() {
519 // Register for write events, so we'll
520 // be notified when the connection finishes/fails.
521 // Note that we don't register for a persistent event here.
522 assert(eventFlags_ == EventHandler::NONE);
523 eventFlags_ = EventHandler::WRITE;
524 if (!ioHandler_.registerHandler(eventFlags_)) {
525 throw AsyncSocketException(
526 AsyncSocketException::INTERNAL_ERROR,
527 withAddr("failed to register AsyncSocket connect handler"));
531 void AsyncSocket::connect(ConnectCallback* callback,
532 const string& ip, uint16_t port,
534 const OptionMap &options) noexcept {
535 DestructorGuard dg(this);
537 connectCallback_ = callback;
538 connect(callback, folly::SocketAddress(ip, port), timeout, options);
539 } catch (const std::exception& ex) {
540 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
542 return failConnect(__func__, tex);
546 void AsyncSocket::cancelConnect() {
547 connectCallback_ = nullptr;
548 if (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN) {
553 void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
554 sendTimeout_ = milliseconds;
555 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
557 // If we are currently pending on write requests, immediately update
558 // writeTimeout_ with the new value.
559 if ((eventFlags_ & EventHandler::WRITE) &&
560 (state_ != StateEnum::CONNECTING && state_ != StateEnum::FAST_OPEN)) {
561 assert(state_ == StateEnum::ESTABLISHED);
562 assert((shutdownFlags_ & SHUT_WRITE) == 0);
563 if (sendTimeout_ > 0) {
564 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
565 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
566 withAddr("failed to reschedule send timeout in setSendTimeout"));
567 return failWrite(__func__, ex);
570 writeTimeout_.cancelTimeout();
575 void AsyncSocket::setErrMessageCB(ErrMessageCallback* callback) {
576 VLOG(6) << "AsyncSocket::setErrMessageCB() this=" << this
577 << ", fd=" << fd_ << ", callback=" << callback
578 << ", state=" << state_;
580 // Short circuit if callback is the same as the existing timestampCallback_.
581 if (callback == errMessageCallback_) {
585 if (!msgErrQueueSupported) {
586 // Per-socket error message queue is not supported on this platform.
587 return invalidState(callback);
590 DestructorGuard dg(this);
591 assert(eventBase_->isInEventBaseThread());
593 switch ((StateEnum)state_) {
594 case StateEnum::CONNECTING:
595 case StateEnum::FAST_OPEN:
596 case StateEnum::ESTABLISHED: {
597 errMessageCallback_ = callback;
600 case StateEnum::CLOSED:
601 case StateEnum::ERROR:
602 // We should never reach here. SHUT_READ should always be set
603 // if we are in STATE_CLOSED or STATE_ERROR.
605 return invalidState(callback);
606 case StateEnum::UNINIT:
607 // We do not allow setReadCallback() to be called before we start
609 return invalidState(callback);
612 // We don't put a default case in the switch statement, so that the compiler
613 // will warn us to update the switch statement if a new state is added.
614 return invalidState(callback);
617 AsyncSocket::ErrMessageCallback* AsyncSocket::getErrMessageCallback() const {
618 return errMessageCallback_;
621 void AsyncSocket::setReadCB(ReadCallback *callback) {
622 VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
623 << ", callback=" << callback << ", state=" << state_;
625 // Short circuit if callback is the same as the existing readCallback_.
627 // Note that this is needed for proper functioning during some cleanup cases.
628 // During cleanup we allow setReadCallback(nullptr) to be called even if the
629 // read callback is already unset and we have been detached from an event
630 // base. This check prevents us from asserting
631 // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
632 if (callback == readCallback_) {
636 /* We are removing a read callback */
637 if (callback == nullptr &&
638 immediateReadHandler_.isLoopCallbackScheduled()) {
639 immediateReadHandler_.cancelLoopCallback();
642 if (shutdownFlags_ & SHUT_READ) {
643 // Reads have already been shut down on this socket.
645 // Allow setReadCallback(nullptr) to be called in this case, but don't
646 // allow a new callback to be set.
648 // For example, setReadCallback(nullptr) can happen after an error if we
649 // invoke some other error callback before invoking readError(). The other
650 // error callback that is invoked first may go ahead and clear the read
651 // callback before we get a chance to invoke readError().
652 if (callback != nullptr) {
653 return invalidState(callback);
655 assert((eventFlags_ & EventHandler::READ) == 0);
656 readCallback_ = nullptr;
660 DestructorGuard dg(this);
661 assert(eventBase_->isInEventBaseThread());
663 switch ((StateEnum)state_) {
664 case StateEnum::CONNECTING:
665 case StateEnum::FAST_OPEN:
666 // For convenience, we allow the read callback to be set while we are
667 // still connecting. We just store the callback for now. Once the
668 // connection completes we'll register for read events.
669 readCallback_ = callback;
671 case StateEnum::ESTABLISHED:
673 readCallback_ = callback;
674 uint16_t oldFlags = eventFlags_;
676 eventFlags_ |= EventHandler::READ;
678 eventFlags_ &= ~EventHandler::READ;
681 // Update our registration if our flags have changed
682 if (eventFlags_ != oldFlags) {
683 // We intentionally ignore the return value here.
684 // updateEventRegistration() will move us into the error state if it
685 // fails, and we don't need to do anything else here afterwards.
686 (void)updateEventRegistration();
690 checkForImmediateRead();
694 case StateEnum::CLOSED:
695 case StateEnum::ERROR:
696 // We should never reach here. SHUT_READ should always be set
697 // if we are in STATE_CLOSED or STATE_ERROR.
699 return invalidState(callback);
700 case StateEnum::UNINIT:
701 // We do not allow setReadCallback() to be called before we start
703 return invalidState(callback);
706 // We don't put a default case in the switch statement, so that the compiler
707 // will warn us to update the switch statement if a new state is added.
708 return invalidState(callback);
711 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
712 return readCallback_;
715 void AsyncSocket::write(WriteCallback* callback,
716 const void* buf, size_t bytes, WriteFlags flags) {
718 op.iov_base = const_cast<void*>(buf);
720 writeImpl(callback, &op, 1, unique_ptr<IOBuf>(), flags);
723 void AsyncSocket::writev(WriteCallback* callback,
727 writeImpl(callback, vec, count, unique_ptr<IOBuf>(), flags);
730 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
732 constexpr size_t kSmallSizeMax = 64;
733 size_t count = buf->countChainElements();
734 if (count <= kSmallSizeMax) {
735 // suppress "warning: variable length array 'vec' is used [-Wvla]"
737 FOLLY_GCC_DISABLE_WARNING(vla);
738 iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA, count, kSmallSizeMax)];
741 writeChainImpl(callback, vec, count, std::move(buf), flags);
743 iovec* vec = new iovec[count];
744 writeChainImpl(callback, vec, count, std::move(buf), flags);
749 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
750 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
751 size_t veclen = buf->fillIov(vec, count);
752 writeImpl(callback, vec, veclen, std::move(buf), flags);
755 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
756 size_t count, unique_ptr<IOBuf>&& buf,
758 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
759 << ", callback=" << callback << ", count=" << count
760 << ", state=" << state_;
761 DestructorGuard dg(this);
762 unique_ptr<IOBuf>ioBuf(std::move(buf));
763 assert(eventBase_->isInEventBaseThread());
765 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
766 // No new writes may be performed after the write side of the socket has
769 // We could just call callback->writeError() here to fail just this write.
770 // However, fail hard and use invalidState() to fail all outstanding
771 // callbacks and move the socket into the error state. There's most likely
772 // a bug in the caller's code, so we abort everything rather than trying to
773 // proceed as best we can.
774 return invalidState(callback);
777 uint32_t countWritten = 0;
778 uint32_t partialWritten = 0;
779 ssize_t bytesWritten = 0;
780 bool mustRegister = false;
781 if ((state_ == StateEnum::ESTABLISHED || state_ == StateEnum::FAST_OPEN) &&
783 if (writeReqHead_ == nullptr) {
784 // If we are established and there are no other writes pending,
785 // we can attempt to perform the write immediately.
786 assert(writeReqTail_ == nullptr);
787 assert((eventFlags_ & EventHandler::WRITE) == 0);
789 auto writeResult = performWrite(
790 vec, uint32_t(count), flags, &countWritten, &partialWritten);
791 bytesWritten = writeResult.writeReturn;
792 if (bytesWritten < 0) {
793 auto errnoCopy = errno;
794 if (writeResult.exception) {
795 return failWrite(__func__, callback, 0, *writeResult.exception);
797 AsyncSocketException ex(
798 AsyncSocketException::INTERNAL_ERROR,
799 withAddr("writev failed"),
801 return failWrite(__func__, callback, 0, ex);
802 } else if (countWritten == count) {
803 // We successfully wrote everything.
804 // Invoke the callback and return.
806 callback->writeSuccess();
809 } else { // continue writing the next writeReq
810 if (bufferCallback_) {
811 bufferCallback_->onEgressBuffered();
815 // Writes might put the socket back into connecting state
816 // if TFO is enabled, and using TFO fails.
817 // This means that write timeouts would not be active, however
818 // connect timeouts would affect this stage.
822 } else if (!connecting()) {
823 // Invalid state for writing
824 return invalidState(callback);
827 // Create a new WriteRequest to add to the queue
830 req = BytesWriteRequest::newRequest(
834 uint32_t(count - countWritten),
836 uint32_t(bytesWritten),
839 } catch (const std::exception& ex) {
840 // we mainly expect to catch std::bad_alloc here
841 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
842 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
843 return failWrite(__func__, callback, size_t(bytesWritten), tex);
846 if (writeReqTail_ == nullptr) {
847 assert(writeReqHead_ == nullptr);
848 writeReqHead_ = writeReqTail_ = req;
850 writeReqTail_->append(req);
854 // Register for write events if are established and not currently
855 // waiting on write events
857 assert(state_ == StateEnum::ESTABLISHED);
858 assert((eventFlags_ & EventHandler::WRITE) == 0);
859 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
860 assert(state_ == StateEnum::ERROR);
863 if (sendTimeout_ > 0) {
864 // Schedule a timeout to fire if the write takes too long.
865 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
866 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
867 withAddr("failed to schedule send timeout"));
868 return failWrite(__func__, ex);
874 void AsyncSocket::writeRequest(WriteRequest* req) {
875 if (writeReqTail_ == nullptr) {
876 assert(writeReqHead_ == nullptr);
877 writeReqHead_ = writeReqTail_ = req;
880 writeReqTail_->append(req);
885 void AsyncSocket::close() {
886 VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
887 << ", state=" << state_ << ", shutdownFlags="
888 << std::hex << (int) shutdownFlags_;
890 // close() is only different from closeNow() when there are pending writes
891 // that need to drain before we can close. In all other cases, just call
894 // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
895 // STATE_ERROR if close() is invoked while a previous closeNow() or failure
896 // is still running. (e.g., If there are multiple pending writes, and we
897 // call writeError() on the first one, it may call close(). In this case we
898 // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
899 // writes will still be in the queue.)
901 // We only need to drain pending writes if we are still in STATE_CONNECTING
902 // or STATE_ESTABLISHED
903 if ((writeReqHead_ == nullptr) ||
904 !(state_ == StateEnum::CONNECTING ||
905 state_ == StateEnum::ESTABLISHED)) {
910 // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
911 // destroyed until close() returns.
912 DestructorGuard dg(this);
913 assert(eventBase_->isInEventBaseThread());
915 // Since there are write requests pending, we have to set the
916 // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
917 // connect finishes and we finish writing these requests.
919 // Set SHUT_READ to indicate that reads are shut down, and set the
920 // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
921 // pending writes complete.
922 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
924 // If a read callback is set, invoke readEOF() immediately to inform it that
925 // the socket has been closed and no more data can be read.
927 // Disable reads if they are enabled
928 if (!updateEventRegistration(0, EventHandler::READ)) {
929 // We're now in the error state; callbacks have been cleaned up
930 assert(state_ == StateEnum::ERROR);
931 assert(readCallback_ == nullptr);
933 ReadCallback* callback = readCallback_;
934 readCallback_ = nullptr;
940 void AsyncSocket::closeNow() {
941 VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
942 << ", state=" << state_ << ", shutdownFlags="
943 << std::hex << (int) shutdownFlags_;
944 DestructorGuard dg(this);
945 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
948 case StateEnum::ESTABLISHED:
949 case StateEnum::CONNECTING:
950 case StateEnum::FAST_OPEN: {
951 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
952 state_ = StateEnum::CLOSED;
954 // If the write timeout was set, cancel it.
955 writeTimeout_.cancelTimeout();
957 // If we are registered for I/O events, unregister.
958 if (eventFlags_ != EventHandler::NONE) {
959 eventFlags_ = EventHandler::NONE;
960 if (!updateEventRegistration()) {
961 // We will have been moved into the error state.
962 assert(state_ == StateEnum::ERROR);
967 if (immediateReadHandler_.isLoopCallbackScheduled()) {
968 immediateReadHandler_.cancelLoopCallback();
972 ioHandler_.changeHandlerFD(-1);
976 invokeConnectErr(socketClosedLocallyEx);
978 failAllWrites(socketClosedLocallyEx);
981 ReadCallback* callback = readCallback_;
982 readCallback_ = nullptr;
987 case StateEnum::CLOSED:
988 // Do nothing. It's possible that we are being called recursively
989 // from inside a callback that we invoked inside another call to close()
990 // that is still running.
992 case StateEnum::ERROR:
993 // Do nothing. The error handling code has performed (or is performing)
996 case StateEnum::UNINIT:
997 assert(eventFlags_ == EventHandler::NONE);
998 assert(connectCallback_ == nullptr);
999 assert(readCallback_ == nullptr);
1000 assert(writeReqHead_ == nullptr);
1001 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1002 state_ = StateEnum::CLOSED;
1006 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
1007 << ") called in unknown state " << state_;
1010 void AsyncSocket::closeWithReset() {
1011 // Enable SO_LINGER, with the linger timeout set to 0.
1012 // This will trigger a TCP reset when we close the socket.
1014 struct linger optLinger = {1, 0};
1015 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
1016 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
1017 << "on " << fd_ << ": errno=" << errno;
1021 // Then let closeNow() take care of the rest
1025 void AsyncSocket::shutdownWrite() {
1026 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
1027 << ", state=" << state_ << ", shutdownFlags="
1028 << std::hex << (int) shutdownFlags_;
1030 // If there are no pending writes, shutdownWrite() is identical to
1031 // shutdownWriteNow().
1032 if (writeReqHead_ == nullptr) {
1037 assert(eventBase_->isInEventBaseThread());
1039 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
1040 // shutdown will be performed once all writes complete.
1041 shutdownFlags_ |= SHUT_WRITE_PENDING;
1044 void AsyncSocket::shutdownWriteNow() {
1045 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
1046 << ", fd=" << fd_ << ", state=" << state_
1047 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
1049 if (shutdownFlags_ & SHUT_WRITE) {
1050 // Writes are already shutdown; nothing else to do.
1054 // If SHUT_READ is already set, just call closeNow() to completely
1055 // close the socket. This can happen if close() was called with writes
1056 // pending, and then shutdownWriteNow() is called before all pending writes
1058 if (shutdownFlags_ & SHUT_READ) {
1063 DestructorGuard dg(this);
1064 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
1066 switch (static_cast<StateEnum>(state_)) {
1067 case StateEnum::ESTABLISHED:
1069 shutdownFlags_ |= SHUT_WRITE;
1071 // If the write timeout was set, cancel it.
1072 writeTimeout_.cancelTimeout();
1074 // If we are registered for write events, unregister.
1075 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1076 // We will have been moved into the error state.
1077 assert(state_ == StateEnum::ERROR);
1081 // Shutdown writes on the file descriptor
1082 shutdown(fd_, SHUT_WR);
1084 // Immediately fail all write requests
1085 failAllWrites(socketShutdownForWritesEx);
1088 case StateEnum::CONNECTING:
1090 // Set the SHUT_WRITE_PENDING flag.
1091 // When the connection completes, it will check this flag,
1092 // shutdown the write half of the socket, and then set SHUT_WRITE.
1093 shutdownFlags_ |= SHUT_WRITE_PENDING;
1095 // Immediately fail all write requests
1096 failAllWrites(socketShutdownForWritesEx);
1099 case StateEnum::UNINIT:
1100 // Callers normally shouldn't call shutdownWriteNow() before the socket
1101 // even starts connecting. Nonetheless, go ahead and set
1102 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
1103 // immediately shut down the write side of the socket.
1104 shutdownFlags_ |= SHUT_WRITE_PENDING;
1106 case StateEnum::FAST_OPEN:
1107 // In fast open state we haven't call connected yet, and if we shutdown
1108 // the writes, we will never try to call connect, so shut everything down
1109 shutdownFlags_ |= SHUT_WRITE;
1110 // Immediately fail all write requests
1111 failAllWrites(socketShutdownForWritesEx);
1113 case StateEnum::CLOSED:
1114 case StateEnum::ERROR:
1115 // We should never get here. SHUT_WRITE should always be set
1116 // in STATE_CLOSED and STATE_ERROR.
1117 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
1118 << ", fd=" << fd_ << ") in unexpected state " << state_
1119 << " with SHUT_WRITE not set ("
1120 << std::hex << (int) shutdownFlags_ << ")";
1125 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
1126 << fd_ << ") called in unknown state " << state_;
1129 bool AsyncSocket::readable() const {
1133 struct pollfd fds[1];
1135 fds[0].events = POLLIN;
1137 int rc = poll(fds, 1, 0);
1141 bool AsyncSocket::isPending() const {
1142 return ioHandler_.isPending();
1145 bool AsyncSocket::hangup() const {
1147 // sanity check, no one should ask for hangup if we are not connected.
1151 #ifdef POLLRDHUP // Linux-only
1152 struct pollfd fds[1];
1154 fds[0].events = POLLRDHUP|POLLHUP;
1157 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1163 bool AsyncSocket::good() const {
1165 (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN ||
1166 state_ == StateEnum::ESTABLISHED) &&
1167 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1170 bool AsyncSocket::error() const {
1171 return (state_ == StateEnum::ERROR);
1174 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1175 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1176 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1177 << ", state=" << state_ << ", events="
1178 << std::hex << eventFlags_ << ")";
1179 assert(eventBase_ == nullptr);
1180 assert(eventBase->isInEventBaseThread());
1182 eventBase_ = eventBase;
1183 ioHandler_.attachEventBase(eventBase);
1184 writeTimeout_.attachEventBase(eventBase);
1186 evbChangeCb_->evbAttached(this);
1190 void AsyncSocket::detachEventBase() {
1191 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1192 << ", old evb=" << eventBase_ << ", state=" << state_
1193 << ", events=" << std::hex << eventFlags_ << ")";
1194 assert(eventBase_ != nullptr);
1195 assert(eventBase_->isInEventBaseThread());
1197 eventBase_ = nullptr;
1198 ioHandler_.detachEventBase();
1199 writeTimeout_.detachEventBase();
1201 evbChangeCb_->evbDetached(this);
1205 bool AsyncSocket::isDetachable() const {
1206 DCHECK(eventBase_ != nullptr);
1207 DCHECK(eventBase_->isInEventBaseThread());
1209 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1212 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1213 if (!localAddr_.isInitialized()) {
1214 localAddr_.setFromLocalAddress(fd_);
1216 *address = localAddr_;
1219 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1220 if (!addr_.isInitialized()) {
1221 addr_.setFromPeerAddress(fd_);
1226 bool AsyncSocket::getTFOSucceded() const {
1227 return detail::tfo_succeeded(fd_);
1230 int AsyncSocket::setNoDelay(bool noDelay) {
1232 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1233 << this << "(state=" << state_ << ")";
1238 int value = noDelay ? 1 : 0;
1239 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1240 int errnoCopy = errno;
1241 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1242 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1243 << strerror(errnoCopy);
1250 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1252 #ifndef TCP_CONGESTION
1253 #define TCP_CONGESTION 13
1257 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1258 << "socket " << this << "(state=" << state_ << ")";
1268 socklen_t(cname.length() + 1)) != 0) {
1269 int errnoCopy = errno;
1270 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1271 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1272 << strerror(errnoCopy);
1279 int AsyncSocket::setQuickAck(bool quickack) {
1281 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1282 << this << "(state=" << state_ << ")";
1287 #ifdef TCP_QUICKACK // Linux-only
1288 int value = quickack ? 1 : 0;
1289 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1290 int errnoCopy = errno;
1291 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1292 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1293 << strerror(errnoCopy);
1303 int AsyncSocket::setSendBufSize(size_t bufsize) {
1305 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1306 << this << "(state=" << state_ << ")";
1310 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1311 int errnoCopy = errno;
1312 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1313 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1314 << strerror(errnoCopy);
1321 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1323 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1324 << this << "(state=" << state_ << ")";
1328 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1329 int errnoCopy = errno;
1330 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1331 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1332 << strerror(errnoCopy);
1339 int AsyncSocket::setTCPProfile(int profd) {
1341 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1342 << this << "(state=" << state_ << ")";
1346 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1347 int errnoCopy = errno;
1348 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1349 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1350 << strerror(errnoCopy);
1357 void AsyncSocket::ioReady(uint16_t events) noexcept {
1358 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd" << fd_
1359 << ", events=" << std::hex << events << ", state=" << state_;
1360 DestructorGuard dg(this);
1361 assert(events & EventHandler::READ_WRITE);
1362 assert(eventBase_->isInEventBaseThread());
1364 uint16_t relevantEvents = uint16_t(events & EventHandler::READ_WRITE);
1365 EventBase* originalEventBase = eventBase_;
1366 // If we got there it means that either EventHandler::READ or
1367 // EventHandler::WRITE is set. Any of these flags can
1368 // indicate that there are messages available in the socket
1369 // error message queue.
1370 handleErrMessages();
1372 // Return now if handleErrMessages() detached us from our EventBase
1373 if (eventBase_ != originalEventBase) {
1377 if (relevantEvents == EventHandler::READ) {
1379 } else if (relevantEvents == EventHandler::WRITE) {
1381 } else if (relevantEvents == EventHandler::READ_WRITE) {
1382 // If both read and write events are ready, process writes first.
1385 // Return now if handleWrite() detached us from our EventBase
1386 if (eventBase_ != originalEventBase) {
1390 // Only call handleRead() if a read callback is still installed.
1391 // (It's possible that the read callback was uninstalled during
1393 if (readCallback_) {
1397 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1398 << std::hex << events << "(this=" << this << ")";
1403 AsyncSocket::ReadResult
1404 AsyncSocket::performRead(void** buf, size_t* buflen, size_t* /* offset */) {
1405 VLOG(5) << "AsyncSocket::performRead() this=" << this << ", buf=" << *buf
1406 << ", buflen=" << *buflen;
1410 recvFlags |= MSG_PEEK;
1413 ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT | recvFlags);
1415 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1416 // No more data to read right now.
1417 return ReadResult(READ_BLOCKING);
1419 return ReadResult(READ_ERROR);
1422 appBytesReceived_ += bytes;
1423 return ReadResult(bytes);
1427 void AsyncSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1428 // no matter what, buffer should be preapared for non-ssl socket
1429 CHECK(readCallback_);
1430 readCallback_->getReadBuffer(buf, buflen);
1433 void AsyncSocket::handleErrMessages() noexcept {
1434 // This method has non-empty implementation only for platforms
1435 // supporting per-socket error queues.
1436 VLOG(5) << "AsyncSocket::handleErrMessages() this=" << this << ", fd=" << fd_
1437 << ", state=" << state_;
1438 if (errMessageCallback_ == nullptr) {
1439 VLOG(7) << "AsyncSocket::handleErrMessages(): "
1440 << "no callback installed - exiting.";
1450 entry.iov_base = &data;
1451 entry.iov_len = sizeof(data);
1452 msg.msg_iov = &entry;
1454 msg.msg_name = nullptr;
1455 msg.msg_namelen = 0;
1456 msg.msg_control = ctrl;
1457 msg.msg_controllen = sizeof(ctrl);
1462 ret = recvmsg(fd_, &msg, MSG_ERRQUEUE);
1463 VLOG(5) << "AsyncSocket::handleErrMessages(): recvmsg returned " << ret;
1466 if (errno != EAGAIN) {
1467 auto errnoCopy = errno;
1468 LOG(ERROR) << "::recvmsg exited with code " << ret
1469 << ", errno: " << errnoCopy;
1470 AsyncSocketException ex(
1471 AsyncSocketException::INTERNAL_ERROR,
1472 withAddr("recvmsg() failed"),
1474 failErrMessageRead(__func__, ex);
1479 for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
1480 cmsg != nullptr && cmsg->cmsg_len != 0;
1481 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1482 errMessageCallback_->errMessage(*cmsg);
1485 #endif //MSG_ERRQUEUE
1488 void AsyncSocket::handleRead() noexcept {
1489 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1490 << ", state=" << state_;
1491 assert(state_ == StateEnum::ESTABLISHED);
1492 assert((shutdownFlags_ & SHUT_READ) == 0);
1493 assert(readCallback_ != nullptr);
1494 assert(eventFlags_ & EventHandler::READ);
1497 // - a read attempt would block
1498 // - readCallback_ is uninstalled
1499 // - the number of loop iterations exceeds the optional maximum
1500 // - this AsyncSocket is moved to another EventBase
1502 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1503 // which is why need to check for it here.
1505 // The last bullet point is slightly subtle. readDataAvailable() may also
1506 // detach this socket from this EventBase. However, before
1507 // readDataAvailable() returns another thread may pick it up, attach it to
1508 // a different EventBase, and install another readCallback_. We need to
1509 // exit immediately after readDataAvailable() returns if the eventBase_ has
1510 // changed. (The caller must perform some sort of locking to transfer the
1511 // AsyncSocket between threads properly. This will be sufficient to ensure
1512 // that this thread sees the updated eventBase_ variable after
1513 // readDataAvailable() returns.)
1514 uint16_t numReads = 0;
1515 EventBase* originalEventBase = eventBase_;
1516 while (readCallback_ && eventBase_ == originalEventBase) {
1517 // Get the buffer to read into.
1518 void* buf = nullptr;
1519 size_t buflen = 0, offset = 0;
1521 prepareReadBuffer(&buf, &buflen);
1522 VLOG(5) << "prepareReadBuffer() buf=" << buf << ", buflen=" << buflen;
1523 } catch (const AsyncSocketException& ex) {
1524 return failRead(__func__, ex);
1525 } catch (const std::exception& ex) {
1526 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1527 string("ReadCallback::getReadBuffer() "
1528 "threw exception: ") +
1530 return failRead(__func__, tex);
1532 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1533 "ReadCallback::getReadBuffer() threw "
1534 "non-exception type");
1535 return failRead(__func__, ex);
1537 if (!isBufferMovable_ && (buf == nullptr || buflen == 0)) {
1538 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1539 "ReadCallback::getReadBuffer() returned "
1541 return failRead(__func__, ex);
1545 auto readResult = performRead(&buf, &buflen, &offset);
1546 auto bytesRead = readResult.readReturn;
1547 VLOG(4) << "this=" << this << ", AsyncSocket::handleRead() got "
1548 << bytesRead << " bytes";
1549 if (bytesRead > 0) {
1550 if (!isBufferMovable_) {
1551 readCallback_->readDataAvailable(size_t(bytesRead));
1553 CHECK(kOpenSslModeMoveBufferOwnership);
1554 VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
1555 << "buf=" << buf << ", " << bytesRead << "/" << buflen
1556 << ", offset=" << offset;
1557 auto readBuf = folly::IOBuf::takeOwnership(buf, buflen);
1558 readBuf->trimStart(offset);
1559 readBuf->trimEnd(buflen - offset - bytesRead);
1560 readCallback_->readBufferAvailable(std::move(readBuf));
1563 // Fall through and continue around the loop if the read
1564 // completely filled the available buffer.
1565 // Note that readCallback_ may have been uninstalled or changed inside
1566 // readDataAvailable().
1567 if (size_t(bytesRead) < buflen) {
1570 } else if (bytesRead == READ_BLOCKING) {
1571 // No more data to read right now.
1573 } else if (bytesRead == READ_ERROR) {
1574 readErr_ = READ_ERROR;
1575 if (readResult.exception) {
1576 return failRead(__func__, *readResult.exception);
1578 auto errnoCopy = errno;
1579 AsyncSocketException ex(
1580 AsyncSocketException::INTERNAL_ERROR,
1581 withAddr("recv() failed"),
1583 return failRead(__func__, ex);
1585 assert(bytesRead == READ_EOF);
1586 readErr_ = READ_EOF;
1588 shutdownFlags_ |= SHUT_READ;
1589 if (!updateEventRegistration(0, EventHandler::READ)) {
1590 // we've already been moved into STATE_ERROR
1591 assert(state_ == StateEnum::ERROR);
1592 assert(readCallback_ == nullptr);
1596 ReadCallback* callback = readCallback_;
1597 readCallback_ = nullptr;
1598 callback->readEOF();
1601 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1602 if (readCallback_ != nullptr) {
1603 // We might still have data in the socket.
1604 // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
1605 scheduleImmediateRead();
1613 * This function attempts to write as much data as possible, until no more data
1616 * - If it sends all available data, it unregisters for write events, and stops
1617 * the writeTimeout_.
1619 * - If not all of the data can be sent immediately, it reschedules
1620 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1621 * registered for write events.
1623 void AsyncSocket::handleWrite() noexcept {
1624 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1625 << ", state=" << state_;
1626 DestructorGuard dg(this);
1628 if (state_ == StateEnum::CONNECTING) {
1634 assert(state_ == StateEnum::ESTABLISHED);
1635 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1636 assert(writeReqHead_ != nullptr);
1638 // Loop until we run out of write requests,
1639 // or until this socket is moved to another EventBase.
1640 // (See the comment in handleRead() explaining how this can happen.)
1641 EventBase* originalEventBase = eventBase_;
1642 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1643 auto writeResult = writeReqHead_->performWrite();
1644 if (writeResult.writeReturn < 0) {
1645 if (writeResult.exception) {
1646 return failWrite(__func__, *writeResult.exception);
1648 auto errnoCopy = errno;
1649 AsyncSocketException ex(
1650 AsyncSocketException::INTERNAL_ERROR,
1651 withAddr("writev() failed"),
1653 return failWrite(__func__, ex);
1654 } else if (writeReqHead_->isComplete()) {
1655 // We finished this request
1656 WriteRequest* req = writeReqHead_;
1657 writeReqHead_ = req->getNext();
1659 if (writeReqHead_ == nullptr) {
1660 writeReqTail_ = nullptr;
1661 // This is the last write request.
1662 // Unregister for write events and cancel the send timer
1663 // before we invoke the callback. We have to update the state properly
1664 // before calling the callback, since it may want to detach us from
1666 if (eventFlags_ & EventHandler::WRITE) {
1667 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1668 assert(state_ == StateEnum::ERROR);
1671 // Stop the send timeout
1672 writeTimeout_.cancelTimeout();
1674 assert(!writeTimeout_.isScheduled());
1676 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
1677 // we finish sending the last write request.
1679 // We have to do this before invoking writeSuccess(), since
1680 // writeSuccess() may detach us from our EventBase.
1681 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
1682 assert(connectCallback_ == nullptr);
1683 shutdownFlags_ |= SHUT_WRITE;
1685 if (shutdownFlags_ & SHUT_READ) {
1686 // Reads have already been shutdown. Fully close the socket and
1687 // move to STATE_CLOSED.
1689 // Note: This code currently moves us to STATE_CLOSED even if
1690 // close() hasn't ever been called. This can occur if we have
1691 // received EOF from the peer and shutdownWrite() has been called
1692 // locally. Should we bother staying in STATE_ESTABLISHED in this
1693 // case, until close() is actually called? I can't think of a
1694 // reason why we would need to do so. No other operations besides
1695 // calling close() or destroying the socket can be performed at
1697 assert(readCallback_ == nullptr);
1698 state_ = StateEnum::CLOSED;
1700 ioHandler_.changeHandlerFD(-1);
1704 // Reads are still enabled, so we are only doing a half-shutdown
1705 shutdown(fd_, SHUT_WR);
1710 // Invoke the callback
1711 WriteCallback* callback = req->getCallback();
1714 callback->writeSuccess();
1716 // We'll continue around the loop, trying to write another request
1719 if (bufferCallback_) {
1720 bufferCallback_->onEgressBuffered();
1722 writeReqHead_->consume();
1723 // Stop after a partial write; it's highly likely that a subsequent write
1724 // attempt will just return EAGAIN.
1726 // Ensure that we are registered for write events.
1727 if ((eventFlags_ & EventHandler::WRITE) == 0) {
1728 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1729 assert(state_ == StateEnum::ERROR);
1734 // Reschedule the send timeout, since we have made some write progress.
1735 if (sendTimeout_ > 0) {
1736 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1737 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1738 withAddr("failed to reschedule write timeout"));
1739 return failWrite(__func__, ex);
1745 if (!writeReqHead_ && bufferCallback_) {
1746 bufferCallback_->onEgressBufferCleared();
1750 void AsyncSocket::checkForImmediateRead() noexcept {
1751 // We currently don't attempt to perform optimistic reads in AsyncSocket.
1752 // (However, note that some subclasses do override this method.)
1754 // Simply calling handleRead() here would be bad, as this would call
1755 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
1756 // buffer even though no data may be available. This would waste lots of
1757 // memory, since the buffer will sit around unused until the socket actually
1758 // becomes readable.
1760 // Checking if the socket is readable now also seems like it would probably
1761 // be a pessimism. In most cases it probably wouldn't be readable, and we
1762 // would just waste an extra system call. Even if it is readable, waiting to
1763 // find out from libevent on the next event loop doesn't seem that bad.
1766 void AsyncSocket::handleInitialReadWrite() noexcept {
1767 // Our callers should already be holding a DestructorGuard, but grab
1768 // one here just to make sure, in case one of our calling code paths ever
1770 DestructorGuard dg(this);
1771 // If we have a readCallback_, make sure we enable read events. We
1772 // may already be registered for reads if connectSuccess() set
1773 // the read calback.
1774 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
1775 assert(state_ == StateEnum::ESTABLISHED);
1776 assert((shutdownFlags_ & SHUT_READ) == 0);
1777 if (!updateEventRegistration(EventHandler::READ, 0)) {
1778 assert(state_ == StateEnum::ERROR);
1781 checkForImmediateRead();
1782 } else if (readCallback_ == nullptr) {
1783 // Unregister for read events.
1784 updateEventRegistration(0, EventHandler::READ);
1787 // If we have write requests pending, try to send them immediately.
1788 // Since we just finished accepting, there is a very good chance that we can
1789 // write without blocking.
1791 // However, we only process them if EventHandler::WRITE is not already set,
1792 // which means that we're already blocked on a write attempt. (This can
1793 // happen if connectSuccess() called write() before returning.)
1794 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
1795 // Call handleWrite() to perform write processing.
1797 } else if (writeReqHead_ == nullptr) {
1798 // Unregister for write event.
1799 updateEventRegistration(0, EventHandler::WRITE);
1803 void AsyncSocket::handleConnect() noexcept {
1804 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
1805 << ", state=" << state_;
1806 assert(state_ == StateEnum::CONNECTING);
1807 // SHUT_WRITE can never be set while we are still connecting;
1808 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
1810 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1812 // In case we had a connect timeout, cancel the timeout
1813 writeTimeout_.cancelTimeout();
1814 // We don't use a persistent registration when waiting on a connect event,
1815 // so we have been automatically unregistered now. Update eventFlags_ to
1817 assert(eventFlags_ == EventHandler::WRITE);
1818 eventFlags_ = EventHandler::NONE;
1820 // Call getsockopt() to check if the connect succeeded
1822 socklen_t len = sizeof(error);
1823 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
1825 auto errnoCopy = errno;
1826 AsyncSocketException ex(
1827 AsyncSocketException::INTERNAL_ERROR,
1828 withAddr("error calling getsockopt() after connect"),
1830 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1831 << fd_ << " host=" << addr_.describe()
1832 << ") exception:" << ex.what();
1833 return failConnect(__func__, ex);
1837 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1838 "connect failed", error);
1839 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1840 << fd_ << " host=" << addr_.describe()
1841 << ") exception: " << ex.what();
1842 return failConnect(__func__, ex);
1845 // Move into STATE_ESTABLISHED
1846 state_ = StateEnum::ESTABLISHED;
1848 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
1849 // perform, immediately shutdown the write half of the socket.
1850 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
1851 // SHUT_READ shouldn't be set. If close() is called on the socket while we
1852 // are still connecting we just abort the connect rather than waiting for
1854 assert((shutdownFlags_ & SHUT_READ) == 0);
1855 shutdown(fd_, SHUT_WR);
1856 shutdownFlags_ |= SHUT_WRITE;
1859 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
1860 << "successfully connected; state=" << state_;
1862 // Remember the EventBase we are attached to, before we start invoking any
1863 // callbacks (since the callbacks may call detachEventBase()).
1864 EventBase* originalEventBase = eventBase_;
1866 invokeConnectSuccess();
1867 // Note that the connect callback may have changed our state.
1868 // (set or unset the read callback, called write(), closed the socket, etc.)
1869 // The following code needs to handle these situations correctly.
1871 // If the socket has been closed, readCallback_ and writeReqHead_ will
1872 // always be nullptr, so that will prevent us from trying to read or write.
1874 // The main thing to check for is if eventBase_ is still originalEventBase.
1875 // If not, we have been detached from this event base, so we shouldn't
1876 // perform any more operations.
1877 if (eventBase_ != originalEventBase) {
1881 handleInitialReadWrite();
1884 void AsyncSocket::timeoutExpired() noexcept {
1885 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
1886 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
1887 DestructorGuard dg(this);
1888 assert(eventBase_->isInEventBaseThread());
1890 if (state_ == StateEnum::CONNECTING) {
1891 // connect() timed out
1892 // Unregister for I/O events.
1893 if (connectCallback_) {
1894 AsyncSocketException ex(
1895 AsyncSocketException::TIMED_OUT,
1897 "connect timed out after {}ms", connectTimeout_.count()));
1898 failConnect(__func__, ex);
1900 // we faced a connect error without a connect callback, which could
1901 // happen due to TFO.
1902 AsyncSocketException ex(
1903 AsyncSocketException::TIMED_OUT, "write timed out during connection");
1904 failWrite(__func__, ex);
1907 // a normal write operation timed out
1908 AsyncSocketException ex(
1909 AsyncSocketException::TIMED_OUT,
1910 folly::sformat("write timed out after {}ms", sendTimeout_));
1911 failWrite(__func__, ex);
1915 ssize_t AsyncSocket::tfoSendMsg(int fd, struct msghdr* msg, int msg_flags) {
1916 return detail::tfo_sendmsg(fd, msg, msg_flags);
1919 AsyncSocket::WriteResult
1920 AsyncSocket::sendSocketMessage(int fd, struct msghdr* msg, int msg_flags) {
1921 ssize_t totalWritten = 0;
1922 if (state_ == StateEnum::FAST_OPEN) {
1923 sockaddr_storage addr;
1924 auto len = addr_.getAddress(&addr);
1925 msg->msg_name = &addr;
1926 msg->msg_namelen = len;
1927 totalWritten = tfoSendMsg(fd_, msg, msg_flags);
1928 if (totalWritten >= 0) {
1929 tfoFinished_ = true;
1930 state_ = StateEnum::ESTABLISHED;
1931 // We schedule this asynchrously so that we don't end up
1932 // invoking initial read or write while a write is in progress.
1933 scheduleInitialReadWrite();
1934 } else if (errno == EINPROGRESS) {
1935 VLOG(4) << "TFO falling back to connecting";
1936 // A normal sendmsg doesn't return EINPROGRESS, however
1937 // TFO might fallback to connecting if there is no
1939 state_ = StateEnum::CONNECTING;
1941 scheduleConnectTimeout();
1942 registerForConnectEvents();
1943 } catch (const AsyncSocketException& ex) {
1945 WRITE_ERROR, folly::make_unique<AsyncSocketException>(ex));
1947 // Let's fake it that no bytes were written and return an errno.
1950 } else if (errno == EOPNOTSUPP) {
1951 // Try falling back to connecting.
1952 VLOG(4) << "TFO not supported";
1953 state_ = StateEnum::CONNECTING;
1955 int ret = socketConnect((const sockaddr*)&addr, len);
1957 // connect succeeded immediately
1958 // Treat this like no data was written.
1959 state_ = StateEnum::ESTABLISHED;
1960 scheduleInitialReadWrite();
1962 // If there was no exception during connections,
1963 // we would return that no bytes were written.
1966 } catch (const AsyncSocketException& ex) {
1968 WRITE_ERROR, folly::make_unique<AsyncSocketException>(ex));
1970 } else if (errno == EAGAIN) {
1971 // Normally sendmsg would indicate that the write would block.
1972 // However in the fast open case, it would indicate that sendmsg
1973 // fell back to a connect. This is a return code from connect()
1974 // instead, and is an error condition indicating no fds available.
1977 folly::make_unique<AsyncSocketException>(
1978 AsyncSocketException::UNKNOWN, "No more free local ports"));
1981 totalWritten = ::sendmsg(fd, msg, msg_flags);
1983 return WriteResult(totalWritten);
1986 AsyncSocket::WriteResult AsyncSocket::performWrite(
1990 uint32_t* countWritten,
1991 uint32_t* partialWritten) {
1992 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
1993 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
1994 // (since it may terminate the program if the main program doesn't explicitly
1997 msg.msg_name = nullptr;
1998 msg.msg_namelen = 0;
1999 msg.msg_iov = const_cast<iovec *>(vec);
2000 msg.msg_iovlen = std::min<size_t>(count, kIovMax);
2001 msg.msg_control = nullptr;
2002 msg.msg_controllen = 0;
2005 int msg_flags = MSG_DONTWAIT;
2007 #ifdef MSG_NOSIGNAL // Linux-only
2008 msg_flags |= MSG_NOSIGNAL;
2009 if (isSet(flags, WriteFlags::CORK)) {
2010 // MSG_MORE tells the kernel we have more data to send, so wait for us to
2011 // give it the rest of the data rather than immediately sending a partial
2012 // frame, even when TCP_NODELAY is enabled.
2013 msg_flags |= MSG_MORE;
2016 if (isSet(flags, WriteFlags::EOR)) {
2017 // marks that this is the last byte of a record (response)
2018 msg_flags |= MSG_EOR;
2020 auto writeResult = sendSocketMessage(fd_, &msg, msg_flags);
2021 auto totalWritten = writeResult.writeReturn;
2022 if (totalWritten < 0) {
2023 bool tryAgain = (errno == EAGAIN);
2025 // Apple has a bug where doing a second write on a socket which we
2026 // have opened with TFO causes an ENOTCONN to be thrown. However the
2027 // socket is really connected, so treat ENOTCONN as a EAGAIN until
2028 // this bug is fixed.
2029 tryAgain |= (errno == ENOTCONN);
2031 if (!writeResult.exception && tryAgain) {
2032 // TCP buffer is full; we can't write any more data right now.
2034 *partialWritten = 0;
2035 return WriteResult(0);
2039 *partialWritten = 0;
2043 appBytesWritten_ += totalWritten;
2045 uint32_t bytesWritten;
2047 for (bytesWritten = uint32_t(totalWritten), n = 0; n < count; ++n) {
2048 const iovec* v = vec + n;
2049 if (v->iov_len > bytesWritten) {
2050 // Partial write finished in the middle of this iovec
2052 *partialWritten = bytesWritten;
2053 return WriteResult(totalWritten);
2056 bytesWritten -= uint32_t(v->iov_len);
2059 assert(bytesWritten == 0);
2061 *partialWritten = 0;
2062 return WriteResult(totalWritten);
2066 * Re-register the EventHandler after eventFlags_ has changed.
2068 * If an error occurs, fail() is called to move the socket into the error state
2069 * and call all currently installed callbacks. After an error, the
2070 * AsyncSocket is completely unregistered.
2072 * @return Returns true on succcess, or false on error.
2074 bool AsyncSocket::updateEventRegistration() {
2075 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
2076 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
2077 << ", events=" << std::hex << eventFlags_;
2078 assert(eventBase_->isInEventBaseThread());
2079 if (eventFlags_ == EventHandler::NONE) {
2080 ioHandler_.unregisterHandler();
2084 // Always register for persistent events, so we don't have to re-register
2085 // after being called back.
2086 if (!ioHandler_.registerHandler(
2087 uint16_t(eventFlags_ | EventHandler::PERSIST))) {
2088 eventFlags_ = EventHandler::NONE; // we're not registered after error
2089 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
2090 withAddr("failed to update AsyncSocket event registration"));
2091 fail("updateEventRegistration", ex);
2098 bool AsyncSocket::updateEventRegistration(uint16_t enable,
2100 uint16_t oldFlags = eventFlags_;
2101 eventFlags_ |= enable;
2102 eventFlags_ &= ~disable;
2103 if (eventFlags_ == oldFlags) {
2106 return updateEventRegistration();
2110 void AsyncSocket::startFail() {
2111 // startFail() should only be called once
2112 assert(state_ != StateEnum::ERROR);
2113 assert(getDestructorGuardCount() > 0);
2114 state_ = StateEnum::ERROR;
2115 // Ensure that SHUT_READ and SHUT_WRITE are set,
2116 // so all future attempts to read or write will be rejected
2117 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
2119 if (eventFlags_ != EventHandler::NONE) {
2120 eventFlags_ = EventHandler::NONE;
2121 ioHandler_.unregisterHandler();
2123 writeTimeout_.cancelTimeout();
2126 ioHandler_.changeHandlerFD(-1);
2131 void AsyncSocket::invokeAllErrors(const AsyncSocketException& ex) {
2132 invokeConnectErr(ex);
2135 if (readCallback_) {
2136 ReadCallback* callback = readCallback_;
2137 readCallback_ = nullptr;
2138 callback->readErr(ex);
2142 void AsyncSocket::finishFail() {
2143 assert(state_ == StateEnum::ERROR);
2144 assert(getDestructorGuardCount() > 0);
2146 AsyncSocketException ex(
2147 AsyncSocketException::INTERNAL_ERROR,
2148 withAddr("socket closing after error"));
2149 invokeAllErrors(ex);
2152 void AsyncSocket::finishFail(const AsyncSocketException& ex) {
2153 assert(state_ == StateEnum::ERROR);
2154 assert(getDestructorGuardCount() > 0);
2155 invokeAllErrors(ex);
2158 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
2159 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2160 << state_ << " host=" << addr_.describe()
2161 << "): failed in " << fn << "(): "
2167 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
2168 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2169 << state_ << " host=" << addr_.describe()
2170 << "): failed while connecting in " << fn << "(): "
2174 invokeConnectErr(ex);
2178 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
2179 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2180 << state_ << " host=" << addr_.describe()
2181 << "): failed while reading in " << fn << "(): "
2185 if (readCallback_ != nullptr) {
2186 ReadCallback* callback = readCallback_;
2187 readCallback_ = nullptr;
2188 callback->readErr(ex);
2194 void AsyncSocket::failErrMessageRead(const char* fn,
2195 const AsyncSocketException& ex) {
2196 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2197 << state_ << " host=" << addr_.describe()
2198 << "): failed while reading message in " << fn << "(): "
2202 if (errMessageCallback_ != nullptr) {
2203 ErrMessageCallback* callback = errMessageCallback_;
2204 errMessageCallback_ = nullptr;
2205 callback->errMessageError(ex);
2211 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
2212 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2213 << state_ << " host=" << addr_.describe()
2214 << "): failed while writing in " << fn << "(): "
2218 // Only invoke the first write callback, since the error occurred while
2219 // writing this request. Let any other pending write callbacks be invoked in
2221 if (writeReqHead_ != nullptr) {
2222 WriteRequest* req = writeReqHead_;
2223 writeReqHead_ = req->getNext();
2224 WriteCallback* callback = req->getCallback();
2225 uint32_t bytesWritten = req->getTotalBytesWritten();
2228 callback->writeErr(bytesWritten, ex);
2235 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
2236 size_t bytesWritten,
2237 const AsyncSocketException& ex) {
2238 // This version of failWrite() is used when the failure occurs before
2239 // we've added the callback to writeReqHead_.
2240 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2241 << state_ << " host=" << addr_.describe()
2242 <<"): failed while writing in " << fn << "(): "
2246 if (callback != nullptr) {
2247 callback->writeErr(bytesWritten, ex);
2253 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
2254 // Invoke writeError() on all write callbacks.
2255 // This is used when writes are forcibly shutdown with write requests
2256 // pending, or when an error occurs with writes pending.
2257 while (writeReqHead_ != nullptr) {
2258 WriteRequest* req = writeReqHead_;
2259 writeReqHead_ = req->getNext();
2260 WriteCallback* callback = req->getCallback();
2262 callback->writeErr(req->getTotalBytesWritten(), ex);
2268 void AsyncSocket::invalidState(ConnectCallback* callback) {
2269 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2270 << "): connect() called in invalid state " << state_;
2273 * The invalidState() methods don't use the normal failure mechanisms,
2274 * since we don't know what state we are in. We don't want to call
2275 * startFail()/finishFail() recursively if we are already in the middle of
2279 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
2280 "connect() called with socket in invalid state");
2281 connectEndTime_ = std::chrono::steady_clock::now();
2282 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2284 callback->connectErr(ex);
2287 // We can't use failConnect() here since connectCallback_
2288 // may already be set to another callback. Invoke this ConnectCallback
2289 // here; any other connectCallback_ will be invoked in finishFail()
2292 callback->connectErr(ex);
2298 void AsyncSocket::invalidState(ErrMessageCallback* callback) {
2299 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2300 << "): setErrMessageCB(" << callback
2301 << ") called in invalid state " << state_;
2303 AsyncSocketException ex(
2304 AsyncSocketException::NOT_OPEN,
2305 msgErrQueueSupported
2306 ? "setErrMessageCB() called with socket in invalid state"
2307 : "This platform does not support socket error message notifications");
2308 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2310 callback->errMessageError(ex);
2315 callback->errMessageError(ex);
2321 void AsyncSocket::invokeConnectErr(const AsyncSocketException& ex) {
2322 connectEndTime_ = std::chrono::steady_clock::now();
2323 if (connectCallback_) {
2324 ConnectCallback* callback = connectCallback_;
2325 connectCallback_ = nullptr;
2326 callback->connectErr(ex);
2330 void AsyncSocket::invokeConnectSuccess() {
2331 connectEndTime_ = std::chrono::steady_clock::now();
2332 if (connectCallback_) {
2333 ConnectCallback* callback = connectCallback_;
2334 connectCallback_ = nullptr;
2335 callback->connectSuccess();
2339 void AsyncSocket::invalidState(ReadCallback* callback) {
2340 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2341 << "): setReadCallback(" << callback
2342 << ") called in invalid state " << state_;
2344 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2345 "setReadCallback() called with socket in "
2347 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2349 callback->readErr(ex);
2354 callback->readErr(ex);
2360 void AsyncSocket::invalidState(WriteCallback* callback) {
2361 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2362 << "): write() called in invalid state " << state_;
2364 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2365 withAddr("write() called with socket in invalid state"));
2366 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2368 callback->writeErr(0, ex);
2373 callback->writeErr(0, ex);
2379 void AsyncSocket::doClose() {
2380 if (fd_ == -1) return;
2381 if (shutdownSocketSet_) {
2382 shutdownSocketSet_->close(fd_);
2389 std::ostream& operator << (std::ostream& os,
2390 const AsyncSocket::StateEnum& state) {
2391 os << static_cast<int>(state);
2395 std::string AsyncSocket::withAddr(const std::string& s) {
2396 // Don't use addr_ directly because it may not be initialized
2397 // e.g. if constructed from fd
2398 folly::SocketAddress peer, local;
2400 getPeerAddress(&peer);
2401 getLocalAddress(&local);
2402 } catch (const std::exception&) {
2407 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";
2410 void AsyncSocket::setBufferCallback(BufferCallback* cb) {
2411 bufferCallback_ = cb;