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/io/async/EventBase.h>
20 #include <folly/io/async/EventHandler.h>
21 #include <folly/SocketAddress.h>
22 #include <folly/io/IOBuf.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;
39 // static members initializers
40 const AsyncSocket::OptionMap AsyncSocket::emptyOptionMap;
42 const AsyncSocketException socketClosedLocallyEx(
43 AsyncSocketException::END_OF_FILE, "socket closed locally");
44 const AsyncSocketException socketShutdownForWritesEx(
45 AsyncSocketException::END_OF_FILE, "socket shutdown for writes");
47 // TODO: It might help performance to provide a version of BytesWriteRequest that
48 // users could derive from, so we can avoid the extra allocation for each call
49 // to write()/writev(). We could templatize TFramedAsyncChannel just like the
50 // protocols are currently templatized for transports.
52 // We would need the version for external users where they provide the iovec
53 // storage space, and only our internal version would allocate it at the end of
56 /* The default WriteRequest implementation, used for write(), writev() and
59 * A new BytesWriteRequest operation is allocated on the heap for all write
60 * operations that cannot be completed immediately.
62 class AsyncSocket::BytesWriteRequest : public AsyncSocket::WriteRequest {
64 static BytesWriteRequest* newRequest(AsyncSocket* socket,
65 WriteCallback* callback,
68 uint32_t partialWritten,
69 uint32_t bytesWritten,
70 unique_ptr<IOBuf>&& ioBuf,
73 // Since we put a variable size iovec array at the end
74 // of each BytesWriteRequest, we have to manually allocate the memory.
75 void* buf = malloc(sizeof(BytesWriteRequest) +
76 (opCount * sizeof(struct iovec)));
78 throw std::bad_alloc();
81 return new(buf) BytesWriteRequest(socket, callback, ops, opCount,
82 partialWritten, bytesWritten,
83 std::move(ioBuf), flags);
86 void destroy() override {
87 this->~BytesWriteRequest();
91 WriteResult performWrite() override {
92 WriteFlags writeFlags = flags_;
93 if (getNext() != nullptr) {
94 writeFlags = writeFlags | WriteFlags::CORK;
96 return socket_->performWrite(
97 getOps(), getOpCount(), writeFlags, &opsWritten_, &partialBytes_);
100 bool isComplete() override {
101 return opsWritten_ == getOpCount();
104 void consume() override {
105 // Advance opIndex_ forward by opsWritten_
106 opIndex_ += opsWritten_;
107 assert(opIndex_ < opCount_);
109 // If we've finished writing any IOBufs, release them
111 for (uint32_t i = opsWritten_; i != 0; --i) {
113 ioBuf_ = ioBuf_->pop();
117 // Move partialBytes_ forward into the current iovec buffer
118 struct iovec* currentOp = writeOps_ + opIndex_;
119 assert((partialBytes_ < currentOp->iov_len) || (currentOp->iov_len == 0));
120 currentOp->iov_base =
121 reinterpret_cast<uint8_t*>(currentOp->iov_base) + partialBytes_;
122 currentOp->iov_len -= partialBytes_;
124 // Increment the totalBytesWritten_ count by bytesWritten_;
125 totalBytesWritten_ += bytesWritten_;
129 BytesWriteRequest(AsyncSocket* socket,
130 WriteCallback* callback,
131 const struct iovec* ops,
133 uint32_t partialBytes,
134 uint32_t bytesWritten,
135 unique_ptr<IOBuf>&& ioBuf,
137 : AsyncSocket::WriteRequest(socket, callback)
141 , ioBuf_(std::move(ioBuf))
143 , partialBytes_(partialBytes)
144 , bytesWritten_(bytesWritten) {
145 memcpy(writeOps_, ops, sizeof(*ops) * opCount_);
148 // private destructor, to ensure callers use destroy()
149 ~BytesWriteRequest() override = default;
151 const struct iovec* getOps() const {
152 assert(opCount_ > opIndex_);
153 return writeOps_ + opIndex_;
156 uint32_t getOpCount() const {
157 assert(opCount_ > opIndex_);
158 return opCount_ - opIndex_;
161 uint32_t opCount_; ///< number of entries in writeOps_
162 uint32_t opIndex_; ///< current index into writeOps_
163 WriteFlags flags_; ///< set for WriteFlags
164 unique_ptr<IOBuf> ioBuf_; ///< underlying IOBuf, or nullptr if N/A
166 // for consume(), how much we wrote on the last write
167 uint32_t opsWritten_; ///< complete ops written
168 uint32_t partialBytes_; ///< partial bytes of incomplete op written
169 ssize_t bytesWritten_; ///< bytes written altogether
171 struct iovec writeOps_[]; ///< write operation(s) list
174 AsyncSocket::AsyncSocket()
175 : eventBase_(nullptr)
176 , writeTimeout_(this, nullptr)
177 , ioHandler_(this, nullptr)
178 , immediateReadHandler_(this) {
179 VLOG(5) << "new AsyncSocket()";
183 AsyncSocket::AsyncSocket(EventBase* evb)
185 , writeTimeout_(this, evb)
186 , ioHandler_(this, evb)
187 , immediateReadHandler_(this) {
188 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
192 AsyncSocket::AsyncSocket(EventBase* evb,
193 const folly::SocketAddress& address,
194 uint32_t connectTimeout)
196 connect(nullptr, address, connectTimeout);
199 AsyncSocket::AsyncSocket(EventBase* evb,
200 const std::string& ip,
202 uint32_t connectTimeout)
204 connect(nullptr, ip, port, connectTimeout);
207 AsyncSocket::AsyncSocket(EventBase* evb, int fd)
209 , writeTimeout_(this, evb)
210 , ioHandler_(this, evb, fd)
211 , immediateReadHandler_(this) {
212 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ", fd="
217 state_ = StateEnum::ESTABLISHED;
220 // init() method, since constructor forwarding isn't supported in most
222 void AsyncSocket::init() {
223 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
225 state_ = StateEnum::UNINIT;
226 eventFlags_ = EventHandler::NONE;
229 maxReadsPerEvent_ = 16;
230 connectCallback_ = nullptr;
231 readCallback_ = nullptr;
232 writeReqHead_ = nullptr;
233 writeReqTail_ = nullptr;
234 shutdownSocketSet_ = nullptr;
235 appBytesWritten_ = 0;
236 appBytesReceived_ = 0;
239 AsyncSocket::~AsyncSocket() {
240 VLOG(7) << "actual destruction of AsyncSocket(this=" << this
241 << ", evb=" << eventBase_ << ", fd=" << fd_
242 << ", state=" << state_ << ")";
245 void AsyncSocket::destroy() {
246 VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
247 << ", fd=" << fd_ << ", state=" << state_;
248 // When destroy is called, close the socket immediately
251 // Then call DelayedDestruction::destroy() to take care of
252 // whether or not we need immediate or delayed destruction
253 DelayedDestruction::destroy();
256 int AsyncSocket::detachFd() {
257 VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
258 << ", evb=" << eventBase_ << ", state=" << state_
259 << ", events=" << std::hex << eventFlags_ << ")";
260 // Extract the fd, and set fd_ to -1 first, so closeNow() won't
261 // actually close the descriptor.
262 if (shutdownSocketSet_) {
263 shutdownSocketSet_->remove(fd_);
267 // Call closeNow() to invoke all pending callbacks with an error.
269 // Update the EventHandler to stop using this fd.
270 // This can only be done after closeNow() unregisters the handler.
271 ioHandler_.changeHandlerFD(-1);
275 const folly::SocketAddress& AsyncSocket::anyAddress() {
276 static const folly::SocketAddress anyAddress =
277 folly::SocketAddress("0.0.0.0", 0);
281 void AsyncSocket::setShutdownSocketSet(ShutdownSocketSet* newSS) {
282 if (shutdownSocketSet_ == newSS) {
285 if (shutdownSocketSet_ && fd_ != -1) {
286 shutdownSocketSet_->remove(fd_);
288 shutdownSocketSet_ = newSS;
289 if (shutdownSocketSet_ && fd_ != -1) {
290 shutdownSocketSet_->add(fd_);
294 void AsyncSocket::setCloseOnExec() {
295 int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
297 auto errnoCopy = errno;
298 throw AsyncSocketException(
299 AsyncSocketException::INTERNAL_ERROR,
300 withAddr("failed to set close-on-exec flag"),
305 void AsyncSocket::connect(ConnectCallback* callback,
306 const folly::SocketAddress& address,
308 const OptionMap &options,
309 const folly::SocketAddress& bindAddr) noexcept {
310 DestructorGuard dg(this);
311 assert(eventBase_->isInEventBaseThread());
315 // Make sure we're in the uninitialized state
316 if (state_ != StateEnum::UNINIT) {
317 return invalidState(callback);
320 connectTimeout_ = std::chrono::milliseconds(timeout);
321 connectStartTime_ = std::chrono::steady_clock::now();
322 // Make connect end time at least >= connectStartTime.
323 connectEndTime_ = connectStartTime_;
326 state_ = StateEnum::CONNECTING;
327 connectCallback_ = callback;
329 sockaddr_storage addrStorage;
330 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
334 // Technically the first parameter should actually be a protocol family
335 // constant (PF_xxx) rather than an address family (AF_xxx), but the
336 // distinction is mainly just historical. In pretty much all
337 // implementations the PF_foo and AF_foo constants are identical.
338 fd_ = socket(address.getFamily(), SOCK_STREAM, 0);
340 auto errnoCopy = errno;
341 throw AsyncSocketException(
342 AsyncSocketException::INTERNAL_ERROR,
343 withAddr("failed to create socket"),
346 if (shutdownSocketSet_) {
347 shutdownSocketSet_->add(fd_);
349 ioHandler_.changeHandlerFD(fd_);
353 // Put the socket in non-blocking mode
354 int flags = fcntl(fd_, F_GETFL, 0);
356 auto errnoCopy = errno;
357 throw AsyncSocketException(
358 AsyncSocketException::INTERNAL_ERROR,
359 withAddr("failed to get socket flags"),
362 int rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
364 auto errnoCopy = errno;
365 throw AsyncSocketException(
366 AsyncSocketException::INTERNAL_ERROR,
367 withAddr("failed to put socket in non-blocking mode"),
371 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
372 // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
373 rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
375 auto errnoCopy = errno;
376 throw AsyncSocketException(
377 AsyncSocketException::INTERNAL_ERROR,
378 "failed to enable F_SETNOSIGPIPE on socket",
383 // By default, turn on TCP_NODELAY
384 // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
385 // setNoDelay() will log an error message if it fails.
386 if (address.getFamily() != AF_UNIX) {
387 (void)setNoDelay(true);
390 VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
391 << ", fd=" << fd_ << ", host=" << address.describe().c_str();
394 if (bindAddr != anyAddress()) {
396 if (::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
397 auto errnoCopy = errno;
399 throw AsyncSocketException(
400 AsyncSocketException::NOT_OPEN,
401 "failed to setsockopt prior to bind on " + bindAddr.describe(),
405 bindAddr.getAddress(&addrStorage);
407 if (::bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
408 auto errnoCopy = errno;
410 throw AsyncSocketException(
411 AsyncSocketException::NOT_OPEN,
412 "failed to bind to async socket: " + bindAddr.describe(),
417 // Apply the additional options if any.
418 for (const auto& opt: options) {
419 int rv = opt.first.apply(fd_, opt.second);
421 auto errnoCopy = errno;
422 throw AsyncSocketException(
423 AsyncSocketException::INTERNAL_ERROR,
424 withAddr("failed to set socket option"),
429 // Perform the connect()
430 address.getAddress(&addrStorage);
432 rv = ::connect(fd_, saddr, address.getActualSize());
434 auto errnoCopy = errno;
435 if (errnoCopy == EINPROGRESS) {
436 // Connection in progress.
438 // Start a timer in case the connection takes too long.
439 if (!writeTimeout_.scheduleTimeout(timeout)) {
440 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
441 withAddr("failed to schedule AsyncSocket connect timeout"));
445 // Register for write events, so we'll
446 // be notified when the connection finishes/fails.
447 // Note that we don't register for a persistent event here.
448 assert(eventFlags_ == EventHandler::NONE);
449 eventFlags_ = EventHandler::WRITE;
450 if (!ioHandler_.registerHandler(eventFlags_)) {
451 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
452 withAddr("failed to register AsyncSocket connect handler"));
456 throw AsyncSocketException(
457 AsyncSocketException::NOT_OPEN,
458 "connect failed (immediately)",
463 // If we're still here the connect() succeeded immediately.
464 // Fall through to call the callback outside of this try...catch block
465 } catch (const AsyncSocketException& ex) {
466 return failConnect(__func__, ex);
467 } catch (const std::exception& ex) {
468 // shouldn't happen, but handle it just in case
469 VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
470 << "): unexpected " << typeid(ex).name() << " exception: "
472 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
473 withAddr(string("unexpected exception: ") +
475 return failConnect(__func__, tex);
478 // The connection succeeded immediately
479 // The read callback may not have been set yet, and no writes may be pending
480 // yet, so we don't have to register for any events at the moment.
481 VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
482 assert(readCallback_ == nullptr);
483 assert(writeReqHead_ == nullptr);
484 state_ = StateEnum::ESTABLISHED;
485 invokeConnectSuccess();
488 void AsyncSocket::connect(ConnectCallback* callback,
489 const string& ip, uint16_t port,
491 const OptionMap &options) noexcept {
492 DestructorGuard dg(this);
494 connectCallback_ = callback;
495 connect(callback, folly::SocketAddress(ip, port), timeout, options);
496 } catch (const std::exception& ex) {
497 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
499 return failConnect(__func__, tex);
503 void AsyncSocket::cancelConnect() {
504 connectCallback_ = nullptr;
505 if (state_ == StateEnum::CONNECTING) {
510 void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
511 sendTimeout_ = milliseconds;
512 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
514 // If we are currently pending on write requests, immediately update
515 // writeTimeout_ with the new value.
516 if ((eventFlags_ & EventHandler::WRITE) &&
517 (state_ != StateEnum::CONNECTING)) {
518 assert(state_ == StateEnum::ESTABLISHED);
519 assert((shutdownFlags_ & SHUT_WRITE) == 0);
520 if (sendTimeout_ > 0) {
521 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
522 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
523 withAddr("failed to reschedule send timeout in setSendTimeout"));
524 return failWrite(__func__, ex);
527 writeTimeout_.cancelTimeout();
532 void AsyncSocket::setReadCB(ReadCallback *callback) {
533 VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
534 << ", callback=" << callback << ", state=" << state_;
536 // Short circuit if callback is the same as the existing readCallback_.
538 // Note that this is needed for proper functioning during some cleanup cases.
539 // During cleanup we allow setReadCallback(nullptr) to be called even if the
540 // read callback is already unset and we have been detached from an event
541 // base. This check prevents us from asserting
542 // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
543 if (callback == readCallback_) {
547 /* We are removing a read callback */
548 if (callback == nullptr &&
549 immediateReadHandler_.isLoopCallbackScheduled()) {
550 immediateReadHandler_.cancelLoopCallback();
553 if (shutdownFlags_ & SHUT_READ) {
554 // Reads have already been shut down on this socket.
556 // Allow setReadCallback(nullptr) to be called in this case, but don't
557 // allow a new callback to be set.
559 // For example, setReadCallback(nullptr) can happen after an error if we
560 // invoke some other error callback before invoking readError(). The other
561 // error callback that is invoked first may go ahead and clear the read
562 // callback before we get a chance to invoke readError().
563 if (callback != nullptr) {
564 return invalidState(callback);
566 assert((eventFlags_ & EventHandler::READ) == 0);
567 readCallback_ = nullptr;
571 DestructorGuard dg(this);
572 assert(eventBase_->isInEventBaseThread());
574 switch ((StateEnum)state_) {
575 case StateEnum::CONNECTING:
576 // For convenience, we allow the read callback to be set while we are
577 // still connecting. We just store the callback for now. Once the
578 // connection completes we'll register for read events.
579 readCallback_ = callback;
581 case StateEnum::ESTABLISHED:
583 readCallback_ = callback;
584 uint16_t oldFlags = eventFlags_;
586 eventFlags_ |= EventHandler::READ;
588 eventFlags_ &= ~EventHandler::READ;
591 // Update our registration if our flags have changed
592 if (eventFlags_ != oldFlags) {
593 // We intentionally ignore the return value here.
594 // updateEventRegistration() will move us into the error state if it
595 // fails, and we don't need to do anything else here afterwards.
596 (void)updateEventRegistration();
600 checkForImmediateRead();
604 case StateEnum::CLOSED:
605 case StateEnum::ERROR:
606 // We should never reach here. SHUT_READ should always be set
607 // if we are in STATE_CLOSED or STATE_ERROR.
609 return invalidState(callback);
610 case StateEnum::UNINIT:
611 // We do not allow setReadCallback() to be called before we start
613 return invalidState(callback);
616 // We don't put a default case in the switch statement, so that the compiler
617 // will warn us to update the switch statement if a new state is added.
618 return invalidState(callback);
621 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
622 return readCallback_;
625 void AsyncSocket::write(WriteCallback* callback,
626 const void* buf, size_t bytes, WriteFlags flags) {
628 op.iov_base = const_cast<void*>(buf);
630 writeImpl(callback, &op, 1, unique_ptr<IOBuf>(), flags);
633 void AsyncSocket::writev(WriteCallback* callback,
637 writeImpl(callback, vec, count, unique_ptr<IOBuf>(), flags);
640 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
642 constexpr size_t kSmallSizeMax = 64;
643 size_t count = buf->countChainElements();
644 if (count <= kSmallSizeMax) {
645 iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA, count, kSmallSizeMax)];
646 writeChainImpl(callback, vec, count, std::move(buf), flags);
648 iovec* vec = new iovec[count];
649 writeChainImpl(callback, vec, count, std::move(buf), flags);
654 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
655 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
656 size_t veclen = buf->fillIov(vec, count);
657 writeImpl(callback, vec, veclen, std::move(buf), flags);
660 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
661 size_t count, unique_ptr<IOBuf>&& buf,
663 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
664 << ", callback=" << callback << ", count=" << count
665 << ", state=" << state_;
666 DestructorGuard dg(this);
667 unique_ptr<IOBuf>ioBuf(std::move(buf));
668 assert(eventBase_->isInEventBaseThread());
670 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
671 // No new writes may be performed after the write side of the socket has
674 // We could just call callback->writeError() here to fail just this write.
675 // However, fail hard and use invalidState() to fail all outstanding
676 // callbacks and move the socket into the error state. There's most likely
677 // a bug in the caller's code, so we abort everything rather than trying to
678 // proceed as best we can.
679 return invalidState(callback);
682 uint32_t countWritten = 0;
683 uint32_t partialWritten = 0;
684 int bytesWritten = 0;
685 bool mustRegister = false;
686 if (state_ == StateEnum::ESTABLISHED && !connecting()) {
687 if (writeReqHead_ == nullptr) {
688 // If we are established and there are no other writes pending,
689 // we can attempt to perform the write immediately.
690 assert(writeReqTail_ == nullptr);
691 assert((eventFlags_ & EventHandler::WRITE) == 0);
694 performWrite(vec, count, flags, &countWritten, &partialWritten);
695 bytesWritten = writeResult.writeReturn;
696 if (bytesWritten < 0) {
697 auto errnoCopy = errno;
698 if (writeResult.exception) {
699 return failWrite(__func__, callback, 0, *writeResult.exception);
701 AsyncSocketException ex(
702 AsyncSocketException::INTERNAL_ERROR,
703 withAddr("writev failed"),
705 return failWrite(__func__, callback, 0, ex);
706 } else if (countWritten == count) {
707 // We successfully wrote everything.
708 // Invoke the callback and return.
710 callback->writeSuccess();
713 } else { // continue writing the next writeReq
714 if (bufferCallback_) {
715 bufferCallback_->onEgressBuffered();
720 } else if (!connecting()) {
721 // Invalid state for writing
722 return invalidState(callback);
725 // Create a new WriteRequest to add to the queue
728 req = BytesWriteRequest::newRequest(this, callback, vec + countWritten,
729 count - countWritten, partialWritten,
730 bytesWritten, std::move(ioBuf), flags);
731 } catch (const std::exception& ex) {
732 // we mainly expect to catch std::bad_alloc here
733 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
734 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
735 return failWrite(__func__, callback, bytesWritten, tex);
738 if (writeReqTail_ == nullptr) {
739 assert(writeReqHead_ == nullptr);
740 writeReqHead_ = writeReqTail_ = req;
742 writeReqTail_->append(req);
746 // Register for write events if are established and not currently
747 // waiting on write events
749 assert(state_ == StateEnum::ESTABLISHED);
750 assert((eventFlags_ & EventHandler::WRITE) == 0);
751 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
752 assert(state_ == StateEnum::ERROR);
755 if (sendTimeout_ > 0) {
756 // Schedule a timeout to fire if the write takes too long.
757 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
758 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
759 withAddr("failed to schedule send timeout"));
760 return failWrite(__func__, ex);
766 void AsyncSocket::writeRequest(WriteRequest* req) {
767 if (writeReqTail_ == nullptr) {
768 assert(writeReqHead_ == nullptr);
769 writeReqHead_ = writeReqTail_ = req;
772 writeReqTail_->append(req);
777 void AsyncSocket::close() {
778 VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
779 << ", state=" << state_ << ", shutdownFlags="
780 << std::hex << (int) shutdownFlags_;
782 // close() is only different from closeNow() when there are pending writes
783 // that need to drain before we can close. In all other cases, just call
786 // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
787 // STATE_ERROR if close() is invoked while a previous closeNow() or failure
788 // is still running. (e.g., If there are multiple pending writes, and we
789 // call writeError() on the first one, it may call close(). In this case we
790 // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
791 // writes will still be in the queue.)
793 // We only need to drain pending writes if we are still in STATE_CONNECTING
794 // or STATE_ESTABLISHED
795 if ((writeReqHead_ == nullptr) ||
796 !(state_ == StateEnum::CONNECTING ||
797 state_ == StateEnum::ESTABLISHED)) {
802 // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
803 // destroyed until close() returns.
804 DestructorGuard dg(this);
805 assert(eventBase_->isInEventBaseThread());
807 // Since there are write requests pending, we have to set the
808 // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
809 // connect finishes and we finish writing these requests.
811 // Set SHUT_READ to indicate that reads are shut down, and set the
812 // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
813 // pending writes complete.
814 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
816 // If a read callback is set, invoke readEOF() immediately to inform it that
817 // the socket has been closed and no more data can be read.
819 // Disable reads if they are enabled
820 if (!updateEventRegistration(0, EventHandler::READ)) {
821 // We're now in the error state; callbacks have been cleaned up
822 assert(state_ == StateEnum::ERROR);
823 assert(readCallback_ == nullptr);
825 ReadCallback* callback = readCallback_;
826 readCallback_ = nullptr;
832 void AsyncSocket::closeNow() {
833 VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
834 << ", state=" << state_ << ", shutdownFlags="
835 << std::hex << (int) shutdownFlags_;
836 DestructorGuard dg(this);
837 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
840 case StateEnum::ESTABLISHED:
841 case StateEnum::CONNECTING:
843 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
844 state_ = StateEnum::CLOSED;
846 // If the write timeout was set, cancel it.
847 writeTimeout_.cancelTimeout();
849 // If we are registered for I/O events, unregister.
850 if (eventFlags_ != EventHandler::NONE) {
851 eventFlags_ = EventHandler::NONE;
852 if (!updateEventRegistration()) {
853 // We will have been moved into the error state.
854 assert(state_ == StateEnum::ERROR);
859 if (immediateReadHandler_.isLoopCallbackScheduled()) {
860 immediateReadHandler_.cancelLoopCallback();
864 ioHandler_.changeHandlerFD(-1);
868 invokeConnectErr(socketClosedLocallyEx);
870 failAllWrites(socketClosedLocallyEx);
873 ReadCallback* callback = readCallback_;
874 readCallback_ = nullptr;
879 case StateEnum::CLOSED:
880 // Do nothing. It's possible that we are being called recursively
881 // from inside a callback that we invoked inside another call to close()
882 // that is still running.
884 case StateEnum::ERROR:
885 // Do nothing. The error handling code has performed (or is performing)
888 case StateEnum::UNINIT:
889 assert(eventFlags_ == EventHandler::NONE);
890 assert(connectCallback_ == nullptr);
891 assert(readCallback_ == nullptr);
892 assert(writeReqHead_ == nullptr);
893 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
894 state_ = StateEnum::CLOSED;
898 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
899 << ") called in unknown state " << state_;
902 void AsyncSocket::closeWithReset() {
903 // Enable SO_LINGER, with the linger timeout set to 0.
904 // This will trigger a TCP reset when we close the socket.
906 struct linger optLinger = {1, 0};
907 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
908 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
909 << "on " << fd_ << ": errno=" << errno;
913 // Then let closeNow() take care of the rest
917 void AsyncSocket::shutdownWrite() {
918 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
919 << ", state=" << state_ << ", shutdownFlags="
920 << std::hex << (int) shutdownFlags_;
922 // If there are no pending writes, shutdownWrite() is identical to
923 // shutdownWriteNow().
924 if (writeReqHead_ == nullptr) {
929 assert(eventBase_->isInEventBaseThread());
931 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
932 // shutdown will be performed once all writes complete.
933 shutdownFlags_ |= SHUT_WRITE_PENDING;
936 void AsyncSocket::shutdownWriteNow() {
937 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
938 << ", fd=" << fd_ << ", state=" << state_
939 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
941 if (shutdownFlags_ & SHUT_WRITE) {
942 // Writes are already shutdown; nothing else to do.
946 // If SHUT_READ is already set, just call closeNow() to completely
947 // close the socket. This can happen if close() was called with writes
948 // pending, and then shutdownWriteNow() is called before all pending writes
950 if (shutdownFlags_ & SHUT_READ) {
955 DestructorGuard dg(this);
956 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
958 switch (static_cast<StateEnum>(state_)) {
959 case StateEnum::ESTABLISHED:
961 shutdownFlags_ |= SHUT_WRITE;
963 // If the write timeout was set, cancel it.
964 writeTimeout_.cancelTimeout();
966 // If we are registered for write events, unregister.
967 if (!updateEventRegistration(0, EventHandler::WRITE)) {
968 // We will have been moved into the error state.
969 assert(state_ == StateEnum::ERROR);
973 // Shutdown writes on the file descriptor
974 ::shutdown(fd_, SHUT_WR);
976 // Immediately fail all write requests
977 failAllWrites(socketShutdownForWritesEx);
980 case StateEnum::CONNECTING:
982 // Set the SHUT_WRITE_PENDING flag.
983 // When the connection completes, it will check this flag,
984 // shutdown the write half of the socket, and then set SHUT_WRITE.
985 shutdownFlags_ |= SHUT_WRITE_PENDING;
987 // Immediately fail all write requests
988 failAllWrites(socketShutdownForWritesEx);
991 case StateEnum::UNINIT:
992 // Callers normally shouldn't call shutdownWriteNow() before the socket
993 // even starts connecting. Nonetheless, go ahead and set
994 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
995 // immediately shut down the write side of the socket.
996 shutdownFlags_ |= SHUT_WRITE_PENDING;
998 case StateEnum::CLOSED:
999 case StateEnum::ERROR:
1000 // We should never get here. SHUT_WRITE should always be set
1001 // in STATE_CLOSED and STATE_ERROR.
1002 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
1003 << ", fd=" << fd_ << ") in unexpected state " << state_
1004 << " with SHUT_WRITE not set ("
1005 << std::hex << (int) shutdownFlags_ << ")";
1010 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
1011 << fd_ << ") called in unknown state " << state_;
1014 bool AsyncSocket::readable() const {
1018 struct pollfd fds[1];
1020 fds[0].events = POLLIN;
1022 int rc = poll(fds, 1, 0);
1026 bool AsyncSocket::isPending() const {
1027 return ioHandler_.isPending();
1030 bool AsyncSocket::hangup() const {
1032 // sanity check, no one should ask for hangup if we are not connected.
1036 #ifdef POLLRDHUP // Linux-only
1037 struct pollfd fds[1];
1039 fds[0].events = POLLRDHUP|POLLHUP;
1042 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1048 bool AsyncSocket::good() const {
1049 return ((state_ == StateEnum::CONNECTING ||
1050 state_ == StateEnum::ESTABLISHED) &&
1051 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1054 bool AsyncSocket::error() const {
1055 return (state_ == StateEnum::ERROR);
1058 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1059 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1060 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1061 << ", state=" << state_ << ", events="
1062 << std::hex << eventFlags_ << ")";
1063 assert(eventBase_ == nullptr);
1064 assert(eventBase->isInEventBaseThread());
1066 eventBase_ = eventBase;
1067 ioHandler_.attachEventBase(eventBase);
1068 writeTimeout_.attachEventBase(eventBase);
1071 void AsyncSocket::detachEventBase() {
1072 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1073 << ", old evb=" << eventBase_ << ", state=" << state_
1074 << ", events=" << std::hex << eventFlags_ << ")";
1075 assert(eventBase_ != nullptr);
1076 assert(eventBase_->isInEventBaseThread());
1078 eventBase_ = nullptr;
1079 ioHandler_.detachEventBase();
1080 writeTimeout_.detachEventBase();
1083 bool AsyncSocket::isDetachable() const {
1084 DCHECK(eventBase_ != nullptr);
1085 DCHECK(eventBase_->isInEventBaseThread());
1087 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1090 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1091 if (!localAddr_.isInitialized()) {
1092 localAddr_.setFromLocalAddress(fd_);
1094 *address = localAddr_;
1097 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1098 if (!addr_.isInitialized()) {
1099 addr_.setFromPeerAddress(fd_);
1104 int AsyncSocket::setNoDelay(bool noDelay) {
1106 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1107 << this << "(state=" << state_ << ")";
1112 int value = noDelay ? 1 : 0;
1113 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1114 int errnoCopy = errno;
1115 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1116 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1117 << strerror(errnoCopy);
1124 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1126 #ifndef TCP_CONGESTION
1127 #define TCP_CONGESTION 13
1131 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1132 << "socket " << this << "(state=" << state_ << ")";
1137 if (setsockopt(fd_, IPPROTO_TCP, TCP_CONGESTION, cname.c_str(),
1138 cname.length() + 1) != 0) {
1139 int errnoCopy = errno;
1140 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1141 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1142 << strerror(errnoCopy);
1149 int AsyncSocket::setQuickAck(bool quickack) {
1151 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1152 << this << "(state=" << state_ << ")";
1157 #ifdef TCP_QUICKACK // Linux-only
1158 int value = quickack ? 1 : 0;
1159 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1160 int errnoCopy = errno;
1161 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1162 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1163 << strerror(errnoCopy);
1173 int AsyncSocket::setSendBufSize(size_t bufsize) {
1175 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1176 << this << "(state=" << state_ << ")";
1180 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1181 int errnoCopy = errno;
1182 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1183 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1184 << strerror(errnoCopy);
1191 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1193 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1194 << this << "(state=" << state_ << ")";
1198 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1199 int errnoCopy = errno;
1200 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1201 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1202 << strerror(errnoCopy);
1209 int AsyncSocket::setTCPProfile(int profd) {
1211 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1212 << this << "(state=" << state_ << ")";
1216 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1217 int errnoCopy = errno;
1218 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1219 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1220 << strerror(errnoCopy);
1227 void AsyncSocket::ioReady(uint16_t events) noexcept {
1228 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd" << fd_
1229 << ", events=" << std::hex << events << ", state=" << state_;
1230 DestructorGuard dg(this);
1231 assert(events & EventHandler::READ_WRITE);
1232 assert(eventBase_->isInEventBaseThread());
1234 uint16_t relevantEvents = events & EventHandler::READ_WRITE;
1235 if (relevantEvents == EventHandler::READ) {
1237 } else if (relevantEvents == EventHandler::WRITE) {
1239 } else if (relevantEvents == EventHandler::READ_WRITE) {
1240 EventBase* originalEventBase = eventBase_;
1241 // If both read and write events are ready, process writes first.
1244 // Return now if handleWrite() detached us from our EventBase
1245 if (eventBase_ != originalEventBase) {
1249 // Only call handleRead() if a read callback is still installed.
1250 // (It's possible that the read callback was uninstalled during
1252 if (readCallback_) {
1256 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1257 << std::hex << events << "(this=" << this << ")";
1262 AsyncSocket::ReadResult
1263 AsyncSocket::performRead(void** buf, size_t* buflen, size_t* /* offset */) {
1264 VLOG(5) << "AsyncSocket::performRead() this=" << this << ", buf=" << *buf
1265 << ", buflen=" << *buflen;
1269 recvFlags |= MSG_PEEK;
1272 ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT | recvFlags);
1274 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1275 // No more data to read right now.
1276 return ReadResult(READ_BLOCKING);
1278 return ReadResult(READ_ERROR);
1281 appBytesReceived_ += bytes;
1282 return ReadResult(bytes);
1286 void AsyncSocket::prepareReadBuffer(void** buf, size_t* buflen) noexcept {
1287 // no matter what, buffer should be preapared for non-ssl socket
1288 CHECK(readCallback_);
1289 readCallback_->getReadBuffer(buf, buflen);
1292 void AsyncSocket::handleRead() noexcept {
1293 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1294 << ", state=" << state_;
1295 assert(state_ == StateEnum::ESTABLISHED);
1296 assert((shutdownFlags_ & SHUT_READ) == 0);
1297 assert(readCallback_ != nullptr);
1298 assert(eventFlags_ & EventHandler::READ);
1301 // - a read attempt would block
1302 // - readCallback_ is uninstalled
1303 // - the number of loop iterations exceeds the optional maximum
1304 // - this AsyncSocket is moved to another EventBase
1306 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1307 // which is why need to check for it here.
1309 // The last bullet point is slightly subtle. readDataAvailable() may also
1310 // detach this socket from this EventBase. However, before
1311 // readDataAvailable() returns another thread may pick it up, attach it to
1312 // a different EventBase, and install another readCallback_. We need to
1313 // exit immediately after readDataAvailable() returns if the eventBase_ has
1314 // changed. (The caller must perform some sort of locking to transfer the
1315 // AsyncSocket between threads properly. This will be sufficient to ensure
1316 // that this thread sees the updated eventBase_ variable after
1317 // readDataAvailable() returns.)
1318 uint16_t numReads = 0;
1319 EventBase* originalEventBase = eventBase_;
1320 while (readCallback_ && eventBase_ == originalEventBase) {
1321 // Get the buffer to read into.
1322 void* buf = nullptr;
1323 size_t buflen = 0, offset = 0;
1325 prepareReadBuffer(&buf, &buflen);
1326 VLOG(5) << "prepareReadBuffer() buf=" << buf << ", buflen=" << buflen;
1327 } catch (const AsyncSocketException& ex) {
1328 return failRead(__func__, ex);
1329 } catch (const std::exception& ex) {
1330 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1331 string("ReadCallback::getReadBuffer() "
1332 "threw exception: ") +
1334 return failRead(__func__, tex);
1336 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1337 "ReadCallback::getReadBuffer() threw "
1338 "non-exception type");
1339 return failRead(__func__, ex);
1341 if (!isBufferMovable_ && (buf == nullptr || buflen == 0)) {
1342 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1343 "ReadCallback::getReadBuffer() returned "
1345 return failRead(__func__, ex);
1349 auto readResult = performRead(&buf, &buflen, &offset);
1350 auto bytesRead = readResult.readReturn;
1351 VLOG(4) << "this=" << this << ", AsyncSocket::handleRead() got "
1352 << bytesRead << " bytes";
1353 if (bytesRead > 0) {
1354 if (!isBufferMovable_) {
1355 readCallback_->readDataAvailable(bytesRead);
1357 CHECK(kOpenSslModeMoveBufferOwnership);
1358 VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
1359 << "buf=" << buf << ", " << bytesRead << "/" << buflen
1360 << ", offset=" << offset;
1361 auto readBuf = folly::IOBuf::takeOwnership(buf, buflen);
1362 readBuf->trimStart(offset);
1363 readBuf->trimEnd(buflen - offset - bytesRead);
1364 readCallback_->readBufferAvailable(std::move(readBuf));
1367 // Fall through and continue around the loop if the read
1368 // completely filled the available buffer.
1369 // Note that readCallback_ may have been uninstalled or changed inside
1370 // readDataAvailable().
1371 if (size_t(bytesRead) < buflen) {
1374 } else if (bytesRead == READ_BLOCKING) {
1375 // No more data to read right now.
1377 } else if (bytesRead == READ_ERROR) {
1378 readErr_ = READ_ERROR;
1379 if (readResult.exception) {
1380 return failRead(__func__, *readResult.exception);
1382 auto errnoCopy = errno;
1383 AsyncSocketException ex(
1384 AsyncSocketException::INTERNAL_ERROR,
1385 withAddr("recv() failed"),
1387 return failRead(__func__, ex);
1389 assert(bytesRead == READ_EOF);
1390 readErr_ = READ_EOF;
1392 shutdownFlags_ |= SHUT_READ;
1393 if (!updateEventRegistration(0, EventHandler::READ)) {
1394 // we've already been moved into STATE_ERROR
1395 assert(state_ == StateEnum::ERROR);
1396 assert(readCallback_ == nullptr);
1400 ReadCallback* callback = readCallback_;
1401 readCallback_ = nullptr;
1402 callback->readEOF();
1405 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1406 if (readCallback_ != nullptr) {
1407 // We might still have data in the socket.
1408 // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
1409 scheduleImmediateRead();
1417 * This function attempts to write as much data as possible, until no more data
1420 * - If it sends all available data, it unregisters for write events, and stops
1421 * the writeTimeout_.
1423 * - If not all of the data can be sent immediately, it reschedules
1424 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1425 * registered for write events.
1427 void AsyncSocket::handleWrite() noexcept {
1428 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1429 << ", state=" << state_;
1430 DestructorGuard dg(this);
1432 if (state_ == StateEnum::CONNECTING) {
1438 assert(state_ == StateEnum::ESTABLISHED);
1439 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1440 assert(writeReqHead_ != nullptr);
1442 // Loop until we run out of write requests,
1443 // or until this socket is moved to another EventBase.
1444 // (See the comment in handleRead() explaining how this can happen.)
1445 EventBase* originalEventBase = eventBase_;
1446 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1447 auto writeResult = writeReqHead_->performWrite();
1448 if (writeResult.writeReturn < 0) {
1449 if (writeResult.exception) {
1450 return failWrite(__func__, *writeResult.exception);
1452 auto errnoCopy = errno;
1453 AsyncSocketException ex(
1454 AsyncSocketException::INTERNAL_ERROR,
1455 withAddr("writev() failed"),
1457 return failWrite(__func__, ex);
1458 } else if (writeReqHead_->isComplete()) {
1459 // We finished this request
1460 WriteRequest* req = writeReqHead_;
1461 writeReqHead_ = req->getNext();
1463 if (writeReqHead_ == nullptr) {
1464 writeReqTail_ = nullptr;
1465 // This is the last write request.
1466 // Unregister for write events and cancel the send timer
1467 // before we invoke the callback. We have to update the state properly
1468 // before calling the callback, since it may want to detach us from
1470 if (eventFlags_ & EventHandler::WRITE) {
1471 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1472 assert(state_ == StateEnum::ERROR);
1475 // Stop the send timeout
1476 writeTimeout_.cancelTimeout();
1478 assert(!writeTimeout_.isScheduled());
1480 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
1481 // we finish sending the last write request.
1483 // We have to do this before invoking writeSuccess(), since
1484 // writeSuccess() may detach us from our EventBase.
1485 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
1486 assert(connectCallback_ == nullptr);
1487 shutdownFlags_ |= SHUT_WRITE;
1489 if (shutdownFlags_ & SHUT_READ) {
1490 // Reads have already been shutdown. Fully close the socket and
1491 // move to STATE_CLOSED.
1493 // Note: This code currently moves us to STATE_CLOSED even if
1494 // close() hasn't ever been called. This can occur if we have
1495 // received EOF from the peer and shutdownWrite() has been called
1496 // locally. Should we bother staying in STATE_ESTABLISHED in this
1497 // case, until close() is actually called? I can't think of a
1498 // reason why we would need to do so. No other operations besides
1499 // calling close() or destroying the socket can be performed at
1501 assert(readCallback_ == nullptr);
1502 state_ = StateEnum::CLOSED;
1504 ioHandler_.changeHandlerFD(-1);
1508 // Reads are still enabled, so we are only doing a half-shutdown
1509 ::shutdown(fd_, SHUT_WR);
1514 // Invoke the callback
1515 WriteCallback* callback = req->getCallback();
1518 callback->writeSuccess();
1520 // We'll continue around the loop, trying to write another request
1523 if (bufferCallback_) {
1524 bufferCallback_->onEgressBuffered();
1526 writeReqHead_->consume();
1527 // Stop after a partial write; it's highly likely that a subsequent write
1528 // attempt will just return EAGAIN.
1530 // Ensure that we are registered for write events.
1531 if ((eventFlags_ & EventHandler::WRITE) == 0) {
1532 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1533 assert(state_ == StateEnum::ERROR);
1538 // Reschedule the send timeout, since we have made some write progress.
1539 if (sendTimeout_ > 0) {
1540 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1541 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1542 withAddr("failed to reschedule write timeout"));
1543 return failWrite(__func__, ex);
1549 if (!writeReqHead_ && bufferCallback_) {
1550 bufferCallback_->onEgressBufferCleared();
1554 void AsyncSocket::checkForImmediateRead() noexcept {
1555 // We currently don't attempt to perform optimistic reads in AsyncSocket.
1556 // (However, note that some subclasses do override this method.)
1558 // Simply calling handleRead() here would be bad, as this would call
1559 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
1560 // buffer even though no data may be available. This would waste lots of
1561 // memory, since the buffer will sit around unused until the socket actually
1562 // becomes readable.
1564 // Checking if the socket is readable now also seems like it would probably
1565 // be a pessimism. In most cases it probably wouldn't be readable, and we
1566 // would just waste an extra system call. Even if it is readable, waiting to
1567 // find out from libevent on the next event loop doesn't seem that bad.
1570 void AsyncSocket::handleInitialReadWrite() noexcept {
1571 // Our callers should already be holding a DestructorGuard, but grab
1572 // one here just to make sure, in case one of our calling code paths ever
1574 DestructorGuard dg(this);
1576 // If we have a readCallback_, make sure we enable read events. We
1577 // may already be registered for reads if connectSuccess() set
1578 // the read calback.
1579 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
1580 assert(state_ == StateEnum::ESTABLISHED);
1581 assert((shutdownFlags_ & SHUT_READ) == 0);
1582 if (!updateEventRegistration(EventHandler::READ, 0)) {
1583 assert(state_ == StateEnum::ERROR);
1586 checkForImmediateRead();
1587 } else if (readCallback_ == nullptr) {
1588 // Unregister for read events.
1589 updateEventRegistration(0, EventHandler::READ);
1592 // If we have write requests pending, try to send them immediately.
1593 // Since we just finished accepting, there is a very good chance that we can
1594 // write without blocking.
1596 // However, we only process them if EventHandler::WRITE is not already set,
1597 // which means that we're already blocked on a write attempt. (This can
1598 // happen if connectSuccess() called write() before returning.)
1599 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
1600 // Call handleWrite() to perform write processing.
1602 } else if (writeReqHead_ == nullptr) {
1603 // Unregister for write event.
1604 updateEventRegistration(0, EventHandler::WRITE);
1608 void AsyncSocket::handleConnect() noexcept {
1609 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
1610 << ", state=" << state_;
1611 assert(state_ == StateEnum::CONNECTING);
1612 // SHUT_WRITE can never be set while we are still connecting;
1613 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
1615 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1617 // In case we had a connect timeout, cancel the timeout
1618 writeTimeout_.cancelTimeout();
1619 // We don't use a persistent registration when waiting on a connect event,
1620 // so we have been automatically unregistered now. Update eventFlags_ to
1622 assert(eventFlags_ == EventHandler::WRITE);
1623 eventFlags_ = EventHandler::NONE;
1625 // Call getsockopt() to check if the connect succeeded
1627 socklen_t len = sizeof(error);
1628 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
1630 auto errnoCopy = errno;
1631 AsyncSocketException ex(
1632 AsyncSocketException::INTERNAL_ERROR,
1633 withAddr("error calling getsockopt() after connect"),
1635 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1636 << fd_ << " host=" << addr_.describe()
1637 << ") exception:" << ex.what();
1638 return failConnect(__func__, ex);
1642 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1643 "connect failed", error);
1644 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1645 << fd_ << " host=" << addr_.describe()
1646 << ") exception: " << ex.what();
1647 return failConnect(__func__, ex);
1650 // Move into STATE_ESTABLISHED
1651 state_ = StateEnum::ESTABLISHED;
1653 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
1654 // perform, immediately shutdown the write half of the socket.
1655 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
1656 // SHUT_READ shouldn't be set. If close() is called on the socket while we
1657 // are still connecting we just abort the connect rather than waiting for
1659 assert((shutdownFlags_ & SHUT_READ) == 0);
1660 ::shutdown(fd_, SHUT_WR);
1661 shutdownFlags_ |= SHUT_WRITE;
1664 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
1665 << "successfully connected; state=" << state_;
1667 // Remember the EventBase we are attached to, before we start invoking any
1668 // callbacks (since the callbacks may call detachEventBase()).
1669 EventBase* originalEventBase = eventBase_;
1671 invokeConnectSuccess();
1672 // Note that the connect callback may have changed our state.
1673 // (set or unset the read callback, called write(), closed the socket, etc.)
1674 // The following code needs to handle these situations correctly.
1676 // If the socket has been closed, readCallback_ and writeReqHead_ will
1677 // always be nullptr, so that will prevent us from trying to read or write.
1679 // The main thing to check for is if eventBase_ is still originalEventBase.
1680 // If not, we have been detached from this event base, so we shouldn't
1681 // perform any more operations.
1682 if (eventBase_ != originalEventBase) {
1686 handleInitialReadWrite();
1689 void AsyncSocket::timeoutExpired() noexcept {
1690 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
1691 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
1692 DestructorGuard dg(this);
1693 assert(eventBase_->isInEventBaseThread());
1695 if (state_ == StateEnum::CONNECTING) {
1696 // connect() timed out
1697 // Unregister for I/O events.
1698 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
1699 "connect timed out");
1700 failConnect(__func__, ex);
1702 // a normal write operation timed out
1703 assert(state_ == StateEnum::ESTABLISHED);
1704 AsyncSocketException ex(AsyncSocketException::TIMED_OUT, "write timed out");
1705 failWrite(__func__, ex);
1709 AsyncSocket::WriteResult AsyncSocket::performWrite(
1713 uint32_t* countWritten,
1714 uint32_t* partialWritten) {
1715 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
1716 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
1717 // (since it may terminate the program if the main program doesn't explicitly
1720 msg.msg_name = nullptr;
1721 msg.msg_namelen = 0;
1722 msg.msg_iov = const_cast<iovec *>(vec);
1723 msg.msg_iovlen = std::min<size_t>(count, kIovMax);
1724 msg.msg_control = nullptr;
1725 msg.msg_controllen = 0;
1728 int msg_flags = MSG_DONTWAIT;
1730 #ifdef MSG_NOSIGNAL // Linux-only
1731 msg_flags |= MSG_NOSIGNAL;
1732 if (isSet(flags, WriteFlags::CORK)) {
1733 // MSG_MORE tells the kernel we have more data to send, so wait for us to
1734 // give it the rest of the data rather than immediately sending a partial
1735 // frame, even when TCP_NODELAY is enabled.
1736 msg_flags |= MSG_MORE;
1739 if (isSet(flags, WriteFlags::EOR)) {
1740 // marks that this is the last byte of a record (response)
1741 msg_flags |= MSG_EOR;
1743 ssize_t totalWritten = ::sendmsg(fd_, &msg, msg_flags);
1744 if (totalWritten < 0) {
1745 if (errno == EAGAIN) {
1746 // TCP buffer is full; we can't write any more data right now.
1748 *partialWritten = 0;
1749 return WriteResult(0);
1753 *partialWritten = 0;
1754 return WriteResult(WRITE_ERROR);
1757 appBytesWritten_ += totalWritten;
1759 uint32_t bytesWritten;
1761 for (bytesWritten = totalWritten, n = 0; n < count; ++n) {
1762 const iovec* v = vec + n;
1763 if (v->iov_len > bytesWritten) {
1764 // Partial write finished in the middle of this iovec
1766 *partialWritten = bytesWritten;
1767 return WriteResult(totalWritten);
1770 bytesWritten -= v->iov_len;
1773 assert(bytesWritten == 0);
1775 *partialWritten = 0;
1776 return WriteResult(totalWritten);
1780 * Re-register the EventHandler after eventFlags_ has changed.
1782 * If an error occurs, fail() is called to move the socket into the error state
1783 * and call all currently installed callbacks. After an error, the
1784 * AsyncSocket is completely unregistered.
1786 * @return Returns true on succcess, or false on error.
1788 bool AsyncSocket::updateEventRegistration() {
1789 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
1790 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
1791 << ", events=" << std::hex << eventFlags_;
1792 assert(eventBase_->isInEventBaseThread());
1793 if (eventFlags_ == EventHandler::NONE) {
1794 ioHandler_.unregisterHandler();
1798 // Always register for persistent events, so we don't have to re-register
1799 // after being called back.
1800 if (!ioHandler_.registerHandler(eventFlags_ | EventHandler::PERSIST)) {
1801 eventFlags_ = EventHandler::NONE; // we're not registered after error
1802 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1803 withAddr("failed to update AsyncSocket event registration"));
1804 fail("updateEventRegistration", ex);
1811 bool AsyncSocket::updateEventRegistration(uint16_t enable,
1813 uint16_t oldFlags = eventFlags_;
1814 eventFlags_ |= enable;
1815 eventFlags_ &= ~disable;
1816 if (eventFlags_ == oldFlags) {
1819 return updateEventRegistration();
1823 void AsyncSocket::startFail() {
1824 // startFail() should only be called once
1825 assert(state_ != StateEnum::ERROR);
1826 assert(getDestructorGuardCount() > 0);
1827 state_ = StateEnum::ERROR;
1828 // Ensure that SHUT_READ and SHUT_WRITE are set,
1829 // so all future attempts to read or write will be rejected
1830 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1832 if (eventFlags_ != EventHandler::NONE) {
1833 eventFlags_ = EventHandler::NONE;
1834 ioHandler_.unregisterHandler();
1836 writeTimeout_.cancelTimeout();
1839 ioHandler_.changeHandlerFD(-1);
1844 void AsyncSocket::finishFail() {
1845 assert(state_ == StateEnum::ERROR);
1846 assert(getDestructorGuardCount() > 0);
1848 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1849 withAddr("socket closing after error"));
1850 invokeConnectErr(ex);
1853 if (readCallback_) {
1854 ReadCallback* callback = readCallback_;
1855 readCallback_ = nullptr;
1856 callback->readErr(ex);
1860 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
1861 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1862 << state_ << " host=" << addr_.describe()
1863 << "): failed in " << fn << "(): "
1869 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
1870 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1871 << state_ << " host=" << addr_.describe()
1872 << "): failed while connecting in " << fn << "(): "
1876 invokeConnectErr(ex);
1880 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
1881 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1882 << state_ << " host=" << addr_.describe()
1883 << "): failed while reading in " << fn << "(): "
1887 if (readCallback_ != nullptr) {
1888 ReadCallback* callback = readCallback_;
1889 readCallback_ = nullptr;
1890 callback->readErr(ex);
1896 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
1897 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1898 << state_ << " host=" << addr_.describe()
1899 << "): failed while writing in " << fn << "(): "
1903 // Only invoke the first write callback, since the error occurred while
1904 // writing this request. Let any other pending write callbacks be invoked in
1906 if (writeReqHead_ != nullptr) {
1907 WriteRequest* req = writeReqHead_;
1908 writeReqHead_ = req->getNext();
1909 WriteCallback* callback = req->getCallback();
1910 uint32_t bytesWritten = req->getTotalBytesWritten();
1913 callback->writeErr(bytesWritten, ex);
1920 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
1921 size_t bytesWritten,
1922 const AsyncSocketException& ex) {
1923 // This version of failWrite() is used when the failure occurs before
1924 // we've added the callback to writeReqHead_.
1925 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1926 << state_ << " host=" << addr_.describe()
1927 <<"): failed while writing in " << fn << "(): "
1931 if (callback != nullptr) {
1932 callback->writeErr(bytesWritten, ex);
1938 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
1939 // Invoke writeError() on all write callbacks.
1940 // This is used when writes are forcibly shutdown with write requests
1941 // pending, or when an error occurs with writes pending.
1942 while (writeReqHead_ != nullptr) {
1943 WriteRequest* req = writeReqHead_;
1944 writeReqHead_ = req->getNext();
1945 WriteCallback* callback = req->getCallback();
1947 callback->writeErr(req->getTotalBytesWritten(), ex);
1953 void AsyncSocket::invalidState(ConnectCallback* callback) {
1954 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
1955 << "): connect() called in invalid state " << state_;
1958 * The invalidState() methods don't use the normal failure mechanisms,
1959 * since we don't know what state we are in. We don't want to call
1960 * startFail()/finishFail() recursively if we are already in the middle of
1964 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
1965 "connect() called with socket in invalid state");
1966 connectEndTime_ = std::chrono::steady_clock::now();
1967 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1969 callback->connectErr(ex);
1972 // We can't use failConnect() here since connectCallback_
1973 // may already be set to another callback. Invoke this ConnectCallback
1974 // here; any other connectCallback_ will be invoked in finishFail()
1977 callback->connectErr(ex);
1983 void AsyncSocket::invokeConnectErr(const AsyncSocketException& ex) {
1984 connectEndTime_ = std::chrono::steady_clock::now();
1985 if (connectCallback_) {
1986 ConnectCallback* callback = connectCallback_;
1987 connectCallback_ = nullptr;
1988 callback->connectErr(ex);
1992 void AsyncSocket::invokeConnectSuccess() {
1993 connectEndTime_ = std::chrono::steady_clock::now();
1994 if (connectCallback_) {
1995 ConnectCallback* callback = connectCallback_;
1996 connectCallback_ = nullptr;
1997 callback->connectSuccess();
2001 void AsyncSocket::invalidState(ReadCallback* callback) {
2002 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2003 << "): setReadCallback(" << callback
2004 << ") called in invalid state " << state_;
2006 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2007 "setReadCallback() called with socket in "
2009 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2011 callback->readErr(ex);
2016 callback->readErr(ex);
2022 void AsyncSocket::invalidState(WriteCallback* callback) {
2023 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2024 << "): write() called in invalid state " << state_;
2026 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2027 withAddr("write() called with socket in invalid state"));
2028 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2030 callback->writeErr(0, ex);
2035 callback->writeErr(0, ex);
2041 void AsyncSocket::doClose() {
2042 if (fd_ == -1) return;
2043 if (shutdownSocketSet_) {
2044 shutdownSocketSet_->close(fd_);
2051 std::ostream& operator << (std::ostream& os,
2052 const AsyncSocket::StateEnum& state) {
2053 os << static_cast<int>(state);
2057 std::string AsyncSocket::withAddr(const std::string& s) {
2058 // Don't use addr_ directly because it may not be initialized
2059 // e.g. if constructed from fd
2060 folly::SocketAddress peer, local;
2062 getPeerAddress(&peer);
2063 getLocalAddress(&local);
2064 } catch (const std::exception&) {
2069 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";
2072 void AsyncSocket::setBufferCallback(BufferCallback* cb) {
2073 bufferCallback_ = cb;