2 * Copyright 2015 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>
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <netinet/in.h>
33 #include <netinet/tcp.h>
34 #include <boost/preprocessor/control/if.hpp>
37 using std::unique_ptr;
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 bool performWrite() override {
94 WriteFlags writeFlags = flags_;
95 if (getNext() != nullptr) {
96 writeFlags = writeFlags | WriteFlags::CORK;
98 bytesWritten_ = socket_->performWrite(getOps(), getOpCount(), writeFlags,
99 &opsWritten_, &partialBytes_);
100 return bytesWritten_ >= 0;
103 bool isComplete() override {
104 return opsWritten_ == getOpCount();
107 void consume() override {
108 // Advance opIndex_ forward by opsWritten_
109 opIndex_ += opsWritten_;
110 assert(opIndex_ < opCount_);
112 // If we've finished writing any IOBufs, release them
114 for (uint32_t i = opsWritten_; i != 0; --i) {
116 ioBuf_ = ioBuf_->pop();
120 // Move partialBytes_ forward into the current iovec buffer
121 struct iovec* currentOp = writeOps_ + opIndex_;
122 assert((partialBytes_ < currentOp->iov_len) || (currentOp->iov_len == 0));
123 currentOp->iov_base =
124 reinterpret_cast<uint8_t*>(currentOp->iov_base) + partialBytes_;
125 currentOp->iov_len -= partialBytes_;
127 // Increment the totalBytesWritten_ count by bytesWritten_;
128 totalBytesWritten_ += bytesWritten_;
132 BytesWriteRequest(AsyncSocket* socket,
133 WriteCallback* callback,
134 const struct iovec* ops,
136 uint32_t partialBytes,
137 uint32_t bytesWritten,
138 unique_ptr<IOBuf>&& ioBuf,
140 : AsyncSocket::WriteRequest(socket, callback)
144 , ioBuf_(std::move(ioBuf))
146 , partialBytes_(partialBytes)
147 , bytesWritten_(bytesWritten) {
148 memcpy(writeOps_, ops, sizeof(*ops) * opCount_);
151 // private destructor, to ensure callers use destroy()
152 ~BytesWriteRequest() override = default;
154 const struct iovec* getOps() const {
155 assert(opCount_ > opIndex_);
156 return writeOps_ + opIndex_;
159 uint32_t getOpCount() const {
160 assert(opCount_ > opIndex_);
161 return opCount_ - opIndex_;
164 uint32_t opCount_; ///< number of entries in writeOps_
165 uint32_t opIndex_; ///< current index into writeOps_
166 WriteFlags flags_; ///< set for WriteFlags
167 unique_ptr<IOBuf> ioBuf_; ///< underlying IOBuf, or nullptr if N/A
169 // for consume(), how much we wrote on the last write
170 uint32_t opsWritten_; ///< complete ops written
171 uint32_t partialBytes_; ///< partial bytes of incomplete op written
172 ssize_t bytesWritten_; ///< bytes written altogether
174 struct iovec writeOps_[]; ///< write operation(s) list
177 AsyncSocket::AsyncSocket()
178 : eventBase_(nullptr)
179 , writeTimeout_(this, nullptr)
180 , ioHandler_(this, nullptr)
181 , immediateReadHandler_(this) {
182 VLOG(5) << "new AsyncSocket()";
186 AsyncSocket::AsyncSocket(EventBase* evb)
188 , writeTimeout_(this, evb)
189 , ioHandler_(this, evb)
190 , immediateReadHandler_(this) {
191 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
195 AsyncSocket::AsyncSocket(EventBase* evb,
196 const folly::SocketAddress& address,
197 uint32_t connectTimeout)
199 connect(nullptr, address, connectTimeout);
202 AsyncSocket::AsyncSocket(EventBase* evb,
203 const std::string& ip,
205 uint32_t connectTimeout)
207 connect(nullptr, ip, port, connectTimeout);
210 AsyncSocket::AsyncSocket(EventBase* evb, int fd)
212 , writeTimeout_(this, evb)
213 , ioHandler_(this, evb, fd)
214 , immediateReadHandler_(this) {
215 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ", fd="
220 state_ = StateEnum::ESTABLISHED;
223 // init() method, since constructor forwarding isn't supported in most
225 void AsyncSocket::init() {
226 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
228 state_ = StateEnum::UNINIT;
229 eventFlags_ = EventHandler::NONE;
232 maxReadsPerEvent_ = 16;
233 connectCallback_ = nullptr;
234 readCallback_ = nullptr;
235 writeReqHead_ = nullptr;
236 writeReqTail_ = nullptr;
237 shutdownSocketSet_ = nullptr;
238 appBytesWritten_ = 0;
239 appBytesReceived_ = 0;
242 AsyncSocket::~AsyncSocket() {
243 VLOG(7) << "actual destruction of AsyncSocket(this=" << this
244 << ", evb=" << eventBase_ << ", fd=" << fd_
245 << ", state=" << state_ << ")";
248 void AsyncSocket::destroy() {
249 VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
250 << ", fd=" << fd_ << ", state=" << state_;
251 // When destroy is called, close the socket immediately
254 // Then call DelayedDestruction::destroy() to take care of
255 // whether or not we need immediate or delayed destruction
256 DelayedDestruction::destroy();
259 int AsyncSocket::detachFd() {
260 VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
261 << ", evb=" << eventBase_ << ", state=" << state_
262 << ", events=" << std::hex << eventFlags_ << ")";
263 // Extract the fd, and set fd_ to -1 first, so closeNow() won't
264 // actually close the descriptor.
265 if (shutdownSocketSet_) {
266 shutdownSocketSet_->remove(fd_);
270 // Call closeNow() to invoke all pending callbacks with an error.
272 // Update the EventHandler to stop using this fd.
273 // This can only be done after closeNow() unregisters the handler.
274 ioHandler_.changeHandlerFD(-1);
278 const folly::SocketAddress& AsyncSocket::anyAddress() {
279 static const folly::SocketAddress anyAddress =
280 folly::SocketAddress("0.0.0.0", 0);
284 void AsyncSocket::setShutdownSocketSet(ShutdownSocketSet* newSS) {
285 if (shutdownSocketSet_ == newSS) {
288 if (shutdownSocketSet_ && fd_ != -1) {
289 shutdownSocketSet_->remove(fd_);
291 shutdownSocketSet_ = newSS;
292 if (shutdownSocketSet_ && fd_ != -1) {
293 shutdownSocketSet_->add(fd_);
297 void AsyncSocket::setCloseOnExec() {
298 int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
300 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
301 withAddr("failed to set close-on-exec flag"),
306 void AsyncSocket::connect(ConnectCallback* callback,
307 const folly::SocketAddress& address,
309 const OptionMap &options,
310 const folly::SocketAddress& bindAddr) noexcept {
311 DestructorGuard dg(this);
312 assert(eventBase_->isInEventBaseThread());
316 // Make sure we're in the uninitialized state
317 if (state_ != StateEnum::UNINIT) {
318 return invalidState(callback);
322 state_ = StateEnum::CONNECTING;
323 connectCallback_ = callback;
325 sockaddr_storage addrStorage;
326 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
330 // Technically the first parameter should actually be a protocol family
331 // constant (PF_xxx) rather than an address family (AF_xxx), but the
332 // distinction is mainly just historical. In pretty much all
333 // implementations the PF_foo and AF_foo constants are identical.
334 fd_ = socket(address.getFamily(), SOCK_STREAM, 0);
336 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
337 withAddr("failed to create socket"), errno);
339 if (shutdownSocketSet_) {
340 shutdownSocketSet_->add(fd_);
342 ioHandler_.changeHandlerFD(fd_);
346 // Put the socket in non-blocking mode
347 int flags = fcntl(fd_, F_GETFL, 0);
349 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
350 withAddr("failed to get socket flags"), errno);
352 int rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
354 throw AsyncSocketException(
355 AsyncSocketException::INTERNAL_ERROR,
356 withAddr("failed to put socket in non-blocking mode"),
360 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
361 // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
362 rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
364 throw AsyncSocketException(
365 AsyncSocketException::INTERNAL_ERROR,
366 "failed to enable F_SETNOSIGPIPE on socket",
371 // By default, turn on TCP_NODELAY
372 // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
373 // setNoDelay() will log an error message if it fails.
374 if (address.getFamily() != AF_UNIX) {
375 (void)setNoDelay(true);
378 VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
379 << ", fd=" << fd_ << ", host=" << address.describe().c_str();
382 if (bindAddr != anyAddress()) {
384 if (::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
386 throw AsyncSocketException(
387 AsyncSocketException::NOT_OPEN,
388 "failed to setsockopt prior to bind on " + bindAddr.describe(),
392 bindAddr.getAddress(&addrStorage);
394 if (::bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
396 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
397 "failed to bind to async socket: " +
403 // Apply the additional options if any.
404 for (const auto& opt: options) {
405 int rv = opt.first.apply(fd_, opt.second);
407 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
408 withAddr("failed to set socket option"),
413 // Perform the connect()
414 address.getAddress(&addrStorage);
416 rv = ::connect(fd_, saddr, address.getActualSize());
418 if (errno == EINPROGRESS) {
419 // Connection in progress.
421 // Start a timer in case the connection takes too long.
422 if (!writeTimeout_.scheduleTimeout(timeout)) {
423 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
424 withAddr("failed to schedule AsyncSocket connect timeout"));
428 // Register for write events, so we'll
429 // be notified when the connection finishes/fails.
430 // Note that we don't register for a persistent event here.
431 assert(eventFlags_ == EventHandler::NONE);
432 eventFlags_ = EventHandler::WRITE;
433 if (!ioHandler_.registerHandler(eventFlags_)) {
434 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
435 withAddr("failed to register AsyncSocket connect handler"));
439 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
440 "connect failed (immediately)", errno);
444 // If we're still here the connect() succeeded immediately.
445 // Fall through to call the callback outside of this try...catch block
446 } catch (const AsyncSocketException& ex) {
447 return failConnect(__func__, ex);
448 } catch (const std::exception& ex) {
449 // shouldn't happen, but handle it just in case
450 VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
451 << "): unexpected " << typeid(ex).name() << " exception: "
453 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
454 withAddr(string("unexpected exception: ") +
456 return failConnect(__func__, tex);
459 // The connection succeeded immediately
460 // The read callback may not have been set yet, and no writes may be pending
461 // yet, so we don't have to register for any events at the moment.
462 VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
463 assert(readCallback_ == nullptr);
464 assert(writeReqHead_ == nullptr);
465 state_ = StateEnum::ESTABLISHED;
467 connectCallback_ = nullptr;
468 callback->connectSuccess();
472 void AsyncSocket::connect(ConnectCallback* callback,
473 const string& ip, uint16_t port,
475 const OptionMap &options) noexcept {
476 DestructorGuard dg(this);
478 connectCallback_ = callback;
479 connect(callback, folly::SocketAddress(ip, port), timeout, options);
480 } catch (const std::exception& ex) {
481 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
483 return failConnect(__func__, tex);
487 void AsyncSocket::cancelConnect() {
488 connectCallback_ = nullptr;
489 if (state_ == StateEnum::CONNECTING) {
494 void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
495 sendTimeout_ = milliseconds;
496 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
498 // If we are currently pending on write requests, immediately update
499 // writeTimeout_ with the new value.
500 if ((eventFlags_ & EventHandler::WRITE) &&
501 (state_ != StateEnum::CONNECTING)) {
502 assert(state_ == StateEnum::ESTABLISHED);
503 assert((shutdownFlags_ & SHUT_WRITE) == 0);
504 if (sendTimeout_ > 0) {
505 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
506 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
507 withAddr("failed to reschedule send timeout in setSendTimeout"));
508 return failWrite(__func__, ex);
511 writeTimeout_.cancelTimeout();
516 void AsyncSocket::setReadCB(ReadCallback *callback) {
517 VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
518 << ", callback=" << callback << ", state=" << state_;
520 // Short circuit if callback is the same as the existing readCallback_.
522 // Note that this is needed for proper functioning during some cleanup cases.
523 // During cleanup we allow setReadCallback(nullptr) to be called even if the
524 // read callback is already unset and we have been detached from an event
525 // base. This check prevents us from asserting
526 // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
527 if (callback == readCallback_) {
531 /* We are removing a read callback */
532 if (callback == nullptr &&
533 immediateReadHandler_.isLoopCallbackScheduled()) {
534 immediateReadHandler_.cancelLoopCallback();
537 if (shutdownFlags_ & SHUT_READ) {
538 // Reads have already been shut down on this socket.
540 // Allow setReadCallback(nullptr) to be called in this case, but don't
541 // allow a new callback to be set.
543 // For example, setReadCallback(nullptr) can happen after an error if we
544 // invoke some other error callback before invoking readError(). The other
545 // error callback that is invoked first may go ahead and clear the read
546 // callback before we get a chance to invoke readError().
547 if (callback != nullptr) {
548 return invalidState(callback);
550 assert((eventFlags_ & EventHandler::READ) == 0);
551 readCallback_ = nullptr;
555 DestructorGuard dg(this);
556 assert(eventBase_->isInEventBaseThread());
558 switch ((StateEnum)state_) {
559 case StateEnum::CONNECTING:
560 // For convenience, we allow the read callback to be set while we are
561 // still connecting. We just store the callback for now. Once the
562 // connection completes we'll register for read events.
563 readCallback_ = callback;
565 case StateEnum::ESTABLISHED:
567 readCallback_ = callback;
568 uint16_t oldFlags = eventFlags_;
570 eventFlags_ |= EventHandler::READ;
572 eventFlags_ &= ~EventHandler::READ;
575 // Update our registration if our flags have changed
576 if (eventFlags_ != oldFlags) {
577 // We intentionally ignore the return value here.
578 // updateEventRegistration() will move us into the error state if it
579 // fails, and we don't need to do anything else here afterwards.
580 (void)updateEventRegistration();
584 checkForImmediateRead();
588 case StateEnum::CLOSED:
589 case StateEnum::ERROR:
590 // We should never reach here. SHUT_READ should always be set
591 // if we are in STATE_CLOSED or STATE_ERROR.
593 return invalidState(callback);
594 case StateEnum::UNINIT:
595 // We do not allow setReadCallback() to be called before we start
597 return invalidState(callback);
600 // We don't put a default case in the switch statement, so that the compiler
601 // will warn us to update the switch statement if a new state is added.
602 return invalidState(callback);
605 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
606 return readCallback_;
609 void AsyncSocket::write(WriteCallback* callback,
610 const void* buf, size_t bytes, WriteFlags flags) {
612 op.iov_base = const_cast<void*>(buf);
614 writeImpl(callback, &op, 1, unique_ptr<IOBuf>(), flags);
617 void AsyncSocket::writev(WriteCallback* callback,
621 writeImpl(callback, vec, count, unique_ptr<IOBuf>(), flags);
624 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
626 constexpr size_t kSmallSizeMax = 64;
627 size_t count = buf->countChainElements();
628 if (count <= kSmallSizeMax) {
629 iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA, count, kSmallSizeMax)];
630 writeChainImpl(callback, vec, count, std::move(buf), flags);
632 iovec* vec = new iovec[count];
633 writeChainImpl(callback, vec, count, std::move(buf), flags);
638 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
639 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
640 size_t veclen = buf->fillIov(vec, count);
641 writeImpl(callback, vec, veclen, std::move(buf), flags);
644 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
645 size_t count, unique_ptr<IOBuf>&& buf,
647 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
648 << ", callback=" << callback << ", count=" << count
649 << ", state=" << state_;
650 DestructorGuard dg(this);
651 unique_ptr<IOBuf>ioBuf(std::move(buf));
652 assert(eventBase_->isInEventBaseThread());
654 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
655 // No new writes may be performed after the write side of the socket has
658 // We could just call callback->writeError() here to fail just this write.
659 // However, fail hard and use invalidState() to fail all outstanding
660 // callbacks and move the socket into the error state. There's most likely
661 // a bug in the caller's code, so we abort everything rather than trying to
662 // proceed as best we can.
663 return invalidState(callback);
666 uint32_t countWritten = 0;
667 uint32_t partialWritten = 0;
668 int bytesWritten = 0;
669 bool mustRegister = false;
670 if (state_ == StateEnum::ESTABLISHED && !connecting()) {
671 if (writeReqHead_ == nullptr) {
672 // If we are established and there are no other writes pending,
673 // we can attempt to perform the write immediately.
674 assert(writeReqTail_ == nullptr);
675 assert((eventFlags_ & EventHandler::WRITE) == 0);
677 bytesWritten = performWrite(vec, count, flags,
678 &countWritten, &partialWritten);
679 if (bytesWritten < 0) {
680 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
681 withAddr("writev failed"), errno);
682 return failWrite(__func__, callback, 0, ex);
683 } else if (countWritten == count) {
684 // We successfully wrote everything.
685 // Invoke the callback and return.
687 callback->writeSuccess();
690 } // else { continue writing the next writeReq }
693 } else if (!connecting()) {
694 // Invalid state for writing
695 return invalidState(callback);
698 // Create a new WriteRequest to add to the queue
701 req = BytesWriteRequest::newRequest(this, callback, vec + countWritten,
702 count - countWritten, partialWritten,
703 bytesWritten, std::move(ioBuf), flags);
704 } catch (const std::exception& ex) {
705 // we mainly expect to catch std::bad_alloc here
706 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
707 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
708 return failWrite(__func__, callback, bytesWritten, tex);
711 if (writeReqTail_ == nullptr) {
712 assert(writeReqHead_ == nullptr);
713 writeReqHead_ = writeReqTail_ = req;
715 writeReqTail_->append(req);
719 // Register for write events if are established and not currently
720 // waiting on write events
722 assert(state_ == StateEnum::ESTABLISHED);
723 assert((eventFlags_ & EventHandler::WRITE) == 0);
724 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
725 assert(state_ == StateEnum::ERROR);
728 if (sendTimeout_ > 0) {
729 // Schedule a timeout to fire if the write takes too long.
730 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
731 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
732 withAddr("failed to schedule send timeout"));
733 return failWrite(__func__, ex);
739 void AsyncSocket::writeRequest(WriteRequest* req) {
740 if (writeReqTail_ == nullptr) {
741 assert(writeReqHead_ == nullptr);
742 writeReqHead_ = writeReqTail_ = req;
745 writeReqTail_->append(req);
750 void AsyncSocket::close() {
751 VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
752 << ", state=" << state_ << ", shutdownFlags="
753 << std::hex << (int) shutdownFlags_;
755 // close() is only different from closeNow() when there are pending writes
756 // that need to drain before we can close. In all other cases, just call
759 // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
760 // STATE_ERROR if close() is invoked while a previous closeNow() or failure
761 // is still running. (e.g., If there are multiple pending writes, and we
762 // call writeError() on the first one, it may call close(). In this case we
763 // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
764 // writes will still be in the queue.)
766 // We only need to drain pending writes if we are still in STATE_CONNECTING
767 // or STATE_ESTABLISHED
768 if ((writeReqHead_ == nullptr) ||
769 !(state_ == StateEnum::CONNECTING ||
770 state_ == StateEnum::ESTABLISHED)) {
775 // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
776 // destroyed until close() returns.
777 DestructorGuard dg(this);
778 assert(eventBase_->isInEventBaseThread());
780 // Since there are write requests pending, we have to set the
781 // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
782 // connect finishes and we finish writing these requests.
784 // Set SHUT_READ to indicate that reads are shut down, and set the
785 // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
786 // pending writes complete.
787 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
789 // If a read callback is set, invoke readEOF() immediately to inform it that
790 // the socket has been closed and no more data can be read.
792 // Disable reads if they are enabled
793 if (!updateEventRegistration(0, EventHandler::READ)) {
794 // We're now in the error state; callbacks have been cleaned up
795 assert(state_ == StateEnum::ERROR);
796 assert(readCallback_ == nullptr);
798 ReadCallback* callback = readCallback_;
799 readCallback_ = nullptr;
805 void AsyncSocket::closeNow() {
806 VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
807 << ", state=" << state_ << ", shutdownFlags="
808 << std::hex << (int) shutdownFlags_;
809 DestructorGuard dg(this);
810 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
813 case StateEnum::ESTABLISHED:
814 case StateEnum::CONNECTING:
816 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
817 state_ = StateEnum::CLOSED;
819 // If the write timeout was set, cancel it.
820 writeTimeout_.cancelTimeout();
822 // If we are registered for I/O events, unregister.
823 if (eventFlags_ != EventHandler::NONE) {
824 eventFlags_ = EventHandler::NONE;
825 if (!updateEventRegistration()) {
826 // We will have been moved into the error state.
827 assert(state_ == StateEnum::ERROR);
832 if (immediateReadHandler_.isLoopCallbackScheduled()) {
833 immediateReadHandler_.cancelLoopCallback();
837 ioHandler_.changeHandlerFD(-1);
841 if (connectCallback_) {
842 ConnectCallback* callback = connectCallback_;
843 connectCallback_ = nullptr;
844 callback->connectErr(socketClosedLocallyEx);
847 failAllWrites(socketClosedLocallyEx);
850 ReadCallback* callback = readCallback_;
851 readCallback_ = nullptr;
856 case StateEnum::CLOSED:
857 // Do nothing. It's possible that we are being called recursively
858 // from inside a callback that we invoked inside another call to close()
859 // that is still running.
861 case StateEnum::ERROR:
862 // Do nothing. The error handling code has performed (or is performing)
865 case StateEnum::UNINIT:
866 assert(eventFlags_ == EventHandler::NONE);
867 assert(connectCallback_ == nullptr);
868 assert(readCallback_ == nullptr);
869 assert(writeReqHead_ == nullptr);
870 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
871 state_ = StateEnum::CLOSED;
875 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
876 << ") called in unknown state " << state_;
879 void AsyncSocket::closeWithReset() {
880 // Enable SO_LINGER, with the linger timeout set to 0.
881 // This will trigger a TCP reset when we close the socket.
883 struct linger optLinger = {1, 0};
884 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
885 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
886 << "on " << fd_ << ": errno=" << errno;
890 // Then let closeNow() take care of the rest
894 void AsyncSocket::shutdownWrite() {
895 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
896 << ", state=" << state_ << ", shutdownFlags="
897 << std::hex << (int) shutdownFlags_;
899 // If there are no pending writes, shutdownWrite() is identical to
900 // shutdownWriteNow().
901 if (writeReqHead_ == nullptr) {
906 assert(eventBase_->isInEventBaseThread());
908 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
909 // shutdown will be performed once all writes complete.
910 shutdownFlags_ |= SHUT_WRITE_PENDING;
913 void AsyncSocket::shutdownWriteNow() {
914 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
915 << ", fd=" << fd_ << ", state=" << state_
916 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
918 if (shutdownFlags_ & SHUT_WRITE) {
919 // Writes are already shutdown; nothing else to do.
923 // If SHUT_READ is already set, just call closeNow() to completely
924 // close the socket. This can happen if close() was called with writes
925 // pending, and then shutdownWriteNow() is called before all pending writes
927 if (shutdownFlags_ & SHUT_READ) {
932 DestructorGuard dg(this);
933 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
935 switch (static_cast<StateEnum>(state_)) {
936 case StateEnum::ESTABLISHED:
938 shutdownFlags_ |= SHUT_WRITE;
940 // If the write timeout was set, cancel it.
941 writeTimeout_.cancelTimeout();
943 // If we are registered for write events, unregister.
944 if (!updateEventRegistration(0, EventHandler::WRITE)) {
945 // We will have been moved into the error state.
946 assert(state_ == StateEnum::ERROR);
950 // Shutdown writes on the file descriptor
951 ::shutdown(fd_, SHUT_WR);
953 // Immediately fail all write requests
954 failAllWrites(socketShutdownForWritesEx);
957 case StateEnum::CONNECTING:
959 // Set the SHUT_WRITE_PENDING flag.
960 // When the connection completes, it will check this flag,
961 // shutdown the write half of the socket, and then set SHUT_WRITE.
962 shutdownFlags_ |= SHUT_WRITE_PENDING;
964 // Immediately fail all write requests
965 failAllWrites(socketShutdownForWritesEx);
968 case StateEnum::UNINIT:
969 // Callers normally shouldn't call shutdownWriteNow() before the socket
970 // even starts connecting. Nonetheless, go ahead and set
971 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
972 // immediately shut down the write side of the socket.
973 shutdownFlags_ |= SHUT_WRITE_PENDING;
975 case StateEnum::CLOSED:
976 case StateEnum::ERROR:
977 // We should never get here. SHUT_WRITE should always be set
978 // in STATE_CLOSED and STATE_ERROR.
979 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
980 << ", fd=" << fd_ << ") in unexpected state " << state_
981 << " with SHUT_WRITE not set ("
982 << std::hex << (int) shutdownFlags_ << ")";
987 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
988 << fd_ << ") called in unknown state " << state_;
991 bool AsyncSocket::readable() const {
995 struct pollfd fds[1];
997 fds[0].events = POLLIN;
999 int rc = poll(fds, 1, 0);
1003 bool AsyncSocket::isPending() const {
1004 return ioHandler_.isPending();
1007 bool AsyncSocket::hangup() const {
1009 // sanity check, no one should ask for hangup if we are not connected.
1013 #ifdef POLLRDHUP // Linux-only
1014 struct pollfd fds[1];
1016 fds[0].events = POLLRDHUP|POLLHUP;
1019 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1025 bool AsyncSocket::good() const {
1026 return ((state_ == StateEnum::CONNECTING ||
1027 state_ == StateEnum::ESTABLISHED) &&
1028 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1031 bool AsyncSocket::error() const {
1032 return (state_ == StateEnum::ERROR);
1035 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1036 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1037 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1038 << ", state=" << state_ << ", events="
1039 << std::hex << eventFlags_ << ")";
1040 assert(eventBase_ == nullptr);
1041 assert(eventBase->isInEventBaseThread());
1043 eventBase_ = eventBase;
1044 ioHandler_.attachEventBase(eventBase);
1045 writeTimeout_.attachEventBase(eventBase);
1048 void AsyncSocket::detachEventBase() {
1049 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1050 << ", old evb=" << eventBase_ << ", state=" << state_
1051 << ", events=" << std::hex << eventFlags_ << ")";
1052 assert(eventBase_ != nullptr);
1053 assert(eventBase_->isInEventBaseThread());
1055 eventBase_ = nullptr;
1056 ioHandler_.detachEventBase();
1057 writeTimeout_.detachEventBase();
1060 bool AsyncSocket::isDetachable() const {
1061 DCHECK(eventBase_ != nullptr);
1062 DCHECK(eventBase_->isInEventBaseThread());
1064 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1067 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1068 address->setFromLocalAddress(fd_);
1071 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1072 if (!addr_.isInitialized()) {
1073 addr_.setFromPeerAddress(fd_);
1078 int AsyncSocket::setNoDelay(bool noDelay) {
1080 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1081 << this << "(state=" << state_ << ")";
1086 int value = noDelay ? 1 : 0;
1087 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1088 int errnoCopy = errno;
1089 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1090 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1091 << strerror(errnoCopy);
1098 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1100 #ifndef TCP_CONGESTION
1101 #define TCP_CONGESTION 13
1105 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1106 << "socket " << this << "(state=" << state_ << ")";
1111 if (setsockopt(fd_, IPPROTO_TCP, TCP_CONGESTION, cname.c_str(),
1112 cname.length() + 1) != 0) {
1113 int errnoCopy = errno;
1114 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1115 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1116 << strerror(errnoCopy);
1123 int AsyncSocket::setQuickAck(bool quickack) {
1125 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1126 << this << "(state=" << state_ << ")";
1131 #ifdef TCP_QUICKACK // Linux-only
1132 int value = quickack ? 1 : 0;
1133 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1134 int errnoCopy = errno;
1135 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1136 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1137 << strerror(errnoCopy);
1147 int AsyncSocket::setSendBufSize(size_t bufsize) {
1149 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1150 << this << "(state=" << state_ << ")";
1154 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1155 int errnoCopy = errno;
1156 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1157 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1158 << strerror(errnoCopy);
1165 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1167 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1168 << this << "(state=" << state_ << ")";
1172 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1173 int errnoCopy = errno;
1174 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1175 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1176 << strerror(errnoCopy);
1183 int AsyncSocket::setTCPProfile(int profd) {
1185 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1186 << this << "(state=" << state_ << ")";
1190 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1191 int errnoCopy = errno;
1192 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1193 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1194 << strerror(errnoCopy);
1201 void AsyncSocket::ioReady(uint16_t events) noexcept {
1202 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd" << fd_
1203 << ", events=" << std::hex << events << ", state=" << state_;
1204 DestructorGuard dg(this);
1205 assert(events & EventHandler::READ_WRITE);
1206 assert(eventBase_->isInEventBaseThread());
1208 uint16_t relevantEvents = events & EventHandler::READ_WRITE;
1209 if (relevantEvents == EventHandler::READ) {
1211 } else if (relevantEvents == EventHandler::WRITE) {
1213 } else if (relevantEvents == EventHandler::READ_WRITE) {
1214 EventBase* originalEventBase = eventBase_;
1215 // If both read and write events are ready, process writes first.
1218 // Return now if handleWrite() detached us from our EventBase
1219 if (eventBase_ != originalEventBase) {
1223 // Only call handleRead() if a read callback is still installed.
1224 // (It's possible that the read callback was uninstalled during
1226 if (readCallback_) {
1230 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1231 << std::hex << events << "(this=" << this << ")";
1236 ssize_t AsyncSocket::performRead(void** buf, size_t* buflen, size_t* offset) {
1237 VLOG(5) << "AsyncSocket::performRead() this=" << this
1238 << ", buf=" << *buf << ", buflen=" << *buflen;
1242 recvFlags |= MSG_PEEK;
1245 ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT | recvFlags);
1247 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1248 // No more data to read right now.
1249 return READ_BLOCKING;
1254 appBytesReceived_ += bytes;
1259 void AsyncSocket::prepareReadBuffer(void** buf, size_t* buflen) noexcept {
1260 // no matter what, buffer should be preapared for non-ssl socket
1261 CHECK(readCallback_);
1262 readCallback_->getReadBuffer(buf, buflen);
1265 void AsyncSocket::handleRead() noexcept {
1266 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1267 << ", state=" << state_;
1268 assert(state_ == StateEnum::ESTABLISHED);
1269 assert((shutdownFlags_ & SHUT_READ) == 0);
1270 assert(readCallback_ != nullptr);
1271 assert(eventFlags_ & EventHandler::READ);
1274 // - a read attempt would block
1275 // - readCallback_ is uninstalled
1276 // - the number of loop iterations exceeds the optional maximum
1277 // - this AsyncSocket is moved to another EventBase
1279 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1280 // which is why need to check for it here.
1282 // The last bullet point is slightly subtle. readDataAvailable() may also
1283 // detach this socket from this EventBase. However, before
1284 // readDataAvailable() returns another thread may pick it up, attach it to
1285 // a different EventBase, and install another readCallback_. We need to
1286 // exit immediately after readDataAvailable() returns if the eventBase_ has
1287 // changed. (The caller must perform some sort of locking to transfer the
1288 // AsyncSocket between threads properly. This will be sufficient to ensure
1289 // that this thread sees the updated eventBase_ variable after
1290 // readDataAvailable() returns.)
1291 uint16_t numReads = 0;
1292 EventBase* originalEventBase = eventBase_;
1293 while (readCallback_ && eventBase_ == originalEventBase) {
1294 // Get the buffer to read into.
1295 void* buf = nullptr;
1296 size_t buflen = 0, offset = 0;
1298 prepareReadBuffer(&buf, &buflen);
1299 VLOG(5) << "prepareReadBuffer() buf=" << buf << ", buflen=" << buflen;
1300 } catch (const AsyncSocketException& ex) {
1301 return failRead(__func__, ex);
1302 } catch (const std::exception& ex) {
1303 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1304 string("ReadCallback::getReadBuffer() "
1305 "threw exception: ") +
1307 return failRead(__func__, tex);
1309 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1310 "ReadCallback::getReadBuffer() threw "
1311 "non-exception type");
1312 return failRead(__func__, ex);
1314 if (!isBufferMovable_ && (buf == nullptr || buflen == 0)) {
1315 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1316 "ReadCallback::getReadBuffer() returned "
1318 return failRead(__func__, ex);
1322 ssize_t bytesRead = performRead(&buf, &buflen, &offset);
1323 VLOG(4) << "this=" << this << ", AsyncSocket::handleRead() got "
1324 << bytesRead << " bytes";
1325 if (bytesRead > 0) {
1326 if (!isBufferMovable_) {
1327 readCallback_->readDataAvailable(bytesRead);
1329 CHECK(kOpenSslModeMoveBufferOwnership);
1330 VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
1331 << "buf=" << buf << ", " << bytesRead << "/" << buflen
1332 << ", offset=" << offset;
1333 auto readBuf = folly::IOBuf::takeOwnership(buf, buflen);
1334 readBuf->trimStart(offset);
1335 readBuf->trimEnd(buflen - offset - bytesRead);
1336 readCallback_->readBufferAvailable(std::move(readBuf));
1339 // Fall through and continue around the loop if the read
1340 // completely filled the available buffer.
1341 // Note that readCallback_ may have been uninstalled or changed inside
1342 // readDataAvailable().
1343 if (size_t(bytesRead) < buflen) {
1346 } else if (bytesRead == READ_BLOCKING) {
1347 // No more data to read right now.
1349 } else if (bytesRead == READ_ERROR) {
1350 readErr_ = READ_ERROR;
1351 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1352 withAddr("recv() failed"), errno);
1353 return failRead(__func__, ex);
1355 assert(bytesRead == READ_EOF);
1356 readErr_ = READ_EOF;
1358 shutdownFlags_ |= SHUT_READ;
1359 if (!updateEventRegistration(0, EventHandler::READ)) {
1360 // we've already been moved into STATE_ERROR
1361 assert(state_ == StateEnum::ERROR);
1362 assert(readCallback_ == nullptr);
1366 ReadCallback* callback = readCallback_;
1367 readCallback_ = nullptr;
1368 callback->readEOF();
1371 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1372 if (readCallback_ != nullptr) {
1373 // We might still have data in the socket.
1374 // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
1375 scheduleImmediateRead();
1383 * This function attempts to write as much data as possible, until no more data
1386 * - If it sends all available data, it unregisters for write events, and stops
1387 * the writeTimeout_.
1389 * - If not all of the data can be sent immediately, it reschedules
1390 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1391 * registered for write events.
1393 void AsyncSocket::handleWrite() noexcept {
1394 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1395 << ", state=" << state_;
1396 if (state_ == StateEnum::CONNECTING) {
1402 assert(state_ == StateEnum::ESTABLISHED);
1403 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1404 assert(writeReqHead_ != nullptr);
1406 // Loop until we run out of write requests,
1407 // or until this socket is moved to another EventBase.
1408 // (See the comment in handleRead() explaining how this can happen.)
1409 EventBase* originalEventBase = eventBase_;
1410 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1411 if (!writeReqHead_->performWrite()) {
1412 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1413 withAddr("writev() failed"), errno);
1414 return failWrite(__func__, ex);
1415 } else if (writeReqHead_->isComplete()) {
1416 // We finished this request
1417 WriteRequest* req = writeReqHead_;
1418 writeReqHead_ = req->getNext();
1420 if (writeReqHead_ == nullptr) {
1421 writeReqTail_ = nullptr;
1422 // This is the last write request.
1423 // Unregister for write events and cancel the send timer
1424 // before we invoke the callback. We have to update the state properly
1425 // before calling the callback, since it may want to detach us from
1427 if (eventFlags_ & EventHandler::WRITE) {
1428 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1429 assert(state_ == StateEnum::ERROR);
1432 // Stop the send timeout
1433 writeTimeout_.cancelTimeout();
1435 assert(!writeTimeout_.isScheduled());
1437 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
1438 // we finish sending the last write request.
1440 // We have to do this before invoking writeSuccess(), since
1441 // writeSuccess() may detach us from our EventBase.
1442 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
1443 assert(connectCallback_ == nullptr);
1444 shutdownFlags_ |= SHUT_WRITE;
1446 if (shutdownFlags_ & SHUT_READ) {
1447 // Reads have already been shutdown. Fully close the socket and
1448 // move to STATE_CLOSED.
1450 // Note: This code currently moves us to STATE_CLOSED even if
1451 // close() hasn't ever been called. This can occur if we have
1452 // received EOF from the peer and shutdownWrite() has been called
1453 // locally. Should we bother staying in STATE_ESTABLISHED in this
1454 // case, until close() is actually called? I can't think of a
1455 // reason why we would need to do so. No other operations besides
1456 // calling close() or destroying the socket can be performed at
1458 assert(readCallback_ == nullptr);
1459 state_ = StateEnum::CLOSED;
1461 ioHandler_.changeHandlerFD(-1);
1465 // Reads are still enabled, so we are only doing a half-shutdown
1466 ::shutdown(fd_, SHUT_WR);
1471 // Invoke the callback
1472 WriteCallback* callback = req->getCallback();
1475 callback->writeSuccess();
1477 // We'll continue around the loop, trying to write another request
1480 writeReqHead_->consume();
1481 // Stop after a partial write; it's highly likely that a subsequent write
1482 // attempt will just return EAGAIN.
1484 // Ensure that we are registered for write events.
1485 if ((eventFlags_ & EventHandler::WRITE) == 0) {
1486 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1487 assert(state_ == StateEnum::ERROR);
1492 // Reschedule the send timeout, since we have made some write progress.
1493 if (sendTimeout_ > 0) {
1494 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1495 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1496 withAddr("failed to reschedule write timeout"));
1497 return failWrite(__func__, ex);
1505 void AsyncSocket::checkForImmediateRead() noexcept {
1506 // We currently don't attempt to perform optimistic reads in AsyncSocket.
1507 // (However, note that some subclasses do override this method.)
1509 // Simply calling handleRead() here would be bad, as this would call
1510 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
1511 // buffer even though no data may be available. This would waste lots of
1512 // memory, since the buffer will sit around unused until the socket actually
1513 // becomes readable.
1515 // Checking if the socket is readable now also seems like it would probably
1516 // be a pessimism. In most cases it probably wouldn't be readable, and we
1517 // would just waste an extra system call. Even if it is readable, waiting to
1518 // find out from libevent on the next event loop doesn't seem that bad.
1521 void AsyncSocket::handleInitialReadWrite() noexcept {
1522 // Our callers should already be holding a DestructorGuard, but grab
1523 // one here just to make sure, in case one of our calling code paths ever
1525 DestructorGuard dg(this);
1527 // If we have a readCallback_, make sure we enable read events. We
1528 // may already be registered for reads if connectSuccess() set
1529 // the read calback.
1530 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
1531 assert(state_ == StateEnum::ESTABLISHED);
1532 assert((shutdownFlags_ & SHUT_READ) == 0);
1533 if (!updateEventRegistration(EventHandler::READ, 0)) {
1534 assert(state_ == StateEnum::ERROR);
1537 checkForImmediateRead();
1538 } else if (readCallback_ == nullptr) {
1539 // Unregister for read events.
1540 updateEventRegistration(0, EventHandler::READ);
1543 // If we have write requests pending, try to send them immediately.
1544 // Since we just finished accepting, there is a very good chance that we can
1545 // write without blocking.
1547 // However, we only process them if EventHandler::WRITE is not already set,
1548 // which means that we're already blocked on a write attempt. (This can
1549 // happen if connectSuccess() called write() before returning.)
1550 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
1551 // Call handleWrite() to perform write processing.
1553 } else if (writeReqHead_ == nullptr) {
1554 // Unregister for write event.
1555 updateEventRegistration(0, EventHandler::WRITE);
1559 void AsyncSocket::handleConnect() noexcept {
1560 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
1561 << ", state=" << state_;
1562 assert(state_ == StateEnum::CONNECTING);
1563 // SHUT_WRITE can never be set while we are still connecting;
1564 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
1566 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1568 // In case we had a connect timeout, cancel the timeout
1569 writeTimeout_.cancelTimeout();
1570 // We don't use a persistent registration when waiting on a connect event,
1571 // so we have been automatically unregistered now. Update eventFlags_ to
1573 assert(eventFlags_ == EventHandler::WRITE);
1574 eventFlags_ = EventHandler::NONE;
1576 // Call getsockopt() to check if the connect succeeded
1578 socklen_t len = sizeof(error);
1579 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
1581 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1582 withAddr("error calling getsockopt() after connect"),
1584 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1585 << fd_ << " host=" << addr_.describe()
1586 << ") exception:" << ex.what();
1587 return failConnect(__func__, ex);
1591 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1592 "connect failed", error);
1593 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1594 << fd_ << " host=" << addr_.describe()
1595 << ") exception: " << ex.what();
1596 return failConnect(__func__, ex);
1599 // Move into STATE_ESTABLISHED
1600 state_ = StateEnum::ESTABLISHED;
1602 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
1603 // perform, immediately shutdown the write half of the socket.
1604 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
1605 // SHUT_READ shouldn't be set. If close() is called on the socket while we
1606 // are still connecting we just abort the connect rather than waiting for
1608 assert((shutdownFlags_ & SHUT_READ) == 0);
1609 ::shutdown(fd_, SHUT_WR);
1610 shutdownFlags_ |= SHUT_WRITE;
1613 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
1614 << "successfully connected; state=" << state_;
1616 // Remember the EventBase we are attached to, before we start invoking any
1617 // callbacks (since the callbacks may call detachEventBase()).
1618 EventBase* originalEventBase = eventBase_;
1620 // Call the connect callback.
1621 if (connectCallback_) {
1622 ConnectCallback* callback = connectCallback_;
1623 connectCallback_ = nullptr;
1624 callback->connectSuccess();
1627 // Note that the connect callback may have changed our state.
1628 // (set or unset the read callback, called write(), closed the socket, etc.)
1629 // The following code needs to handle these situations correctly.
1631 // If the socket has been closed, readCallback_ and writeReqHead_ will
1632 // always be nullptr, so that will prevent us from trying to read or write.
1634 // The main thing to check for is if eventBase_ is still originalEventBase.
1635 // If not, we have been detached from this event base, so we shouldn't
1636 // perform any more operations.
1637 if (eventBase_ != originalEventBase) {
1641 handleInitialReadWrite();
1644 void AsyncSocket::timeoutExpired() noexcept {
1645 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
1646 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
1647 DestructorGuard dg(this);
1648 assert(eventBase_->isInEventBaseThread());
1650 if (state_ == StateEnum::CONNECTING) {
1651 // connect() timed out
1652 // Unregister for I/O events.
1653 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
1654 "connect timed out");
1655 failConnect(__func__, ex);
1657 // a normal write operation timed out
1658 assert(state_ == StateEnum::ESTABLISHED);
1659 AsyncSocketException ex(AsyncSocketException::TIMED_OUT, "write timed out");
1660 failWrite(__func__, ex);
1664 ssize_t AsyncSocket::performWrite(const iovec* vec,
1667 uint32_t* countWritten,
1668 uint32_t* partialWritten) {
1669 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
1670 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
1671 // (since it may terminate the program if the main program doesn't explicitly
1674 msg.msg_name = nullptr;
1675 msg.msg_namelen = 0;
1676 msg.msg_iov = const_cast<iovec *>(vec);
1677 #ifdef IOV_MAX // not defined on Android
1678 msg.msg_iovlen = std::min(count, (uint32_t)IOV_MAX);
1680 msg.msg_iovlen = std::min(count, (uint32_t)UIO_MAXIOV);
1682 msg.msg_control = nullptr;
1683 msg.msg_controllen = 0;
1686 int msg_flags = MSG_DONTWAIT;
1688 #ifdef MSG_NOSIGNAL // Linux-only
1689 msg_flags |= MSG_NOSIGNAL;
1690 if (isSet(flags, WriteFlags::CORK)) {
1691 // MSG_MORE tells the kernel we have more data to send, so wait for us to
1692 // give it the rest of the data rather than immediately sending a partial
1693 // frame, even when TCP_NODELAY is enabled.
1694 msg_flags |= MSG_MORE;
1697 if (isSet(flags, WriteFlags::EOR)) {
1698 // marks that this is the last byte of a record (response)
1699 msg_flags |= MSG_EOR;
1701 ssize_t totalWritten = ::sendmsg(fd_, &msg, msg_flags);
1702 if (totalWritten < 0) {
1703 if (errno == EAGAIN) {
1704 // TCP buffer is full; we can't write any more data right now.
1706 *partialWritten = 0;
1711 *partialWritten = 0;
1715 appBytesWritten_ += totalWritten;
1717 uint32_t bytesWritten;
1719 for (bytesWritten = totalWritten, n = 0; n < count; ++n) {
1720 const iovec* v = vec + n;
1721 if (v->iov_len > bytesWritten) {
1722 // Partial write finished in the middle of this iovec
1724 *partialWritten = bytesWritten;
1725 return totalWritten;
1728 bytesWritten -= v->iov_len;
1731 assert(bytesWritten == 0);
1733 *partialWritten = 0;
1734 return totalWritten;
1738 * Re-register the EventHandler after eventFlags_ has changed.
1740 * If an error occurs, fail() is called to move the socket into the error state
1741 * and call all currently installed callbacks. After an error, the
1742 * AsyncSocket is completely unregistered.
1744 * @return Returns true on succcess, or false on error.
1746 bool AsyncSocket::updateEventRegistration() {
1747 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
1748 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
1749 << ", events=" << std::hex << eventFlags_;
1750 assert(eventBase_->isInEventBaseThread());
1751 if (eventFlags_ == EventHandler::NONE) {
1752 ioHandler_.unregisterHandler();
1756 // Always register for persistent events, so we don't have to re-register
1757 // after being called back.
1758 if (!ioHandler_.registerHandler(eventFlags_ | EventHandler::PERSIST)) {
1759 eventFlags_ = EventHandler::NONE; // we're not registered after error
1760 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1761 withAddr("failed to update AsyncSocket event registration"));
1762 fail("updateEventRegistration", ex);
1769 bool AsyncSocket::updateEventRegistration(uint16_t enable,
1771 uint16_t oldFlags = eventFlags_;
1772 eventFlags_ |= enable;
1773 eventFlags_ &= ~disable;
1774 if (eventFlags_ == oldFlags) {
1777 return updateEventRegistration();
1781 void AsyncSocket::startFail() {
1782 // startFail() should only be called once
1783 assert(state_ != StateEnum::ERROR);
1784 assert(getDestructorGuardCount() > 0);
1785 state_ = StateEnum::ERROR;
1786 // Ensure that SHUT_READ and SHUT_WRITE are set,
1787 // so all future attempts to read or write will be rejected
1788 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1790 if (eventFlags_ != EventHandler::NONE) {
1791 eventFlags_ = EventHandler::NONE;
1792 ioHandler_.unregisterHandler();
1794 writeTimeout_.cancelTimeout();
1797 ioHandler_.changeHandlerFD(-1);
1802 void AsyncSocket::finishFail() {
1803 assert(state_ == StateEnum::ERROR);
1804 assert(getDestructorGuardCount() > 0);
1806 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1807 withAddr("socket closing after error"));
1808 if (connectCallback_) {
1809 ConnectCallback* callback = connectCallback_;
1810 connectCallback_ = nullptr;
1811 callback->connectErr(ex);
1816 if (readCallback_) {
1817 ReadCallback* callback = readCallback_;
1818 readCallback_ = nullptr;
1819 callback->readErr(ex);
1823 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
1824 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1825 << state_ << " host=" << addr_.describe()
1826 << "): failed in " << fn << "(): "
1832 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
1833 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1834 << state_ << " host=" << addr_.describe()
1835 << "): failed while connecting in " << fn << "(): "
1839 if (connectCallback_ != nullptr) {
1840 ConnectCallback* callback = connectCallback_;
1841 connectCallback_ = nullptr;
1842 callback->connectErr(ex);
1848 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
1849 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1850 << state_ << " host=" << addr_.describe()
1851 << "): failed while reading in " << fn << "(): "
1855 if (readCallback_ != nullptr) {
1856 ReadCallback* callback = readCallback_;
1857 readCallback_ = nullptr;
1858 callback->readErr(ex);
1864 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
1865 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1866 << state_ << " host=" << addr_.describe()
1867 << "): failed while writing in " << fn << "(): "
1871 // Only invoke the first write callback, since the error occurred while
1872 // writing this request. Let any other pending write callbacks be invoked in
1874 if (writeReqHead_ != nullptr) {
1875 WriteRequest* req = writeReqHead_;
1876 writeReqHead_ = req->getNext();
1877 WriteCallback* callback = req->getCallback();
1878 uint32_t bytesWritten = req->getTotalBytesWritten();
1881 callback->writeErr(bytesWritten, ex);
1888 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
1889 size_t bytesWritten,
1890 const AsyncSocketException& ex) {
1891 // This version of failWrite() is used when the failure occurs before
1892 // we've added the callback to writeReqHead_.
1893 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1894 << state_ << " host=" << addr_.describe()
1895 <<"): failed while writing in " << fn << "(): "
1899 if (callback != nullptr) {
1900 callback->writeErr(bytesWritten, ex);
1906 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
1907 // Invoke writeError() on all write callbacks.
1908 // This is used when writes are forcibly shutdown with write requests
1909 // pending, or when an error occurs with writes pending.
1910 while (writeReqHead_ != nullptr) {
1911 WriteRequest* req = writeReqHead_;
1912 writeReqHead_ = req->getNext();
1913 WriteCallback* callback = req->getCallback();
1915 callback->writeErr(req->getTotalBytesWritten(), ex);
1921 void AsyncSocket::invalidState(ConnectCallback* callback) {
1922 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
1923 << "): connect() called in invalid state " << state_;
1926 * The invalidState() methods don't use the normal failure mechanisms,
1927 * since we don't know what state we are in. We don't want to call
1928 * startFail()/finishFail() recursively if we are already in the middle of
1932 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
1933 "connect() called with socket in invalid state");
1934 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1936 callback->connectErr(ex);
1939 // We can't use failConnect() here since connectCallback_
1940 // may already be set to another callback. Invoke this ConnectCallback
1941 // here; any other connectCallback_ will be invoked in finishFail()
1944 callback->connectErr(ex);
1950 void AsyncSocket::invalidState(ReadCallback* callback) {
1951 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
1952 << "): setReadCallback(" << callback
1953 << ") called in invalid state " << state_;
1955 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1956 "setReadCallback() called with socket in "
1958 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1960 callback->readErr(ex);
1965 callback->readErr(ex);
1971 void AsyncSocket::invalidState(WriteCallback* callback) {
1972 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
1973 << "): write() called in invalid state " << state_;
1975 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1976 withAddr("write() called with socket in invalid state"));
1977 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1979 callback->writeErr(0, ex);
1984 callback->writeErr(0, ex);
1990 void AsyncSocket::doClose() {
1991 if (fd_ == -1) return;
1992 if (shutdownSocketSet_) {
1993 shutdownSocketSet_->close(fd_);
2000 std::ostream& operator << (std::ostream& os,
2001 const AsyncSocket::StateEnum& state) {
2002 os << static_cast<int>(state);
2006 std::string AsyncSocket::withAddr(const std::string& s) {
2007 // Don't use addr_ directly because it may not be initialized
2008 // e.g. if constructed from fd
2009 folly::SocketAddress peer, local;
2011 getPeerAddress(&peer);
2012 getLocalAddress(&local);
2013 } catch (const std::exception&) {
2018 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";