2 * Copyright 2016 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>
31 #include <sys/types.h>
32 #include <boost/preprocessor/control/if.hpp>
35 using std::unique_ptr;
37 namespace fsp = folly::portability::sockets;
41 // static members initializers
42 const AsyncSocket::OptionMap AsyncSocket::emptyOptionMap;
44 const AsyncSocketException socketClosedLocallyEx(
45 AsyncSocketException::END_OF_FILE, "socket closed locally");
46 const AsyncSocketException socketShutdownForWritesEx(
47 AsyncSocketException::END_OF_FILE, "socket shutdown for writes");
49 // TODO: It might help performance to provide a version of BytesWriteRequest that
50 // users could derive from, so we can avoid the extra allocation for each call
51 // to write()/writev(). We could templatize TFramedAsyncChannel just like the
52 // protocols are currently templatized for transports.
54 // We would need the version for external users where they provide the iovec
55 // storage space, and only our internal version would allocate it at the end of
58 /* The default WriteRequest implementation, used for write(), writev() and
61 * A new BytesWriteRequest operation is allocated on the heap for all write
62 * operations that cannot be completed immediately.
64 class AsyncSocket::BytesWriteRequest : public AsyncSocket::WriteRequest {
66 static BytesWriteRequest* newRequest(AsyncSocket* socket,
67 WriteCallback* callback,
70 uint32_t partialWritten,
71 uint32_t bytesWritten,
72 unique_ptr<IOBuf>&& ioBuf,
75 // Since we put a variable size iovec array at the end
76 // of each BytesWriteRequest, we have to manually allocate the memory.
77 void* buf = malloc(sizeof(BytesWriteRequest) +
78 (opCount * sizeof(struct iovec)));
80 throw std::bad_alloc();
83 return new(buf) BytesWriteRequest(socket, callback, ops, opCount,
84 partialWritten, bytesWritten,
85 std::move(ioBuf), flags);
88 void destroy() override {
89 this->~BytesWriteRequest();
93 WriteResult performWrite() override {
94 WriteFlags writeFlags = flags_;
95 if (getNext() != nullptr) {
96 writeFlags = writeFlags | WriteFlags::CORK;
98 return socket_->performWrite(
99 getOps(), getOpCount(), writeFlags, &opsWritten_, &partialBytes_);
102 bool isComplete() override {
103 return opsWritten_ == getOpCount();
106 void consume() override {
107 // Advance opIndex_ forward by opsWritten_
108 opIndex_ += opsWritten_;
109 assert(opIndex_ < opCount_);
111 // If we've finished writing any IOBufs, release them
113 for (uint32_t i = opsWritten_; i != 0; --i) {
115 ioBuf_ = ioBuf_->pop();
119 // Move partialBytes_ forward into the current iovec buffer
120 struct iovec* currentOp = writeOps_ + opIndex_;
121 assert((partialBytes_ < currentOp->iov_len) || (currentOp->iov_len == 0));
122 currentOp->iov_base =
123 reinterpret_cast<uint8_t*>(currentOp->iov_base) + partialBytes_;
124 currentOp->iov_len -= partialBytes_;
126 // Increment the totalBytesWritten_ count by bytesWritten_;
127 totalBytesWritten_ += bytesWritten_;
131 BytesWriteRequest(AsyncSocket* socket,
132 WriteCallback* callback,
133 const struct iovec* ops,
135 uint32_t partialBytes,
136 uint32_t bytesWritten,
137 unique_ptr<IOBuf>&& ioBuf,
139 : AsyncSocket::WriteRequest(socket, callback)
143 , ioBuf_(std::move(ioBuf))
145 , partialBytes_(partialBytes)
146 , bytesWritten_(bytesWritten) {
147 memcpy(writeOps_, ops, sizeof(*ops) * opCount_);
150 // private destructor, to ensure callers use destroy()
151 ~BytesWriteRequest() override = default;
153 const struct iovec* getOps() const {
154 assert(opCount_ > opIndex_);
155 return writeOps_ + opIndex_;
158 uint32_t getOpCount() const {
159 assert(opCount_ > opIndex_);
160 return opCount_ - opIndex_;
163 uint32_t opCount_; ///< number of entries in writeOps_
164 uint32_t opIndex_; ///< current index into writeOps_
165 WriteFlags flags_; ///< set for WriteFlags
166 unique_ptr<IOBuf> ioBuf_; ///< underlying IOBuf, or nullptr if N/A
168 // for consume(), how much we wrote on the last write
169 uint32_t opsWritten_; ///< complete ops written
170 uint32_t partialBytes_; ///< partial bytes of incomplete op written
171 ssize_t bytesWritten_; ///< bytes written altogether
173 struct iovec writeOps_[]; ///< write operation(s) list
176 AsyncSocket::AsyncSocket()
177 : eventBase_(nullptr)
178 , writeTimeout_(this, nullptr)
179 , ioHandler_(this, nullptr)
180 , immediateReadHandler_(this) {
181 VLOG(5) << "new AsyncSocket()";
185 AsyncSocket::AsyncSocket(EventBase* evb)
187 , writeTimeout_(this, evb)
188 , ioHandler_(this, evb)
189 , immediateReadHandler_(this) {
190 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
194 AsyncSocket::AsyncSocket(EventBase* evb,
195 const folly::SocketAddress& address,
196 uint32_t connectTimeout)
198 connect(nullptr, address, connectTimeout);
201 AsyncSocket::AsyncSocket(EventBase* evb,
202 const std::string& ip,
204 uint32_t connectTimeout)
206 connect(nullptr, ip, port, connectTimeout);
209 AsyncSocket::AsyncSocket(EventBase* evb, int fd)
211 , writeTimeout_(this, evb)
212 , ioHandler_(this, evb, fd)
213 , immediateReadHandler_(this) {
214 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ", fd="
219 state_ = StateEnum::ESTABLISHED;
222 // init() method, since constructor forwarding isn't supported in most
224 void AsyncSocket::init() {
225 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
227 state_ = StateEnum::UNINIT;
228 eventFlags_ = EventHandler::NONE;
231 maxReadsPerEvent_ = 16;
232 connectCallback_ = nullptr;
233 readCallback_ = nullptr;
234 writeReqHead_ = nullptr;
235 writeReqTail_ = nullptr;
236 shutdownSocketSet_ = nullptr;
237 appBytesWritten_ = 0;
238 appBytesReceived_ = 0;
241 AsyncSocket::~AsyncSocket() {
242 VLOG(7) << "actual destruction of AsyncSocket(this=" << this
243 << ", evb=" << eventBase_ << ", fd=" << fd_
244 << ", state=" << state_ << ")";
247 void AsyncSocket::destroy() {
248 VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
249 << ", fd=" << fd_ << ", state=" << state_;
250 // When destroy is called, close the socket immediately
253 // Then call DelayedDestruction::destroy() to take care of
254 // whether or not we need immediate or delayed destruction
255 DelayedDestruction::destroy();
258 int AsyncSocket::detachFd() {
259 VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
260 << ", evb=" << eventBase_ << ", state=" << state_
261 << ", events=" << std::hex << eventFlags_ << ")";
262 // Extract the fd, and set fd_ to -1 first, so closeNow() won't
263 // actually close the descriptor.
264 if (shutdownSocketSet_) {
265 shutdownSocketSet_->remove(fd_);
269 // Call closeNow() to invoke all pending callbacks with an error.
271 // Update the EventHandler to stop using this fd.
272 // This can only be done after closeNow() unregisters the handler.
273 ioHandler_.changeHandlerFD(-1);
277 const folly::SocketAddress& AsyncSocket::anyAddress() {
278 static const folly::SocketAddress anyAddress =
279 folly::SocketAddress("0.0.0.0", 0);
283 void AsyncSocket::setShutdownSocketSet(ShutdownSocketSet* newSS) {
284 if (shutdownSocketSet_ == newSS) {
287 if (shutdownSocketSet_ && fd_ != -1) {
288 shutdownSocketSet_->remove(fd_);
290 shutdownSocketSet_ = newSS;
291 if (shutdownSocketSet_ && fd_ != -1) {
292 shutdownSocketSet_->add(fd_);
296 void AsyncSocket::setCloseOnExec() {
297 int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
299 auto errnoCopy = errno;
300 throw AsyncSocketException(
301 AsyncSocketException::INTERNAL_ERROR,
302 withAddr("failed to set close-on-exec flag"),
307 void AsyncSocket::connect(ConnectCallback* callback,
308 const folly::SocketAddress& address,
310 const OptionMap &options,
311 const folly::SocketAddress& bindAddr) noexcept {
312 DestructorGuard dg(this);
313 assert(eventBase_->isInEventBaseThread());
317 // Make sure we're in the uninitialized state
318 if (state_ != StateEnum::UNINIT) {
319 return invalidState(callback);
322 connectTimeout_ = std::chrono::milliseconds(timeout);
323 connectStartTime_ = std::chrono::steady_clock::now();
324 // Make connect end time at least >= connectStartTime.
325 connectEndTime_ = connectStartTime_;
328 state_ = StateEnum::CONNECTING;
329 connectCallback_ = callback;
331 sockaddr_storage addrStorage;
332 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
336 // Technically the first parameter should actually be a protocol family
337 // constant (PF_xxx) rather than an address family (AF_xxx), but the
338 // distinction is mainly just historical. In pretty much all
339 // implementations the PF_foo and AF_foo constants are identical.
340 fd_ = fsp::socket(address.getFamily(), SOCK_STREAM, 0);
342 auto errnoCopy = errno;
343 throw AsyncSocketException(
344 AsyncSocketException::INTERNAL_ERROR,
345 withAddr("failed to create socket"),
348 if (shutdownSocketSet_) {
349 shutdownSocketSet_->add(fd_);
351 ioHandler_.changeHandlerFD(fd_);
355 // Put the socket in non-blocking mode
356 int flags = fcntl(fd_, F_GETFL, 0);
358 auto errnoCopy = errno;
359 throw AsyncSocketException(
360 AsyncSocketException::INTERNAL_ERROR,
361 withAddr("failed to get socket flags"),
364 int rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
366 auto errnoCopy = errno;
367 throw AsyncSocketException(
368 AsyncSocketException::INTERNAL_ERROR,
369 withAddr("failed to put socket in non-blocking mode"),
373 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
374 // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
375 rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
377 auto errnoCopy = errno;
378 throw AsyncSocketException(
379 AsyncSocketException::INTERNAL_ERROR,
380 "failed to enable F_SETNOSIGPIPE on socket",
385 // By default, turn on TCP_NODELAY
386 // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
387 // setNoDelay() will log an error message if it fails.
388 if (address.getFamily() != AF_UNIX) {
389 (void)setNoDelay(true);
392 VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
393 << ", fd=" << fd_ << ", host=" << address.describe().c_str();
396 if (bindAddr != anyAddress()) {
398 if (setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
399 auto errnoCopy = errno;
401 throw AsyncSocketException(
402 AsyncSocketException::NOT_OPEN,
403 "failed to setsockopt prior to bind on " + bindAddr.describe(),
407 bindAddr.getAddress(&addrStorage);
409 if (bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
410 auto errnoCopy = errno;
412 throw AsyncSocketException(
413 AsyncSocketException::NOT_OPEN,
414 "failed to bind to async socket: " + bindAddr.describe(),
419 // Apply the additional options if any.
420 for (const auto& opt: options) {
421 int rv = opt.first.apply(fd_, opt.second);
423 auto errnoCopy = errno;
424 throw AsyncSocketException(
425 AsyncSocketException::INTERNAL_ERROR,
426 withAddr("failed to set socket option"),
431 // Perform the connect()
432 address.getAddress(&addrStorage);
435 state_ = StateEnum::FAST_OPEN;
436 tfoAttempted_ = true;
438 if (socketConnect(saddr, addr_.getActualSize()) < 0) {
443 // If we're still here the connect() succeeded immediately.
444 // Fall through to call the callback outside of this try...catch block
445 } catch (const AsyncSocketException& ex) {
446 return failConnect(__func__, ex);
447 } catch (const std::exception& ex) {
448 // shouldn't happen, but handle it just in case
449 VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
450 << "): unexpected " << typeid(ex).name() << " exception: "
452 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
453 withAddr(string("unexpected exception: ") +
455 return failConnect(__func__, tex);
458 // The connection succeeded immediately
459 // The read callback may not have been set yet, and no writes may be pending
460 // yet, so we don't have to register for any events at the moment.
461 VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
462 assert(readCallback_ == nullptr);
463 assert(writeReqHead_ == nullptr);
464 if (state_ != StateEnum::FAST_OPEN) {
465 state_ = StateEnum::ESTABLISHED;
467 invokeConnectSuccess();
470 int AsyncSocket::socketConnect(const struct sockaddr* saddr, socklen_t len) {
471 int rv = ::connect(fd_, saddr, len);
473 auto errnoCopy = errno;
474 if (errnoCopy == EINPROGRESS) {
475 scheduleConnectTimeoutAndRegisterForEvents();
477 throw AsyncSocketException(
478 AsyncSocketException::NOT_OPEN,
479 "connect failed (immediately)",
486 void AsyncSocket::scheduleConnectTimeoutAndRegisterForEvents() {
487 // Connection in progress.
488 int timeout = connectTimeout_.count();
490 // Start a timer in case the connection takes too long.
491 if (!writeTimeout_.scheduleTimeout(timeout)) {
492 throw AsyncSocketException(
493 AsyncSocketException::INTERNAL_ERROR,
494 withAddr("failed to schedule AsyncSocket connect timeout"));
498 // Register for write events, so we'll
499 // be notified when the connection finishes/fails.
500 // Note that we don't register for a persistent event here.
501 assert(eventFlags_ == EventHandler::NONE);
502 eventFlags_ = EventHandler::WRITE;
503 if (!ioHandler_.registerHandler(eventFlags_)) {
504 throw AsyncSocketException(
505 AsyncSocketException::INTERNAL_ERROR,
506 withAddr("failed to register AsyncSocket connect handler"));
510 void AsyncSocket::connect(ConnectCallback* callback,
511 const string& ip, uint16_t port,
513 const OptionMap &options) noexcept {
514 DestructorGuard dg(this);
516 connectCallback_ = callback;
517 connect(callback, folly::SocketAddress(ip, port), timeout, options);
518 } catch (const std::exception& ex) {
519 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
521 return failConnect(__func__, tex);
525 void AsyncSocket::cancelConnect() {
526 connectCallback_ = nullptr;
527 if (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN) {
532 void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
533 sendTimeout_ = milliseconds;
534 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
536 // If we are currently pending on write requests, immediately update
537 // writeTimeout_ with the new value.
538 if ((eventFlags_ & EventHandler::WRITE) &&
539 (state_ != StateEnum::CONNECTING && state_ != StateEnum::FAST_OPEN)) {
540 assert(state_ == StateEnum::ESTABLISHED);
541 assert((shutdownFlags_ & SHUT_WRITE) == 0);
542 if (sendTimeout_ > 0) {
543 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
544 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
545 withAddr("failed to reschedule send timeout in setSendTimeout"));
546 return failWrite(__func__, ex);
549 writeTimeout_.cancelTimeout();
554 void AsyncSocket::setReadCB(ReadCallback *callback) {
555 VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
556 << ", callback=" << callback << ", state=" << state_;
558 // Short circuit if callback is the same as the existing readCallback_.
560 // Note that this is needed for proper functioning during some cleanup cases.
561 // During cleanup we allow setReadCallback(nullptr) to be called even if the
562 // read callback is already unset and we have been detached from an event
563 // base. This check prevents us from asserting
564 // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
565 if (callback == readCallback_) {
569 /* We are removing a read callback */
570 if (callback == nullptr &&
571 immediateReadHandler_.isLoopCallbackScheduled()) {
572 immediateReadHandler_.cancelLoopCallback();
575 if (shutdownFlags_ & SHUT_READ) {
576 // Reads have already been shut down on this socket.
578 // Allow setReadCallback(nullptr) to be called in this case, but don't
579 // allow a new callback to be set.
581 // For example, setReadCallback(nullptr) can happen after an error if we
582 // invoke some other error callback before invoking readError(). The other
583 // error callback that is invoked first may go ahead and clear the read
584 // callback before we get a chance to invoke readError().
585 if (callback != nullptr) {
586 return invalidState(callback);
588 assert((eventFlags_ & EventHandler::READ) == 0);
589 readCallback_ = nullptr;
593 DestructorGuard dg(this);
594 assert(eventBase_->isInEventBaseThread());
596 switch ((StateEnum)state_) {
597 case StateEnum::CONNECTING:
598 case StateEnum::FAST_OPEN:
599 // For convenience, we allow the read callback to be set while we are
600 // still connecting. We just store the callback for now. Once the
601 // connection completes we'll register for read events.
602 readCallback_ = callback;
604 case StateEnum::ESTABLISHED:
606 readCallback_ = callback;
607 uint16_t oldFlags = eventFlags_;
609 eventFlags_ |= EventHandler::READ;
611 eventFlags_ &= ~EventHandler::READ;
614 // Update our registration if our flags have changed
615 if (eventFlags_ != oldFlags) {
616 // We intentionally ignore the return value here.
617 // updateEventRegistration() will move us into the error state if it
618 // fails, and we don't need to do anything else here afterwards.
619 (void)updateEventRegistration();
623 checkForImmediateRead();
627 case StateEnum::CLOSED:
628 case StateEnum::ERROR:
629 // We should never reach here. SHUT_READ should always be set
630 // if we are in STATE_CLOSED or STATE_ERROR.
632 return invalidState(callback);
633 case StateEnum::UNINIT:
634 // We do not allow setReadCallback() to be called before we start
636 return invalidState(callback);
639 // We don't put a default case in the switch statement, so that the compiler
640 // will warn us to update the switch statement if a new state is added.
641 return invalidState(callback);
644 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
645 return readCallback_;
648 void AsyncSocket::write(WriteCallback* callback,
649 const void* buf, size_t bytes, WriteFlags flags) {
651 op.iov_base = const_cast<void*>(buf);
653 writeImpl(callback, &op, 1, unique_ptr<IOBuf>(), flags);
656 void AsyncSocket::writev(WriteCallback* callback,
660 writeImpl(callback, vec, count, unique_ptr<IOBuf>(), flags);
663 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
665 constexpr size_t kSmallSizeMax = 64;
666 size_t count = buf->countChainElements();
667 if (count <= kSmallSizeMax) {
668 // suppress "warning: variable length array 'vec' is used [-Wvla]"
670 FOLLY_GCC_DISABLE_WARNING(vla);
671 iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA, count, kSmallSizeMax)];
674 writeChainImpl(callback, vec, count, std::move(buf), flags);
676 iovec* vec = new iovec[count];
677 writeChainImpl(callback, vec, count, std::move(buf), flags);
682 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
683 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
684 size_t veclen = buf->fillIov(vec, count);
685 writeImpl(callback, vec, veclen, std::move(buf), flags);
688 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
689 size_t count, unique_ptr<IOBuf>&& buf,
691 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
692 << ", callback=" << callback << ", count=" << count
693 << ", state=" << state_;
694 DestructorGuard dg(this);
695 unique_ptr<IOBuf>ioBuf(std::move(buf));
696 assert(eventBase_->isInEventBaseThread());
698 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
699 // No new writes may be performed after the write side of the socket has
702 // We could just call callback->writeError() here to fail just this write.
703 // However, fail hard and use invalidState() to fail all outstanding
704 // callbacks and move the socket into the error state. There's most likely
705 // a bug in the caller's code, so we abort everything rather than trying to
706 // proceed as best we can.
707 return invalidState(callback);
710 uint32_t countWritten = 0;
711 uint32_t partialWritten = 0;
712 int bytesWritten = 0;
713 bool mustRegister = false;
714 if ((state_ == StateEnum::ESTABLISHED || state_ == StateEnum::FAST_OPEN) &&
716 if (writeReqHead_ == nullptr) {
717 // If we are established and there are no other writes pending,
718 // we can attempt to perform the write immediately.
719 assert(writeReqTail_ == nullptr);
720 assert((eventFlags_ & EventHandler::WRITE) == 0);
723 performWrite(vec, count, flags, &countWritten, &partialWritten);
724 bytesWritten = writeResult.writeReturn;
725 if (bytesWritten < 0) {
726 auto errnoCopy = errno;
727 if (writeResult.exception) {
728 return failWrite(__func__, callback, 0, *writeResult.exception);
730 AsyncSocketException ex(
731 AsyncSocketException::INTERNAL_ERROR,
732 withAddr("writev failed"),
734 return failWrite(__func__, callback, 0, ex);
735 } else if (countWritten == count) {
736 // We successfully wrote everything.
737 // Invoke the callback and return.
739 callback->writeSuccess();
742 } else { // continue writing the next writeReq
743 if (bufferCallback_) {
744 bufferCallback_->onEgressBuffered();
748 // Writes might put the socket back into connecting state
749 // if TFO is enabled, and using TFO fails.
750 // This means that write timeouts would not be active, however
751 // connect timeouts would affect this stage.
755 } else if (!connecting()) {
756 // Invalid state for writing
757 return invalidState(callback);
760 // Create a new WriteRequest to add to the queue
763 req = BytesWriteRequest::newRequest(this, callback, vec + countWritten,
764 count - countWritten, partialWritten,
765 bytesWritten, std::move(ioBuf), flags);
766 } catch (const std::exception& ex) {
767 // we mainly expect to catch std::bad_alloc here
768 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
769 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
770 return failWrite(__func__, callback, bytesWritten, tex);
773 if (writeReqTail_ == nullptr) {
774 assert(writeReqHead_ == nullptr);
775 writeReqHead_ = writeReqTail_ = req;
777 writeReqTail_->append(req);
781 // Register for write events if are established and not currently
782 // waiting on write events
784 assert(state_ == StateEnum::ESTABLISHED);
785 assert((eventFlags_ & EventHandler::WRITE) == 0);
786 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
787 assert(state_ == StateEnum::ERROR);
790 if (sendTimeout_ > 0) {
791 // Schedule a timeout to fire if the write takes too long.
792 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
793 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
794 withAddr("failed to schedule send timeout"));
795 return failWrite(__func__, ex);
801 void AsyncSocket::writeRequest(WriteRequest* req) {
802 if (writeReqTail_ == nullptr) {
803 assert(writeReqHead_ == nullptr);
804 writeReqHead_ = writeReqTail_ = req;
807 writeReqTail_->append(req);
812 void AsyncSocket::close() {
813 VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
814 << ", state=" << state_ << ", shutdownFlags="
815 << std::hex << (int) shutdownFlags_;
817 // close() is only different from closeNow() when there are pending writes
818 // that need to drain before we can close. In all other cases, just call
821 // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
822 // STATE_ERROR if close() is invoked while a previous closeNow() or failure
823 // is still running. (e.g., If there are multiple pending writes, and we
824 // call writeError() on the first one, it may call close(). In this case we
825 // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
826 // writes will still be in the queue.)
828 // We only need to drain pending writes if we are still in STATE_CONNECTING
829 // or STATE_ESTABLISHED
830 if ((writeReqHead_ == nullptr) ||
831 !(state_ == StateEnum::CONNECTING ||
832 state_ == StateEnum::ESTABLISHED)) {
837 // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
838 // destroyed until close() returns.
839 DestructorGuard dg(this);
840 assert(eventBase_->isInEventBaseThread());
842 // Since there are write requests pending, we have to set the
843 // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
844 // connect finishes and we finish writing these requests.
846 // Set SHUT_READ to indicate that reads are shut down, and set the
847 // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
848 // pending writes complete.
849 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
851 // If a read callback is set, invoke readEOF() immediately to inform it that
852 // the socket has been closed and no more data can be read.
854 // Disable reads if they are enabled
855 if (!updateEventRegistration(0, EventHandler::READ)) {
856 // We're now in the error state; callbacks have been cleaned up
857 assert(state_ == StateEnum::ERROR);
858 assert(readCallback_ == nullptr);
860 ReadCallback* callback = readCallback_;
861 readCallback_ = nullptr;
867 void AsyncSocket::closeNow() {
868 VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
869 << ", state=" << state_ << ", shutdownFlags="
870 << std::hex << (int) shutdownFlags_;
871 DestructorGuard dg(this);
872 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
875 case StateEnum::ESTABLISHED:
876 case StateEnum::CONNECTING:
877 case StateEnum::FAST_OPEN: {
878 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
879 state_ = StateEnum::CLOSED;
881 // If the write timeout was set, cancel it.
882 writeTimeout_.cancelTimeout();
884 // If we are registered for I/O events, unregister.
885 if (eventFlags_ != EventHandler::NONE) {
886 eventFlags_ = EventHandler::NONE;
887 if (!updateEventRegistration()) {
888 // We will have been moved into the error state.
889 assert(state_ == StateEnum::ERROR);
894 if (immediateReadHandler_.isLoopCallbackScheduled()) {
895 immediateReadHandler_.cancelLoopCallback();
899 ioHandler_.changeHandlerFD(-1);
903 invokeConnectErr(socketClosedLocallyEx);
905 failAllWrites(socketClosedLocallyEx);
908 ReadCallback* callback = readCallback_;
909 readCallback_ = nullptr;
914 case StateEnum::CLOSED:
915 // Do nothing. It's possible that we are being called recursively
916 // from inside a callback that we invoked inside another call to close()
917 // that is still running.
919 case StateEnum::ERROR:
920 // Do nothing. The error handling code has performed (or is performing)
923 case StateEnum::UNINIT:
924 assert(eventFlags_ == EventHandler::NONE);
925 assert(connectCallback_ == nullptr);
926 assert(readCallback_ == nullptr);
927 assert(writeReqHead_ == nullptr);
928 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
929 state_ = StateEnum::CLOSED;
933 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
934 << ") called in unknown state " << state_;
937 void AsyncSocket::closeWithReset() {
938 // Enable SO_LINGER, with the linger timeout set to 0.
939 // This will trigger a TCP reset when we close the socket.
941 struct linger optLinger = {1, 0};
942 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
943 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
944 << "on " << fd_ << ": errno=" << errno;
948 // Then let closeNow() take care of the rest
952 void AsyncSocket::shutdownWrite() {
953 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
954 << ", state=" << state_ << ", shutdownFlags="
955 << std::hex << (int) shutdownFlags_;
957 // If there are no pending writes, shutdownWrite() is identical to
958 // shutdownWriteNow().
959 if (writeReqHead_ == nullptr) {
964 assert(eventBase_->isInEventBaseThread());
966 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
967 // shutdown will be performed once all writes complete.
968 shutdownFlags_ |= SHUT_WRITE_PENDING;
971 void AsyncSocket::shutdownWriteNow() {
972 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
973 << ", fd=" << fd_ << ", state=" << state_
974 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
976 if (shutdownFlags_ & SHUT_WRITE) {
977 // Writes are already shutdown; nothing else to do.
981 // If SHUT_READ is already set, just call closeNow() to completely
982 // close the socket. This can happen if close() was called with writes
983 // pending, and then shutdownWriteNow() is called before all pending writes
985 if (shutdownFlags_ & SHUT_READ) {
990 DestructorGuard dg(this);
991 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
993 switch (static_cast<StateEnum>(state_)) {
994 case StateEnum::ESTABLISHED:
996 shutdownFlags_ |= SHUT_WRITE;
998 // If the write timeout was set, cancel it.
999 writeTimeout_.cancelTimeout();
1001 // If we are registered for write events, unregister.
1002 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1003 // We will have been moved into the error state.
1004 assert(state_ == StateEnum::ERROR);
1008 // Shutdown writes on the file descriptor
1009 shutdown(fd_, SHUT_WR);
1011 // Immediately fail all write requests
1012 failAllWrites(socketShutdownForWritesEx);
1015 case StateEnum::CONNECTING:
1017 // Set the SHUT_WRITE_PENDING flag.
1018 // When the connection completes, it will check this flag,
1019 // shutdown the write half of the socket, and then set SHUT_WRITE.
1020 shutdownFlags_ |= SHUT_WRITE_PENDING;
1022 // Immediately fail all write requests
1023 failAllWrites(socketShutdownForWritesEx);
1026 case StateEnum::UNINIT:
1027 // Callers normally shouldn't call shutdownWriteNow() before the socket
1028 // even starts connecting. Nonetheless, go ahead and set
1029 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
1030 // immediately shut down the write side of the socket.
1031 shutdownFlags_ |= SHUT_WRITE_PENDING;
1033 case StateEnum::FAST_OPEN:
1034 // In fast open state we haven't call connected yet, and if we shutdown
1035 // the writes, we will never try to call connect, so shut everything down
1036 shutdownFlags_ |= SHUT_WRITE;
1037 // Immediately fail all write requests
1038 failAllWrites(socketShutdownForWritesEx);
1040 case StateEnum::CLOSED:
1041 case StateEnum::ERROR:
1042 // We should never get here. SHUT_WRITE should always be set
1043 // in STATE_CLOSED and STATE_ERROR.
1044 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
1045 << ", fd=" << fd_ << ") in unexpected state " << state_
1046 << " with SHUT_WRITE not set ("
1047 << std::hex << (int) shutdownFlags_ << ")";
1052 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
1053 << fd_ << ") called in unknown state " << state_;
1056 bool AsyncSocket::readable() const {
1060 struct pollfd fds[1];
1062 fds[0].events = POLLIN;
1064 int rc = poll(fds, 1, 0);
1068 bool AsyncSocket::isPending() const {
1069 return ioHandler_.isPending();
1072 bool AsyncSocket::hangup() const {
1074 // sanity check, no one should ask for hangup if we are not connected.
1078 #ifdef POLLRDHUP // Linux-only
1079 struct pollfd fds[1];
1081 fds[0].events = POLLRDHUP|POLLHUP;
1084 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1090 bool AsyncSocket::good() const {
1092 (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN ||
1093 state_ == StateEnum::ESTABLISHED) &&
1094 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1097 bool AsyncSocket::error() const {
1098 return (state_ == StateEnum::ERROR);
1101 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1102 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1103 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1104 << ", state=" << state_ << ", events="
1105 << std::hex << eventFlags_ << ")";
1106 assert(eventBase_ == nullptr);
1107 assert(eventBase->isInEventBaseThread());
1109 eventBase_ = eventBase;
1110 ioHandler_.attachEventBase(eventBase);
1111 writeTimeout_.attachEventBase(eventBase);
1114 void AsyncSocket::detachEventBase() {
1115 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1116 << ", old evb=" << eventBase_ << ", state=" << state_
1117 << ", events=" << std::hex << eventFlags_ << ")";
1118 assert(eventBase_ != nullptr);
1119 assert(eventBase_->isInEventBaseThread());
1121 eventBase_ = nullptr;
1122 ioHandler_.detachEventBase();
1123 writeTimeout_.detachEventBase();
1126 bool AsyncSocket::isDetachable() const {
1127 DCHECK(eventBase_ != nullptr);
1128 DCHECK(eventBase_->isInEventBaseThread());
1130 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1133 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1134 if (!localAddr_.isInitialized()) {
1135 localAddr_.setFromLocalAddress(fd_);
1137 *address = localAddr_;
1140 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1141 if (!addr_.isInitialized()) {
1142 addr_.setFromPeerAddress(fd_);
1147 int AsyncSocket::setNoDelay(bool noDelay) {
1149 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1150 << this << "(state=" << state_ << ")";
1155 int value = noDelay ? 1 : 0;
1156 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1157 int errnoCopy = errno;
1158 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1159 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1160 << strerror(errnoCopy);
1167 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1169 #ifndef TCP_CONGESTION
1170 #define TCP_CONGESTION 13
1174 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1175 << "socket " << this << "(state=" << state_ << ")";
1180 if (setsockopt(fd_, IPPROTO_TCP, TCP_CONGESTION, cname.c_str(),
1181 cname.length() + 1) != 0) {
1182 int errnoCopy = errno;
1183 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1184 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1185 << strerror(errnoCopy);
1192 int AsyncSocket::setQuickAck(bool quickack) {
1194 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1195 << this << "(state=" << state_ << ")";
1200 #ifdef TCP_QUICKACK // Linux-only
1201 int value = quickack ? 1 : 0;
1202 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1203 int errnoCopy = errno;
1204 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1205 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1206 << strerror(errnoCopy);
1216 int AsyncSocket::setSendBufSize(size_t bufsize) {
1218 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1219 << this << "(state=" << state_ << ")";
1223 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1224 int errnoCopy = errno;
1225 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1226 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1227 << strerror(errnoCopy);
1234 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1236 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1237 << this << "(state=" << state_ << ")";
1241 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1242 int errnoCopy = errno;
1243 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1244 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1245 << strerror(errnoCopy);
1252 int AsyncSocket::setTCPProfile(int profd) {
1254 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1255 << this << "(state=" << state_ << ")";
1259 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1260 int errnoCopy = errno;
1261 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1262 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1263 << strerror(errnoCopy);
1270 void AsyncSocket::ioReady(uint16_t events) noexcept {
1271 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd" << fd_
1272 << ", events=" << std::hex << events << ", state=" << state_;
1273 DestructorGuard dg(this);
1274 assert(events & EventHandler::READ_WRITE);
1275 assert(eventBase_->isInEventBaseThread());
1277 uint16_t relevantEvents = events & EventHandler::READ_WRITE;
1278 if (relevantEvents == EventHandler::READ) {
1280 } else if (relevantEvents == EventHandler::WRITE) {
1282 } else if (relevantEvents == EventHandler::READ_WRITE) {
1283 EventBase* originalEventBase = eventBase_;
1284 // If both read and write events are ready, process writes first.
1287 // Return now if handleWrite() detached us from our EventBase
1288 if (eventBase_ != originalEventBase) {
1292 // Only call handleRead() if a read callback is still installed.
1293 // (It's possible that the read callback was uninstalled during
1295 if (readCallback_) {
1299 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1300 << std::hex << events << "(this=" << this << ")";
1305 AsyncSocket::ReadResult
1306 AsyncSocket::performRead(void** buf, size_t* buflen, size_t* /* offset */) {
1307 VLOG(5) << "AsyncSocket::performRead() this=" << this << ", buf=" << *buf
1308 << ", buflen=" << *buflen;
1312 recvFlags |= MSG_PEEK;
1315 ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT | recvFlags);
1317 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1318 // No more data to read right now.
1319 return ReadResult(READ_BLOCKING);
1321 return ReadResult(READ_ERROR);
1324 appBytesReceived_ += bytes;
1325 return ReadResult(bytes);
1329 void AsyncSocket::prepareReadBuffer(void** buf, size_t* buflen) noexcept {
1330 // no matter what, buffer should be preapared for non-ssl socket
1331 CHECK(readCallback_);
1332 readCallback_->getReadBuffer(buf, buflen);
1335 void AsyncSocket::handleRead() noexcept {
1336 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1337 << ", state=" << state_;
1338 assert(state_ == StateEnum::ESTABLISHED);
1339 assert((shutdownFlags_ & SHUT_READ) == 0);
1340 assert(readCallback_ != nullptr);
1341 assert(eventFlags_ & EventHandler::READ);
1344 // - a read attempt would block
1345 // - readCallback_ is uninstalled
1346 // - the number of loop iterations exceeds the optional maximum
1347 // - this AsyncSocket is moved to another EventBase
1349 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1350 // which is why need to check for it here.
1352 // The last bullet point is slightly subtle. readDataAvailable() may also
1353 // detach this socket from this EventBase. However, before
1354 // readDataAvailable() returns another thread may pick it up, attach it to
1355 // a different EventBase, and install another readCallback_. We need to
1356 // exit immediately after readDataAvailable() returns if the eventBase_ has
1357 // changed. (The caller must perform some sort of locking to transfer the
1358 // AsyncSocket between threads properly. This will be sufficient to ensure
1359 // that this thread sees the updated eventBase_ variable after
1360 // readDataAvailable() returns.)
1361 uint16_t numReads = 0;
1362 EventBase* originalEventBase = eventBase_;
1363 while (readCallback_ && eventBase_ == originalEventBase) {
1364 // Get the buffer to read into.
1365 void* buf = nullptr;
1366 size_t buflen = 0, offset = 0;
1368 prepareReadBuffer(&buf, &buflen);
1369 VLOG(5) << "prepareReadBuffer() buf=" << buf << ", buflen=" << buflen;
1370 } catch (const AsyncSocketException& ex) {
1371 return failRead(__func__, ex);
1372 } catch (const std::exception& ex) {
1373 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1374 string("ReadCallback::getReadBuffer() "
1375 "threw exception: ") +
1377 return failRead(__func__, tex);
1379 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1380 "ReadCallback::getReadBuffer() threw "
1381 "non-exception type");
1382 return failRead(__func__, ex);
1384 if (!isBufferMovable_ && (buf == nullptr || buflen == 0)) {
1385 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1386 "ReadCallback::getReadBuffer() returned "
1388 return failRead(__func__, ex);
1392 auto readResult = performRead(&buf, &buflen, &offset);
1393 auto bytesRead = readResult.readReturn;
1394 VLOG(4) << "this=" << this << ", AsyncSocket::handleRead() got "
1395 << bytesRead << " bytes";
1396 if (bytesRead > 0) {
1397 if (!isBufferMovable_) {
1398 readCallback_->readDataAvailable(bytesRead);
1400 CHECK(kOpenSslModeMoveBufferOwnership);
1401 VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
1402 << "buf=" << buf << ", " << bytesRead << "/" << buflen
1403 << ", offset=" << offset;
1404 auto readBuf = folly::IOBuf::takeOwnership(buf, buflen);
1405 readBuf->trimStart(offset);
1406 readBuf->trimEnd(buflen - offset - bytesRead);
1407 readCallback_->readBufferAvailable(std::move(readBuf));
1410 // Fall through and continue around the loop if the read
1411 // completely filled the available buffer.
1412 // Note that readCallback_ may have been uninstalled or changed inside
1413 // readDataAvailable().
1414 if (size_t(bytesRead) < buflen) {
1417 } else if (bytesRead == READ_BLOCKING) {
1418 // No more data to read right now.
1420 } else if (bytesRead == READ_ERROR) {
1421 readErr_ = READ_ERROR;
1422 if (readResult.exception) {
1423 return failRead(__func__, *readResult.exception);
1425 auto errnoCopy = errno;
1426 AsyncSocketException ex(
1427 AsyncSocketException::INTERNAL_ERROR,
1428 withAddr("recv() failed"),
1430 return failRead(__func__, ex);
1432 assert(bytesRead == READ_EOF);
1433 readErr_ = READ_EOF;
1435 shutdownFlags_ |= SHUT_READ;
1436 if (!updateEventRegistration(0, EventHandler::READ)) {
1437 // we've already been moved into STATE_ERROR
1438 assert(state_ == StateEnum::ERROR);
1439 assert(readCallback_ == nullptr);
1443 ReadCallback* callback = readCallback_;
1444 readCallback_ = nullptr;
1445 callback->readEOF();
1448 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1449 if (readCallback_ != nullptr) {
1450 // We might still have data in the socket.
1451 // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
1452 scheduleImmediateRead();
1460 * This function attempts to write as much data as possible, until no more data
1463 * - If it sends all available data, it unregisters for write events, and stops
1464 * the writeTimeout_.
1466 * - If not all of the data can be sent immediately, it reschedules
1467 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1468 * registered for write events.
1470 void AsyncSocket::handleWrite() noexcept {
1471 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1472 << ", state=" << state_;
1473 DestructorGuard dg(this);
1475 if (state_ == StateEnum::CONNECTING) {
1481 assert(state_ == StateEnum::ESTABLISHED);
1482 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1483 assert(writeReqHead_ != nullptr);
1485 // Loop until we run out of write requests,
1486 // or until this socket is moved to another EventBase.
1487 // (See the comment in handleRead() explaining how this can happen.)
1488 EventBase* originalEventBase = eventBase_;
1489 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1490 auto writeResult = writeReqHead_->performWrite();
1491 if (writeResult.writeReturn < 0) {
1492 if (writeResult.exception) {
1493 return failWrite(__func__, *writeResult.exception);
1495 auto errnoCopy = errno;
1496 AsyncSocketException ex(
1497 AsyncSocketException::INTERNAL_ERROR,
1498 withAddr("writev() failed"),
1500 return failWrite(__func__, ex);
1501 } else if (writeReqHead_->isComplete()) {
1502 // We finished this request
1503 WriteRequest* req = writeReqHead_;
1504 writeReqHead_ = req->getNext();
1506 if (writeReqHead_ == nullptr) {
1507 writeReqTail_ = nullptr;
1508 // This is the last write request.
1509 // Unregister for write events and cancel the send timer
1510 // before we invoke the callback. We have to update the state properly
1511 // before calling the callback, since it may want to detach us from
1513 if (eventFlags_ & EventHandler::WRITE) {
1514 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1515 assert(state_ == StateEnum::ERROR);
1518 // Stop the send timeout
1519 writeTimeout_.cancelTimeout();
1521 assert(!writeTimeout_.isScheduled());
1523 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
1524 // we finish sending the last write request.
1526 // We have to do this before invoking writeSuccess(), since
1527 // writeSuccess() may detach us from our EventBase.
1528 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
1529 assert(connectCallback_ == nullptr);
1530 shutdownFlags_ |= SHUT_WRITE;
1532 if (shutdownFlags_ & SHUT_READ) {
1533 // Reads have already been shutdown. Fully close the socket and
1534 // move to STATE_CLOSED.
1536 // Note: This code currently moves us to STATE_CLOSED even if
1537 // close() hasn't ever been called. This can occur if we have
1538 // received EOF from the peer and shutdownWrite() has been called
1539 // locally. Should we bother staying in STATE_ESTABLISHED in this
1540 // case, until close() is actually called? I can't think of a
1541 // reason why we would need to do so. No other operations besides
1542 // calling close() or destroying the socket can be performed at
1544 assert(readCallback_ == nullptr);
1545 state_ = StateEnum::CLOSED;
1547 ioHandler_.changeHandlerFD(-1);
1551 // Reads are still enabled, so we are only doing a half-shutdown
1552 shutdown(fd_, SHUT_WR);
1557 // Invoke the callback
1558 WriteCallback* callback = req->getCallback();
1561 callback->writeSuccess();
1563 // We'll continue around the loop, trying to write another request
1566 if (bufferCallback_) {
1567 bufferCallback_->onEgressBuffered();
1569 writeReqHead_->consume();
1570 // Stop after a partial write; it's highly likely that a subsequent write
1571 // attempt will just return EAGAIN.
1573 // Ensure that we are registered for write events.
1574 if ((eventFlags_ & EventHandler::WRITE) == 0) {
1575 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1576 assert(state_ == StateEnum::ERROR);
1581 // Reschedule the send timeout, since we have made some write progress.
1582 if (sendTimeout_ > 0) {
1583 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1584 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1585 withAddr("failed to reschedule write timeout"));
1586 return failWrite(__func__, ex);
1592 if (!writeReqHead_ && bufferCallback_) {
1593 bufferCallback_->onEgressBufferCleared();
1597 void AsyncSocket::checkForImmediateRead() noexcept {
1598 // We currently don't attempt to perform optimistic reads in AsyncSocket.
1599 // (However, note that some subclasses do override this method.)
1601 // Simply calling handleRead() here would be bad, as this would call
1602 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
1603 // buffer even though no data may be available. This would waste lots of
1604 // memory, since the buffer will sit around unused until the socket actually
1605 // becomes readable.
1607 // Checking if the socket is readable now also seems like it would probably
1608 // be a pessimism. In most cases it probably wouldn't be readable, and we
1609 // would just waste an extra system call. Even if it is readable, waiting to
1610 // find out from libevent on the next event loop doesn't seem that bad.
1613 void AsyncSocket::handleInitialReadWrite() noexcept {
1614 // Our callers should already be holding a DestructorGuard, but grab
1615 // one here just to make sure, in case one of our calling code paths ever
1617 DestructorGuard dg(this);
1619 // If we have a readCallback_, make sure we enable read events. We
1620 // may already be registered for reads if connectSuccess() set
1621 // the read calback.
1622 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
1623 assert(state_ == StateEnum::ESTABLISHED);
1624 assert((shutdownFlags_ & SHUT_READ) == 0);
1625 if (!updateEventRegistration(EventHandler::READ, 0)) {
1626 assert(state_ == StateEnum::ERROR);
1629 checkForImmediateRead();
1630 } else if (readCallback_ == nullptr) {
1631 // Unregister for read events.
1632 updateEventRegistration(0, EventHandler::READ);
1635 // If we have write requests pending, try to send them immediately.
1636 // Since we just finished accepting, there is a very good chance that we can
1637 // write without blocking.
1639 // However, we only process them if EventHandler::WRITE is not already set,
1640 // which means that we're already blocked on a write attempt. (This can
1641 // happen if connectSuccess() called write() before returning.)
1642 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
1643 // Call handleWrite() to perform write processing.
1645 } else if (writeReqHead_ == nullptr) {
1646 // Unregister for write event.
1647 updateEventRegistration(0, EventHandler::WRITE);
1651 void AsyncSocket::handleConnect() noexcept {
1652 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
1653 << ", state=" << state_;
1654 assert(state_ == StateEnum::CONNECTING);
1655 // SHUT_WRITE can never be set while we are still connecting;
1656 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
1658 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1660 // In case we had a connect timeout, cancel the timeout
1661 writeTimeout_.cancelTimeout();
1662 // We don't use a persistent registration when waiting on a connect event,
1663 // so we have been automatically unregistered now. Update eventFlags_ to
1665 assert(eventFlags_ == EventHandler::WRITE);
1666 eventFlags_ = EventHandler::NONE;
1668 // Call getsockopt() to check if the connect succeeded
1670 socklen_t len = sizeof(error);
1671 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
1673 auto errnoCopy = errno;
1674 AsyncSocketException ex(
1675 AsyncSocketException::INTERNAL_ERROR,
1676 withAddr("error calling getsockopt() after connect"),
1678 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1679 << fd_ << " host=" << addr_.describe()
1680 << ") exception:" << ex.what();
1681 return failConnect(__func__, ex);
1685 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1686 "connect failed", error);
1687 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1688 << fd_ << " host=" << addr_.describe()
1689 << ") exception: " << ex.what();
1690 return failConnect(__func__, ex);
1693 // Move into STATE_ESTABLISHED
1694 state_ = StateEnum::ESTABLISHED;
1696 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
1697 // perform, immediately shutdown the write half of the socket.
1698 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
1699 // SHUT_READ shouldn't be set. If close() is called on the socket while we
1700 // are still connecting we just abort the connect rather than waiting for
1702 assert((shutdownFlags_ & SHUT_READ) == 0);
1703 shutdown(fd_, SHUT_WR);
1704 shutdownFlags_ |= SHUT_WRITE;
1707 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
1708 << "successfully connected; state=" << state_;
1710 // Remember the EventBase we are attached to, before we start invoking any
1711 // callbacks (since the callbacks may call detachEventBase()).
1712 EventBase* originalEventBase = eventBase_;
1714 invokeConnectSuccess();
1715 // Note that the connect callback may have changed our state.
1716 // (set or unset the read callback, called write(), closed the socket, etc.)
1717 // The following code needs to handle these situations correctly.
1719 // If the socket has been closed, readCallback_ and writeReqHead_ will
1720 // always be nullptr, so that will prevent us from trying to read or write.
1722 // The main thing to check for is if eventBase_ is still originalEventBase.
1723 // If not, we have been detached from this event base, so we shouldn't
1724 // perform any more operations.
1725 if (eventBase_ != originalEventBase) {
1729 handleInitialReadWrite();
1732 void AsyncSocket::timeoutExpired() noexcept {
1733 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
1734 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
1735 DestructorGuard dg(this);
1736 assert(eventBase_->isInEventBaseThread());
1738 if (state_ == StateEnum::CONNECTING) {
1739 // connect() timed out
1740 // Unregister for I/O events.
1741 if (connectCallback_) {
1742 AsyncSocketException ex(
1743 AsyncSocketException::TIMED_OUT, "connect timed out");
1744 failConnect(__func__, ex);
1746 // we faced a connect error without a connect callback, which could
1747 // happen due to TFO.
1748 AsyncSocketException ex(
1749 AsyncSocketException::TIMED_OUT, "write timed out during connection");
1750 failWrite(__func__, ex);
1753 // a normal write operation timed out
1754 AsyncSocketException ex(AsyncSocketException::TIMED_OUT, "write timed out");
1755 failWrite(__func__, ex);
1759 ssize_t AsyncSocket::tfoSendMsg(int fd, struct msghdr* msg, int msg_flags) {
1760 return detail::tfo_sendmsg(fd, msg, msg_flags);
1763 AsyncSocket::WriteResult
1764 AsyncSocket::sendSocketMessage(int fd, struct msghdr* msg, int msg_flags) {
1765 ssize_t totalWritten = 0;
1766 if (state_ == StateEnum::FAST_OPEN) {
1767 sockaddr_storage addr;
1768 auto len = addr_.getAddress(&addr);
1769 msg->msg_name = &addr;
1770 msg->msg_namelen = len;
1771 totalWritten = tfoSendMsg(fd_, msg, msg_flags);
1772 if (totalWritten >= 0) {
1773 // Call tfo_succeeded to check if TFO was used.
1774 tfoSucceeded_ = detail::tfo_succeeded(fd_);
1776 auto errnoCopy = errno;
1777 AsyncSocketException ex(
1778 AsyncSocketException::INTERNAL_ERROR,
1779 withAddr("error calling tfo_succeeded"),
1782 WRITE_ERROR, folly::make_unique<AsyncSocketException>(ex));
1785 tfoFinished_ = true;
1786 state_ = StateEnum::ESTABLISHED;
1787 handleInitialReadWrite();
1788 } else if (errno == EINPROGRESS) {
1789 VLOG(4) << "TFO falling back to connecting";
1790 // A normal sendmsg doesn't return EINPROGRESS, however
1791 // TFO might fallback to connecting if there is no
1793 state_ = StateEnum::CONNECTING;
1795 scheduleConnectTimeoutAndRegisterForEvents();
1796 } catch (const AsyncSocketException& ex) {
1798 WRITE_ERROR, folly::make_unique<AsyncSocketException>(ex));
1800 // Let's fake it that no bytes were written and return an errno.
1803 } else if (errno == EOPNOTSUPP) {
1804 VLOG(4) << "TFO not supported";
1805 // Try falling back to connecting.
1806 state_ = StateEnum::CONNECTING;
1808 int ret = socketConnect((const sockaddr*)&addr, len);
1810 // connect succeeded immediately
1811 // Treat this like no data was written.
1812 state_ = StateEnum::ESTABLISHED;
1813 handleInitialReadWrite();
1815 // If there was no exception during connections,
1816 // we would return that no bytes were written.
1819 } catch (const AsyncSocketException& ex) {
1821 WRITE_ERROR, folly::make_unique<AsyncSocketException>(ex));
1823 } else if (errno == EAGAIN) {
1824 // Normally sendmsg would indicate that the write would block.
1825 // However in the fast open case, it would indicate that sendmsg
1826 // fell back to a connect. This is a return code from connect()
1827 // instead, and is an error condition indicating no fds available.
1830 folly::make_unique<AsyncSocketException>(
1831 AsyncSocketException::UNKNOWN, "No more free local ports"));
1834 totalWritten = ::sendmsg(fd, msg, msg_flags);
1836 return WriteResult(totalWritten);
1839 AsyncSocket::WriteResult AsyncSocket::performWrite(
1843 uint32_t* countWritten,
1844 uint32_t* partialWritten) {
1845 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
1846 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
1847 // (since it may terminate the program if the main program doesn't explicitly
1850 msg.msg_name = nullptr;
1851 msg.msg_namelen = 0;
1852 msg.msg_iov = const_cast<iovec *>(vec);
1853 msg.msg_iovlen = std::min<size_t>(count, kIovMax);
1854 msg.msg_control = nullptr;
1855 msg.msg_controllen = 0;
1858 int msg_flags = MSG_DONTWAIT;
1860 #ifdef MSG_NOSIGNAL // Linux-only
1861 msg_flags |= MSG_NOSIGNAL;
1862 if (isSet(flags, WriteFlags::CORK)) {
1863 // MSG_MORE tells the kernel we have more data to send, so wait for us to
1864 // give it the rest of the data rather than immediately sending a partial
1865 // frame, even when TCP_NODELAY is enabled.
1866 msg_flags |= MSG_MORE;
1869 if (isSet(flags, WriteFlags::EOR)) {
1870 // marks that this is the last byte of a record (response)
1871 msg_flags |= MSG_EOR;
1873 auto writeResult = sendSocketMessage(fd_, &msg, msg_flags);
1874 auto totalWritten = writeResult.writeReturn;
1875 if (totalWritten < 0) {
1876 if (!writeResult.exception && errno == EAGAIN) {
1877 // TCP buffer is full; we can't write any more data right now.
1879 *partialWritten = 0;
1880 return WriteResult(0);
1884 *partialWritten = 0;
1888 appBytesWritten_ += totalWritten;
1890 uint32_t bytesWritten;
1892 for (bytesWritten = totalWritten, n = 0; n < count; ++n) {
1893 const iovec* v = vec + n;
1894 if (v->iov_len > bytesWritten) {
1895 // Partial write finished in the middle of this iovec
1897 *partialWritten = bytesWritten;
1898 return WriteResult(totalWritten);
1901 bytesWritten -= v->iov_len;
1904 assert(bytesWritten == 0);
1906 *partialWritten = 0;
1907 return WriteResult(totalWritten);
1911 * Re-register the EventHandler after eventFlags_ has changed.
1913 * If an error occurs, fail() is called to move the socket into the error state
1914 * and call all currently installed callbacks. After an error, the
1915 * AsyncSocket is completely unregistered.
1917 * @return Returns true on succcess, or false on error.
1919 bool AsyncSocket::updateEventRegistration() {
1920 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
1921 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
1922 << ", events=" << std::hex << eventFlags_;
1923 assert(eventBase_->isInEventBaseThread());
1924 if (eventFlags_ == EventHandler::NONE) {
1925 ioHandler_.unregisterHandler();
1929 // Always register for persistent events, so we don't have to re-register
1930 // after being called back.
1931 if (!ioHandler_.registerHandler(eventFlags_ | EventHandler::PERSIST)) {
1932 eventFlags_ = EventHandler::NONE; // we're not registered after error
1933 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1934 withAddr("failed to update AsyncSocket event registration"));
1935 fail("updateEventRegistration", ex);
1942 bool AsyncSocket::updateEventRegistration(uint16_t enable,
1944 uint16_t oldFlags = eventFlags_;
1945 eventFlags_ |= enable;
1946 eventFlags_ &= ~disable;
1947 if (eventFlags_ == oldFlags) {
1950 return updateEventRegistration();
1954 void AsyncSocket::startFail() {
1955 // startFail() should only be called once
1956 assert(state_ != StateEnum::ERROR);
1957 assert(getDestructorGuardCount() > 0);
1958 state_ = StateEnum::ERROR;
1959 // Ensure that SHUT_READ and SHUT_WRITE are set,
1960 // so all future attempts to read or write will be rejected
1961 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1963 if (eventFlags_ != EventHandler::NONE) {
1964 eventFlags_ = EventHandler::NONE;
1965 ioHandler_.unregisterHandler();
1967 writeTimeout_.cancelTimeout();
1970 ioHandler_.changeHandlerFD(-1);
1975 void AsyncSocket::finishFail() {
1976 assert(state_ == StateEnum::ERROR);
1977 assert(getDestructorGuardCount() > 0);
1979 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1980 withAddr("socket closing after error"));
1981 invokeConnectErr(ex);
1984 if (readCallback_) {
1985 ReadCallback* callback = readCallback_;
1986 readCallback_ = nullptr;
1987 callback->readErr(ex);
1991 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
1992 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1993 << state_ << " host=" << addr_.describe()
1994 << "): failed in " << fn << "(): "
2000 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
2001 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2002 << state_ << " host=" << addr_.describe()
2003 << "): failed while connecting in " << fn << "(): "
2007 invokeConnectErr(ex);
2011 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
2012 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2013 << state_ << " host=" << addr_.describe()
2014 << "): failed while reading in " << fn << "(): "
2018 if (readCallback_ != nullptr) {
2019 ReadCallback* callback = readCallback_;
2020 readCallback_ = nullptr;
2021 callback->readErr(ex);
2027 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
2028 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2029 << state_ << " host=" << addr_.describe()
2030 << "): failed while writing in " << fn << "(): "
2034 // Only invoke the first write callback, since the error occurred while
2035 // writing this request. Let any other pending write callbacks be invoked in
2037 if (writeReqHead_ != nullptr) {
2038 WriteRequest* req = writeReqHead_;
2039 writeReqHead_ = req->getNext();
2040 WriteCallback* callback = req->getCallback();
2041 uint32_t bytesWritten = req->getTotalBytesWritten();
2044 callback->writeErr(bytesWritten, ex);
2051 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
2052 size_t bytesWritten,
2053 const AsyncSocketException& ex) {
2054 // This version of failWrite() is used when the failure occurs before
2055 // we've added the callback to writeReqHead_.
2056 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2057 << state_ << " host=" << addr_.describe()
2058 <<"): failed while writing in " << fn << "(): "
2062 if (callback != nullptr) {
2063 callback->writeErr(bytesWritten, ex);
2069 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
2070 // Invoke writeError() on all write callbacks.
2071 // This is used when writes are forcibly shutdown with write requests
2072 // pending, or when an error occurs with writes pending.
2073 while (writeReqHead_ != nullptr) {
2074 WriteRequest* req = writeReqHead_;
2075 writeReqHead_ = req->getNext();
2076 WriteCallback* callback = req->getCallback();
2078 callback->writeErr(req->getTotalBytesWritten(), ex);
2084 void AsyncSocket::invalidState(ConnectCallback* callback) {
2085 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2086 << "): connect() called in invalid state " << state_;
2089 * The invalidState() methods don't use the normal failure mechanisms,
2090 * since we don't know what state we are in. We don't want to call
2091 * startFail()/finishFail() recursively if we are already in the middle of
2095 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
2096 "connect() called with socket in invalid state");
2097 connectEndTime_ = std::chrono::steady_clock::now();
2098 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2100 callback->connectErr(ex);
2103 // We can't use failConnect() here since connectCallback_
2104 // may already be set to another callback. Invoke this ConnectCallback
2105 // here; any other connectCallback_ will be invoked in finishFail()
2108 callback->connectErr(ex);
2114 void AsyncSocket::invokeConnectErr(const AsyncSocketException& ex) {
2115 connectEndTime_ = std::chrono::steady_clock::now();
2116 if (connectCallback_) {
2117 ConnectCallback* callback = connectCallback_;
2118 connectCallback_ = nullptr;
2119 callback->connectErr(ex);
2123 void AsyncSocket::invokeConnectSuccess() {
2124 connectEndTime_ = std::chrono::steady_clock::now();
2125 if (connectCallback_) {
2126 ConnectCallback* callback = connectCallback_;
2127 connectCallback_ = nullptr;
2128 callback->connectSuccess();
2132 void AsyncSocket::invalidState(ReadCallback* callback) {
2133 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2134 << "): setReadCallback(" << callback
2135 << ") called in invalid state " << state_;
2137 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2138 "setReadCallback() called with socket in "
2140 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2142 callback->readErr(ex);
2147 callback->readErr(ex);
2153 void AsyncSocket::invalidState(WriteCallback* callback) {
2154 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2155 << "): write() called in invalid state " << state_;
2157 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2158 withAddr("write() called with socket in invalid state"));
2159 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2161 callback->writeErr(0, ex);
2166 callback->writeErr(0, ex);
2172 void AsyncSocket::doClose() {
2173 if (fd_ == -1) return;
2174 if (shutdownSocketSet_) {
2175 shutdownSocketSet_->close(fd_);
2182 std::ostream& operator << (std::ostream& os,
2183 const AsyncSocket::StateEnum& state) {
2184 os << static_cast<int>(state);
2188 std::string AsyncSocket::withAddr(const std::string& s) {
2189 // Don't use addr_ directly because it may not be initialized
2190 // e.g. if constructed from fd
2191 folly::SocketAddress peer, local;
2193 getPeerAddress(&peer);
2194 getLocalAddress(&local);
2195 } catch (const std::exception&) {
2200 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";
2203 void AsyncSocket::setBufferCallback(BufferCallback* cb) {
2204 bufferCallback_ = cb;