2 * Copyright 2014 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/SocketAddress.h>
21 #include <folly/io/IOBuf.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <netinet/in.h>
31 #include <netinet/tcp.h>
34 using std::unique_ptr;
38 // static members initializers
39 const AsyncSocket::OptionMap AsyncSocket::emptyOptionMap;
40 const folly::SocketAddress AsyncSocket::anyAddress =
41 folly::SocketAddress("0.0.0.0", 0);
43 const AsyncSocketException socketClosedLocallyEx(
44 AsyncSocketException::END_OF_FILE, "socket closed locally");
45 const AsyncSocketException socketShutdownForWritesEx(
46 AsyncSocketException::END_OF_FILE, "socket shutdown for writes");
48 // TODO: It might help performance to provide a version of WriteRequest that
49 // users could derive from, so we can avoid the extra allocation for each call
50 // to write()/writev(). We could templatize TFramedAsyncChannel just like the
51 // protocols are currently templatized for transports.
53 // We would need the version for external users where they provide the iovec
54 // storage space, and only our internal version would allocate it at the end of
58 * A WriteRequest object tracks information about a pending write() or writev()
61 * A new WriteRequest operation is allocated on the heap for all write
62 * operations that cannot be completed immediately.
64 class AsyncSocket::WriteRequest {
66 static WriteRequest* newRequest(WriteCallback* callback,
69 unique_ptr<IOBuf>&& ioBuf,
72 // Since we put a variable size iovec array at the end
73 // of each WriteRequest, we have to manually allocate the memory.
74 void* buf = malloc(sizeof(WriteRequest) +
75 (opCount * sizeof(struct iovec)));
77 throw std::bad_alloc();
80 return new(buf) WriteRequest(callback, ops, opCount, std::move(ioBuf),
85 this->~WriteRequest();
90 return isSet(flags_, WriteFlags::CORK);
93 WriteFlags flags() const {
97 WriteRequest* getNext() const {
101 WriteCallback* getCallback() const {
105 uint32_t getBytesWritten() const {
106 return bytesWritten_;
109 const struct iovec* getOps() const {
110 assert(opCount_ > opIndex_);
111 return writeOps_ + opIndex_;
114 uint32_t getOpCount() const {
115 assert(opCount_ > opIndex_);
116 return opCount_ - opIndex_;
119 void consume(uint32_t wholeOps, uint32_t partialBytes,
120 uint32_t totalBytesWritten) {
121 // Advance opIndex_ forward by wholeOps
122 opIndex_ += wholeOps;
123 assert(opIndex_ < opCount_);
125 // If we've finished writing any IOBufs, release them
127 for (uint32_t i = wholeOps; i != 0; --i) {
129 ioBuf_ = ioBuf_->pop();
133 // Move partialBytes forward into the current iovec buffer
134 struct iovec* currentOp = writeOps_ + opIndex_;
135 assert((partialBytes < currentOp->iov_len) || (currentOp->iov_len == 0));
136 currentOp->iov_base =
137 reinterpret_cast<uint8_t*>(currentOp->iov_base) + partialBytes;
138 currentOp->iov_len -= partialBytes;
140 // Increment the bytesWritten_ count by totalBytesWritten
141 bytesWritten_ += totalBytesWritten;
144 void append(WriteRequest* next) {
145 assert(next_ == nullptr);
150 WriteRequest(WriteCallback* callback,
151 const struct iovec* ops,
153 unique_ptr<IOBuf>&& ioBuf,
156 , callback_(callback)
161 , ioBuf_(std::move(ioBuf)) {
162 memcpy(writeOps_, ops, sizeof(*ops) * opCount_);
165 // Private destructor, to ensure callers use destroy()
168 WriteRequest* next_; ///< pointer to next WriteRequest
169 WriteCallback* callback_; ///< completion callback
170 uint32_t bytesWritten_; ///< bytes written
171 uint32_t opCount_; ///< number of entries in writeOps_
172 uint32_t opIndex_; ///< current index into writeOps_
173 WriteFlags flags_; ///< set for WriteFlags
174 unique_ptr<IOBuf> ioBuf_; ///< underlying IOBuf, or nullptr if N/A
175 struct iovec writeOps_[]; ///< write operation(s) list
178 AsyncSocket::AsyncSocket()
179 : eventBase_(nullptr)
180 , writeTimeout_(this, nullptr)
181 , ioHandler_(this, nullptr) {
182 VLOG(5) << "new AsyncSocket(" << ")";
186 AsyncSocket::AsyncSocket(EventBase* evb)
188 , writeTimeout_(this, evb)
189 , ioHandler_(this, evb) {
190 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
194 AsyncSocket::AsyncSocket(EventBase* evb,
195 const folly::SocketAddress& address,
196 uint32_t connectTimeout)
198 , writeTimeout_(this, evb)
199 , ioHandler_(this, evb) {
200 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
202 connect(nullptr, address, connectTimeout);
205 AsyncSocket::AsyncSocket(EventBase* evb,
206 const std::string& ip,
208 uint32_t connectTimeout)
210 , writeTimeout_(this, evb)
211 , ioHandler_(this, evb) {
212 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
214 connect(nullptr, ip, port, connectTimeout);
217 AsyncSocket::AsyncSocket(EventBase* evb, int fd)
219 , writeTimeout_(this, evb)
220 , ioHandler_(this, evb, fd) {
221 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ", fd="
226 state_ = StateEnum::ESTABLISHED;
229 // init() method, since constructor forwarding isn't supported in most
231 void AsyncSocket::init() {
232 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
234 state_ = StateEnum::UNINIT;
235 eventFlags_ = EventHandler::NONE;
238 maxReadsPerEvent_ = 16;
239 connectCallback_ = nullptr;
240 readCallback_ = nullptr;
241 writeReqHead_ = nullptr;
242 writeReqTail_ = nullptr;
243 shutdownSocketSet_ = nullptr;
244 appBytesWritten_ = 0;
245 appBytesReceived_ = 0;
248 AsyncSocket::~AsyncSocket() {
249 VLOG(7) << "actual destruction of AsyncSocket(this=" << this
250 << ", evb=" << eventBase_ << ", fd=" << fd_
251 << ", state=" << state_ << ")";
254 void AsyncSocket::destroy() {
255 VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
256 << ", fd=" << fd_ << ", state=" << state_;
257 // When destroy is called, close the socket immediately
260 // Then call DelayedDestruction::destroy() to take care of
261 // whether or not we need immediate or delayed destruction
262 DelayedDestruction::destroy();
265 int AsyncSocket::detachFd() {
266 VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
267 << ", evb=" << eventBase_ << ", state=" << state_
268 << ", events=" << std::hex << eventFlags_ << ")";
269 // Extract the fd, and set fd_ to -1 first, so closeNow() won't
270 // actually close the descriptor.
271 if (shutdownSocketSet_) {
272 shutdownSocketSet_->remove(fd_);
276 // Call closeNow() to invoke all pending callbacks with an error.
278 // Update the EventHandler to stop using this fd.
279 // This can only be done after closeNow() unregisters the handler.
280 ioHandler_.changeHandlerFD(-1);
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 if (shutdownFlags_ & SHUT_READ) {
532 // Reads have already been shut down on this socket.
534 // Allow setReadCallback(nullptr) to be called in this case, but don't
535 // allow a new callback to be set.
537 // For example, setReadCallback(nullptr) can happen after an error if we
538 // invoke some other error callback before invoking readError(). The other
539 // error callback that is invoked first may go ahead and clear the read
540 // callback before we get a chance to invoke readError().
541 if (callback != nullptr) {
542 return invalidState(callback);
544 assert((eventFlags_ & EventHandler::READ) == 0);
545 readCallback_ = nullptr;
549 DestructorGuard dg(this);
550 assert(eventBase_->isInEventBaseThread());
552 switch ((StateEnum)state_) {
553 case StateEnum::CONNECTING:
554 // For convenience, we allow the read callback to be set while we are
555 // still connecting. We just store the callback for now. Once the
556 // connection completes we'll register for read events.
557 readCallback_ = callback;
559 case StateEnum::ESTABLISHED:
561 readCallback_ = callback;
562 uint16_t oldFlags = eventFlags_;
564 eventFlags_ |= EventHandler::READ;
566 eventFlags_ &= ~EventHandler::READ;
569 // Update our registration if our flags have changed
570 if (eventFlags_ != oldFlags) {
571 // We intentionally ignore the return value here.
572 // updateEventRegistration() will move us into the error state if it
573 // fails, and we don't need to do anything else here afterwards.
574 (void)updateEventRegistration();
578 checkForImmediateRead();
582 case StateEnum::CLOSED:
583 case StateEnum::ERROR:
584 // We should never reach here. SHUT_READ should always be set
585 // if we are in STATE_CLOSED or STATE_ERROR.
587 return invalidState(callback);
588 case StateEnum::UNINIT:
589 // We do not allow setReadCallback() to be called before we start
591 return invalidState(callback);
594 // We don't put a default case in the switch statement, so that the compiler
595 // will warn us to update the switch statement if a new state is added.
596 return invalidState(callback);
599 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
600 return readCallback_;
603 void AsyncSocket::write(WriteCallback* callback,
604 const void* buf, size_t bytes, WriteFlags flags) {
606 op.iov_base = const_cast<void*>(buf);
608 writeImpl(callback, &op, 1, std::move(unique_ptr<IOBuf>()), flags);
611 void AsyncSocket::writev(WriteCallback* callback,
615 writeImpl(callback, vec, count, std::move(unique_ptr<IOBuf>()), flags);
618 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
620 size_t count = buf->countChainElements();
623 writeChainImpl(callback, vec, count, std::move(buf), flags);
625 iovec* vec = new iovec[count];
626 writeChainImpl(callback, vec, count, std::move(buf), flags);
631 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
632 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
633 const IOBuf* head = buf.get();
634 const IOBuf* next = head;
637 vec[i].iov_base = const_cast<uint8_t *>(next->data());
638 vec[i].iov_len = next->length();
639 // IOBuf can get confused by empty iovec buffers, so increment the
640 // output pointer only if the iovec buffer is non-empty. We could
641 // end the loop with i < count, but that's ok.
642 if (vec[i].iov_len != 0) {
646 } while (next != head);
647 writeImpl(callback, vec, i, std::move(buf), flags);
650 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
651 size_t count, unique_ptr<IOBuf>&& buf,
653 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
654 << ", callback=" << callback << ", count=" << count
655 << ", state=" << state_;
656 DestructorGuard dg(this);
657 unique_ptr<IOBuf>ioBuf(std::move(buf));
658 assert(eventBase_->isInEventBaseThread());
660 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
661 // No new writes may be performed after the write side of the socket has
664 // We could just call callback->writeError() here to fail just this write.
665 // However, fail hard and use invalidState() to fail all outstanding
666 // callbacks and move the socket into the error state. There's most likely
667 // a bug in the caller's code, so we abort everything rather than trying to
668 // proceed as best we can.
669 return invalidState(callback);
672 uint32_t countWritten = 0;
673 uint32_t partialWritten = 0;
674 int bytesWritten = 0;
675 bool mustRegister = false;
676 if (state_ == StateEnum::ESTABLISHED && !connecting()) {
677 if (writeReqHead_ == nullptr) {
678 // If we are established and there are no other writes pending,
679 // we can attempt to perform the write immediately.
680 assert(writeReqTail_ == nullptr);
681 assert((eventFlags_ & EventHandler::WRITE) == 0);
683 bytesWritten = performWrite(vec, count, flags,
684 &countWritten, &partialWritten);
685 if (bytesWritten < 0) {
686 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
687 withAddr("writev failed"), errno);
688 return failWrite(__func__, callback, 0, ex);
689 } else if (countWritten == count) {
690 // We successfully wrote everything.
691 // Invoke the callback and return.
693 callback->writeSuccess();
696 } // else { continue writing the next writeReq }
699 } else if (!connecting()) {
700 // Invalid state for writing
701 return invalidState(callback);
704 // Create a new WriteRequest to add to the queue
707 req = WriteRequest::newRequest(callback, vec + countWritten,
708 count - countWritten, std::move(ioBuf),
710 } catch (const std::exception& ex) {
711 // we mainly expect to catch std::bad_alloc here
712 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
713 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
714 return failWrite(__func__, callback, bytesWritten, tex);
716 req->consume(0, partialWritten, bytesWritten);
717 if (writeReqTail_ == nullptr) {
718 assert(writeReqHead_ == nullptr);
719 writeReqHead_ = writeReqTail_ = req;
721 writeReqTail_->append(req);
725 // Register for write events if are established and not currently
726 // waiting on write events
728 assert(state_ == StateEnum::ESTABLISHED);
729 assert((eventFlags_ & EventHandler::WRITE) == 0);
730 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
731 assert(state_ == StateEnum::ERROR);
734 if (sendTimeout_ > 0) {
735 // Schedule a timeout to fire if the write takes too long.
736 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
737 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
738 withAddr("failed to schedule send timeout"));
739 return failWrite(__func__, ex);
745 void AsyncSocket::close() {
746 VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
747 << ", state=" << state_ << ", shutdownFlags="
748 << std::hex << (int) shutdownFlags_;
750 // close() is only different from closeNow() when there are pending writes
751 // that need to drain before we can close. In all other cases, just call
754 // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
755 // STATE_ERROR if close() is invoked while a previous closeNow() or failure
756 // is still running. (e.g., If there are multiple pending writes, and we
757 // call writeError() on the first one, it may call close(). In this case we
758 // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
759 // writes will still be in the queue.)
761 // We only need to drain pending writes if we are still in STATE_CONNECTING
762 // or STATE_ESTABLISHED
763 if ((writeReqHead_ == nullptr) ||
764 !(state_ == StateEnum::CONNECTING ||
765 state_ == StateEnum::ESTABLISHED)) {
770 // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
771 // destroyed until close() returns.
772 DestructorGuard dg(this);
773 assert(eventBase_->isInEventBaseThread());
775 // Since there are write requests pending, we have to set the
776 // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
777 // connect finishes and we finish writing these requests.
779 // Set SHUT_READ to indicate that reads are shut down, and set the
780 // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
781 // pending writes complete.
782 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
784 // If a read callback is set, invoke readEOF() immediately to inform it that
785 // the socket has been closed and no more data can be read.
787 // Disable reads if they are enabled
788 if (!updateEventRegistration(0, EventHandler::READ)) {
789 // We're now in the error state; callbacks have been cleaned up
790 assert(state_ == StateEnum::ERROR);
791 assert(readCallback_ == nullptr);
793 ReadCallback* callback = readCallback_;
794 readCallback_ = nullptr;
800 void AsyncSocket::closeNow() {
801 VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
802 << ", state=" << state_ << ", shutdownFlags="
803 << std::hex << (int) shutdownFlags_;
804 DestructorGuard dg(this);
805 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
808 case StateEnum::ESTABLISHED:
809 case StateEnum::CONNECTING:
811 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
812 state_ = StateEnum::CLOSED;
814 // If the write timeout was set, cancel it.
815 writeTimeout_.cancelTimeout();
817 // If we are registered for I/O events, unregister.
818 if (eventFlags_ != EventHandler::NONE) {
819 eventFlags_ = EventHandler::NONE;
820 if (!updateEventRegistration()) {
821 // We will have been moved into the error state.
822 assert(state_ == StateEnum::ERROR);
828 ioHandler_.changeHandlerFD(-1);
832 if (connectCallback_) {
833 ConnectCallback* callback = connectCallback_;
834 connectCallback_ = nullptr;
835 callback->connectErr(socketClosedLocallyEx);
838 failAllWrites(socketClosedLocallyEx);
841 ReadCallback* callback = readCallback_;
842 readCallback_ = nullptr;
847 case StateEnum::CLOSED:
848 // Do nothing. It's possible that we are being called recursively
849 // from inside a callback that we invoked inside another call to close()
850 // that is still running.
852 case StateEnum::ERROR:
853 // Do nothing. The error handling code has performed (or is performing)
856 case StateEnum::UNINIT:
857 assert(eventFlags_ == EventHandler::NONE);
858 assert(connectCallback_ == nullptr);
859 assert(readCallback_ == nullptr);
860 assert(writeReqHead_ == nullptr);
861 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
862 state_ = StateEnum::CLOSED;
866 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
867 << ") called in unknown state " << state_;
870 void AsyncSocket::closeWithReset() {
871 // Enable SO_LINGER, with the linger timeout set to 0.
872 // This will trigger a TCP reset when we close the socket.
874 struct linger optLinger = {1, 0};
875 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
876 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
877 << "on " << fd_ << ": errno=" << errno;
881 // Then let closeNow() take care of the rest
885 void AsyncSocket::shutdownWrite() {
886 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
887 << ", state=" << state_ << ", shutdownFlags="
888 << std::hex << (int) shutdownFlags_;
890 // If there are no pending writes, shutdownWrite() is identical to
891 // shutdownWriteNow().
892 if (writeReqHead_ == nullptr) {
897 assert(eventBase_->isInEventBaseThread());
899 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
900 // shutdown will be performed once all writes complete.
901 shutdownFlags_ |= SHUT_WRITE_PENDING;
904 void AsyncSocket::shutdownWriteNow() {
905 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
906 << ", fd=" << fd_ << ", state=" << state_
907 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
909 if (shutdownFlags_ & SHUT_WRITE) {
910 // Writes are already shutdown; nothing else to do.
914 // If SHUT_READ is already set, just call closeNow() to completely
915 // close the socket. This can happen if close() was called with writes
916 // pending, and then shutdownWriteNow() is called before all pending writes
918 if (shutdownFlags_ & SHUT_READ) {
923 DestructorGuard dg(this);
924 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
926 switch (static_cast<StateEnum>(state_)) {
927 case StateEnum::ESTABLISHED:
929 shutdownFlags_ |= SHUT_WRITE;
931 // If the write timeout was set, cancel it.
932 writeTimeout_.cancelTimeout();
934 // If we are registered for write events, unregister.
935 if (!updateEventRegistration(0, EventHandler::WRITE)) {
936 // We will have been moved into the error state.
937 assert(state_ == StateEnum::ERROR);
941 // Shutdown writes on the file descriptor
942 ::shutdown(fd_, SHUT_WR);
944 // Immediately fail all write requests
945 failAllWrites(socketShutdownForWritesEx);
948 case StateEnum::CONNECTING:
950 // Set the SHUT_WRITE_PENDING flag.
951 // When the connection completes, it will check this flag,
952 // shutdown the write half of the socket, and then set SHUT_WRITE.
953 shutdownFlags_ |= SHUT_WRITE_PENDING;
955 // Immediately fail all write requests
956 failAllWrites(socketShutdownForWritesEx);
959 case StateEnum::UNINIT:
960 // Callers normally shouldn't call shutdownWriteNow() before the socket
961 // even starts connecting. Nonetheless, go ahead and set
962 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
963 // immediately shut down the write side of the socket.
964 shutdownFlags_ |= SHUT_WRITE_PENDING;
966 case StateEnum::CLOSED:
967 case StateEnum::ERROR:
968 // We should never get here. SHUT_WRITE should always be set
969 // in STATE_CLOSED and STATE_ERROR.
970 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
971 << ", fd=" << fd_ << ") in unexpected state " << state_
972 << " with SHUT_WRITE not set ("
973 << std::hex << (int) shutdownFlags_ << ")";
978 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
979 << fd_ << ") called in unknown state " << state_;
982 bool AsyncSocket::readable() const {
986 struct pollfd fds[1];
988 fds[0].events = POLLIN;
990 int rc = poll(fds, 1, 0);
994 bool AsyncSocket::isPending() const {
995 return ioHandler_.isPending();
998 bool AsyncSocket::hangup() const {
1000 // sanity check, no one should ask for hangup if we are not connected.
1004 #ifdef POLLRDHUP // Linux-only
1005 struct pollfd fds[1];
1007 fds[0].events = POLLRDHUP|POLLHUP;
1010 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1016 bool AsyncSocket::good() const {
1017 return ((state_ == StateEnum::CONNECTING ||
1018 state_ == StateEnum::ESTABLISHED) &&
1019 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1022 bool AsyncSocket::error() const {
1023 return (state_ == StateEnum::ERROR);
1026 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1027 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1028 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1029 << ", state=" << state_ << ", events="
1030 << std::hex << eventFlags_ << ")";
1031 assert(eventBase_ == nullptr);
1032 assert(eventBase->isInEventBaseThread());
1034 eventBase_ = eventBase;
1035 ioHandler_.attachEventBase(eventBase);
1036 writeTimeout_.attachEventBase(eventBase);
1039 void AsyncSocket::detachEventBase() {
1040 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1041 << ", old evb=" << eventBase_ << ", state=" << state_
1042 << ", events=" << std::hex << eventFlags_ << ")";
1043 assert(eventBase_ != nullptr);
1044 assert(eventBase_->isInEventBaseThread());
1046 eventBase_ = nullptr;
1047 ioHandler_.detachEventBase();
1048 writeTimeout_.detachEventBase();
1051 bool AsyncSocket::isDetachable() const {
1052 DCHECK(eventBase_ != nullptr);
1053 DCHECK(eventBase_->isInEventBaseThread());
1055 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1058 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1059 address->setFromLocalAddress(fd_);
1062 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1063 if (!addr_.isInitialized()) {
1064 addr_.setFromPeerAddress(fd_);
1069 int AsyncSocket::setNoDelay(bool noDelay) {
1071 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1072 << this << "(state=" << state_ << ")";
1077 int value = noDelay ? 1 : 0;
1078 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1079 int errnoCopy = errno;
1080 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1081 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1082 << strerror(errnoCopy);
1089 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1091 #ifndef TCP_CONGESTION
1092 #define TCP_CONGESTION 13
1096 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1097 << "socket " << this << "(state=" << state_ << ")";
1102 if (setsockopt(fd_, IPPROTO_TCP, TCP_CONGESTION, cname.c_str(),
1103 cname.length() + 1) != 0) {
1104 int errnoCopy = errno;
1105 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1106 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1107 << strerror(errnoCopy);
1114 int AsyncSocket::setQuickAck(bool quickack) {
1116 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1117 << this << "(state=" << state_ << ")";
1122 #ifdef TCP_QUICKACK // Linux-only
1123 int value = quickack ? 1 : 0;
1124 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1125 int errnoCopy = errno;
1126 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1127 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1128 << strerror(errnoCopy);
1138 int AsyncSocket::setSendBufSize(size_t bufsize) {
1140 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1141 << this << "(state=" << state_ << ")";
1145 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1146 int errnoCopy = errno;
1147 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1148 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1149 << strerror(errnoCopy);
1156 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1158 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1159 << this << "(state=" << state_ << ")";
1163 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1164 int errnoCopy = errno;
1165 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1166 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1167 << strerror(errnoCopy);
1174 int AsyncSocket::setTCPProfile(int profd) {
1176 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1177 << this << "(state=" << state_ << ")";
1181 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1182 int errnoCopy = errno;
1183 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1184 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1185 << strerror(errnoCopy);
1192 void AsyncSocket::ioReady(uint16_t events) noexcept {
1193 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd" << fd_
1194 << ", events=" << std::hex << events << ", state=" << state_;
1195 DestructorGuard dg(this);
1196 assert(events & EventHandler::READ_WRITE);
1197 assert(eventBase_->isInEventBaseThread());
1199 uint16_t relevantEvents = events & EventHandler::READ_WRITE;
1200 if (relevantEvents == EventHandler::READ) {
1202 } else if (relevantEvents == EventHandler::WRITE) {
1204 } else if (relevantEvents == EventHandler::READ_WRITE) {
1205 EventBase* originalEventBase = eventBase_;
1206 // If both read and write events are ready, process writes first.
1209 // Return now if handleWrite() detached us from our EventBase
1210 if (eventBase_ != originalEventBase) {
1214 // Only call handleRead() if a read callback is still installed.
1215 // (It's possible that the read callback was uninstalled during
1217 if (readCallback_) {
1221 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1222 << std::hex << events << "(this=" << this << ")";
1227 ssize_t AsyncSocket::performRead(void* buf, size_t buflen) {
1228 ssize_t bytes = recv(fd_, buf, buflen, MSG_DONTWAIT);
1230 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1231 // No more data to read right now.
1232 return READ_BLOCKING;
1237 appBytesReceived_ += bytes;
1242 void AsyncSocket::handleRead() noexcept {
1243 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1244 << ", state=" << state_;
1245 assert(state_ == StateEnum::ESTABLISHED);
1246 assert((shutdownFlags_ & SHUT_READ) == 0);
1247 assert(readCallback_ != nullptr);
1248 assert(eventFlags_ & EventHandler::READ);
1251 // - a read attempt would block
1252 // - readCallback_ is uninstalled
1253 // - the number of loop iterations exceeds the optional maximum
1254 // - this AsyncSocket is moved to another EventBase
1256 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1257 // which is why need to check for it here.
1259 // The last bullet point is slightly subtle. readDataAvailable() may also
1260 // detach this socket from this EventBase. However, before
1261 // readDataAvailable() returns another thread may pick it up, attach it to
1262 // a different EventBase, and install another readCallback_. We need to
1263 // exit immediately after readDataAvailable() returns if the eventBase_ has
1264 // changed. (The caller must perform some sort of locking to transfer the
1265 // AsyncSocket between threads properly. This will be sufficient to ensure
1266 // that this thread sees the updated eventBase_ variable after
1267 // readDataAvailable() returns.)
1268 uint16_t numReads = 0;
1269 EventBase* originalEventBase = eventBase_;
1270 while (readCallback_ && eventBase_ == originalEventBase) {
1271 // Get the buffer to read into.
1272 void* buf = nullptr;
1275 readCallback_->getReadBuffer(&buf, &buflen);
1276 } catch (const AsyncSocketException& ex) {
1277 return failRead(__func__, ex);
1278 } catch (const std::exception& ex) {
1279 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1280 string("ReadCallback::getReadBuffer() "
1281 "threw exception: ") +
1283 return failRead(__func__, tex);
1285 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1286 "ReadCallback::getReadBuffer() threw "
1287 "non-exception type");
1288 return failRead(__func__, ex);
1290 if (buf == nullptr || buflen == 0) {
1291 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1292 "ReadCallback::getReadBuffer() returned "
1294 return failRead(__func__, ex);
1298 ssize_t bytesRead = performRead(buf, buflen);
1299 if (bytesRead > 0) {
1300 readCallback_->readDataAvailable(bytesRead);
1301 // Fall through and continue around the loop if the read
1302 // completely filled the available buffer.
1303 // Note that readCallback_ may have been uninstalled or changed inside
1304 // readDataAvailable().
1305 if (size_t(bytesRead) < buflen) {
1308 } else if (bytesRead == READ_BLOCKING) {
1309 // No more data to read right now.
1311 } else if (bytesRead == READ_ERROR) {
1312 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1313 withAddr("recv() failed"), errno);
1314 return failRead(__func__, ex);
1316 assert(bytesRead == READ_EOF);
1318 shutdownFlags_ |= SHUT_READ;
1319 if (!updateEventRegistration(0, EventHandler::READ)) {
1320 // we've already been moved into STATE_ERROR
1321 assert(state_ == StateEnum::ERROR);
1322 assert(readCallback_ == nullptr);
1326 ReadCallback* callback = readCallback_;
1327 readCallback_ = nullptr;
1328 callback->readEOF();
1331 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1338 * This function attempts to write as much data as possible, until no more data
1341 * - If it sends all available data, it unregisters for write events, and stops
1342 * the writeTimeout_.
1344 * - If not all of the data can be sent immediately, it reschedules
1345 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1346 * registered for write events.
1348 void AsyncSocket::handleWrite() noexcept {
1349 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1350 << ", state=" << state_;
1351 if (state_ == StateEnum::CONNECTING) {
1357 assert(state_ == StateEnum::ESTABLISHED);
1358 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1359 assert(writeReqHead_ != nullptr);
1361 // Loop until we run out of write requests,
1362 // or until this socket is moved to another EventBase.
1363 // (See the comment in handleRead() explaining how this can happen.)
1364 EventBase* originalEventBase = eventBase_;
1365 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1366 uint32_t countWritten;
1367 uint32_t partialWritten;
1368 WriteFlags writeFlags = writeReqHead_->flags();
1369 if (writeReqHead_->getNext() != nullptr) {
1370 writeFlags = writeFlags | WriteFlags::CORK;
1372 int bytesWritten = performWrite(writeReqHead_->getOps(),
1373 writeReqHead_->getOpCount(),
1374 writeFlags, &countWritten, &partialWritten);
1375 if (bytesWritten < 0) {
1376 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1377 withAddr("writev() failed"), errno);
1378 return failWrite(__func__, ex);
1379 } else if (countWritten == writeReqHead_->getOpCount()) {
1380 // We finished this request
1381 WriteRequest* req = writeReqHead_;
1382 writeReqHead_ = req->getNext();
1384 if (writeReqHead_ == nullptr) {
1385 writeReqTail_ = nullptr;
1386 // This is the last write request.
1387 // Unregister for write events and cancel the send timer
1388 // before we invoke the callback. We have to update the state properly
1389 // before calling the callback, since it may want to detach us from
1391 if (eventFlags_ & EventHandler::WRITE) {
1392 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1393 assert(state_ == StateEnum::ERROR);
1396 // Stop the send timeout
1397 writeTimeout_.cancelTimeout();
1399 assert(!writeTimeout_.isScheduled());
1401 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
1402 // we finish sending the last write request.
1404 // We have to do this before invoking writeSuccess(), since
1405 // writeSuccess() may detach us from our EventBase.
1406 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
1407 assert(connectCallback_ == nullptr);
1408 shutdownFlags_ |= SHUT_WRITE;
1410 if (shutdownFlags_ & SHUT_READ) {
1411 // Reads have already been shutdown. Fully close the socket and
1412 // move to STATE_CLOSED.
1414 // Note: This code currently moves us to STATE_CLOSED even if
1415 // close() hasn't ever been called. This can occur if we have
1416 // received EOF from the peer and shutdownWrite() has been called
1417 // locally. Should we bother staying in STATE_ESTABLISHED in this
1418 // case, until close() is actually called? I can't think of a
1419 // reason why we would need to do so. No other operations besides
1420 // calling close() or destroying the socket can be performed at
1422 assert(readCallback_ == nullptr);
1423 state_ = StateEnum::CLOSED;
1425 ioHandler_.changeHandlerFD(-1);
1429 // Reads are still enabled, so we are only doing a half-shutdown
1430 ::shutdown(fd_, SHUT_WR);
1435 // Invoke the callback
1436 WriteCallback* callback = req->getCallback();
1439 callback->writeSuccess();
1441 // We'll continue around the loop, trying to write another request
1444 writeReqHead_->consume(countWritten, partialWritten, bytesWritten);
1445 // Stop after a partial write; it's highly likely that a subsequent write
1446 // attempt will just return EAGAIN.
1448 // Ensure that we are registered for write events.
1449 if ((eventFlags_ & EventHandler::WRITE) == 0) {
1450 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1451 assert(state_ == StateEnum::ERROR);
1456 // Reschedule the send timeout, since we have made some write progress.
1457 if (sendTimeout_ > 0) {
1458 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1459 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1460 withAddr("failed to reschedule write timeout"));
1461 return failWrite(__func__, ex);
1469 void AsyncSocket::checkForImmediateRead() noexcept {
1470 // We currently don't attempt to perform optimistic reads in AsyncSocket.
1471 // (However, note that some subclasses do override this method.)
1473 // Simply calling handleRead() here would be bad, as this would call
1474 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
1475 // buffer even though no data may be available. This would waste lots of
1476 // memory, since the buffer will sit around unused until the socket actually
1477 // becomes readable.
1479 // Checking if the socket is readable now also seems like it would probably
1480 // be a pessimism. In most cases it probably wouldn't be readable, and we
1481 // would just waste an extra system call. Even if it is readable, waiting to
1482 // find out from libevent on the next event loop doesn't seem that bad.
1485 void AsyncSocket::handleInitialReadWrite() noexcept {
1486 // Our callers should already be holding a DestructorGuard, but grab
1487 // one here just to make sure, in case one of our calling code paths ever
1489 DestructorGuard dg(this);
1491 // If we have a readCallback_, make sure we enable read events. We
1492 // may already be registered for reads if connectSuccess() set
1493 // the read calback.
1494 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
1495 assert(state_ == StateEnum::ESTABLISHED);
1496 assert((shutdownFlags_ & SHUT_READ) == 0);
1497 if (!updateEventRegistration(EventHandler::READ, 0)) {
1498 assert(state_ == StateEnum::ERROR);
1501 checkForImmediateRead();
1502 } else if (readCallback_ == nullptr) {
1503 // Unregister for read events.
1504 updateEventRegistration(0, EventHandler::READ);
1507 // If we have write requests pending, try to send them immediately.
1508 // Since we just finished accepting, there is a very good chance that we can
1509 // write without blocking.
1511 // However, we only process them if EventHandler::WRITE is not already set,
1512 // which means that we're already blocked on a write attempt. (This can
1513 // happen if connectSuccess() called write() before returning.)
1514 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
1515 // Call handleWrite() to perform write processing.
1517 } else if (writeReqHead_ == nullptr) {
1518 // Unregister for write event.
1519 updateEventRegistration(0, EventHandler::WRITE);
1523 void AsyncSocket::handleConnect() noexcept {
1524 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
1525 << ", state=" << state_;
1526 assert(state_ == StateEnum::CONNECTING);
1527 // SHUT_WRITE can never be set while we are still connecting;
1528 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
1530 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1532 // In case we had a connect timeout, cancel the timeout
1533 writeTimeout_.cancelTimeout();
1534 // We don't use a persistent registration when waiting on a connect event,
1535 // so we have been automatically unregistered now. Update eventFlags_ to
1537 assert(eventFlags_ == EventHandler::WRITE);
1538 eventFlags_ = EventHandler::NONE;
1540 // Call getsockopt() to check if the connect succeeded
1542 socklen_t len = sizeof(error);
1543 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
1545 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1546 withAddr("error calling getsockopt() after connect"),
1548 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1549 << fd_ << " host=" << addr_.describe()
1550 << ") exception:" << ex.what();
1551 return failConnect(__func__, ex);
1555 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1556 "connect failed", error);
1557 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1558 << fd_ << " host=" << addr_.describe()
1559 << ") exception: " << ex.what();
1560 return failConnect(__func__, ex);
1563 // Move into STATE_ESTABLISHED
1564 state_ = StateEnum::ESTABLISHED;
1566 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
1567 // perform, immediately shutdown the write half of the socket.
1568 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
1569 // SHUT_READ shouldn't be set. If close() is called on the socket while we
1570 // are still connecting we just abort the connect rather than waiting for
1572 assert((shutdownFlags_ & SHUT_READ) == 0);
1573 ::shutdown(fd_, SHUT_WR);
1574 shutdownFlags_ |= SHUT_WRITE;
1577 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
1578 << "successfully connected; state=" << state_;
1580 // Remember the EventBase we are attached to, before we start invoking any
1581 // callbacks (since the callbacks may call detachEventBase()).
1582 EventBase* originalEventBase = eventBase_;
1584 // Call the connect callback.
1585 if (connectCallback_) {
1586 ConnectCallback* callback = connectCallback_;
1587 connectCallback_ = nullptr;
1588 callback->connectSuccess();
1591 // Note that the connect callback may have changed our state.
1592 // (set or unset the read callback, called write(), closed the socket, etc.)
1593 // The following code needs to handle these situations correctly.
1595 // If the socket has been closed, readCallback_ and writeReqHead_ will
1596 // always be nullptr, so that will prevent us from trying to read or write.
1598 // The main thing to check for is if eventBase_ is still originalEventBase.
1599 // If not, we have been detached from this event base, so we shouldn't
1600 // perform any more operations.
1601 if (eventBase_ != originalEventBase) {
1605 handleInitialReadWrite();
1608 void AsyncSocket::timeoutExpired() noexcept {
1609 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
1610 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
1611 DestructorGuard dg(this);
1612 assert(eventBase_->isInEventBaseThread());
1614 if (state_ == StateEnum::CONNECTING) {
1615 // connect() timed out
1616 // Unregister for I/O events.
1617 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
1618 "connect timed out");
1619 failConnect(__func__, ex);
1621 // a normal write operation timed out
1622 assert(state_ == StateEnum::ESTABLISHED);
1623 AsyncSocketException ex(AsyncSocketException::TIMED_OUT, "write timed out");
1624 failWrite(__func__, ex);
1628 ssize_t AsyncSocket::performWrite(const iovec* vec,
1631 uint32_t* countWritten,
1632 uint32_t* partialWritten) {
1633 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
1634 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
1635 // (since it may terminate the program if the main program doesn't explicitly
1638 msg.msg_name = nullptr;
1639 msg.msg_namelen = 0;
1640 msg.msg_iov = const_cast<iovec *>(vec);
1641 #ifdef IOV_MAX // not defined on Android
1642 msg.msg_iovlen = std::min(count, (uint32_t)IOV_MAX);
1644 msg.msg_iovlen = std::min(count, (uint32_t)UIO_MAXIOV);
1646 msg.msg_control = nullptr;
1647 msg.msg_controllen = 0;
1650 int msg_flags = MSG_DONTWAIT;
1652 #ifdef MSG_NOSIGNAL // Linux-only
1653 msg_flags |= MSG_NOSIGNAL;
1654 if (isSet(flags, WriteFlags::CORK)) {
1655 // MSG_MORE tells the kernel we have more data to send, so wait for us to
1656 // give it the rest of the data rather than immediately sending a partial
1657 // frame, even when TCP_NODELAY is enabled.
1658 msg_flags |= MSG_MORE;
1661 if (isSet(flags, WriteFlags::EOR)) {
1662 // marks that this is the last byte of a record (response)
1663 msg_flags |= MSG_EOR;
1665 ssize_t totalWritten = ::sendmsg(fd_, &msg, msg_flags);
1666 if (totalWritten < 0) {
1667 if (errno == EAGAIN) {
1668 // TCP buffer is full; we can't write any more data right now.
1670 *partialWritten = 0;
1675 *partialWritten = 0;
1679 appBytesWritten_ += totalWritten;
1681 uint32_t bytesWritten;
1683 for (bytesWritten = totalWritten, n = 0; n < count; ++n) {
1684 const iovec* v = vec + n;
1685 if (v->iov_len > bytesWritten) {
1686 // Partial write finished in the middle of this iovec
1688 *partialWritten = bytesWritten;
1689 return totalWritten;
1692 bytesWritten -= v->iov_len;
1695 assert(bytesWritten == 0);
1697 *partialWritten = 0;
1698 return totalWritten;
1702 * Re-register the EventHandler after eventFlags_ has changed.
1704 * If an error occurs, fail() is called to move the socket into the error state
1705 * and call all currently installed callbacks. After an error, the
1706 * AsyncSocket is completely unregistered.
1708 * @return Returns true on succcess, or false on error.
1710 bool AsyncSocket::updateEventRegistration() {
1711 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
1712 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
1713 << ", events=" << std::hex << eventFlags_;
1714 assert(eventBase_->isInEventBaseThread());
1715 if (eventFlags_ == EventHandler::NONE) {
1716 ioHandler_.unregisterHandler();
1720 // Always register for persistent events, so we don't have to re-register
1721 // after being called back.
1722 if (!ioHandler_.registerHandler(eventFlags_ | EventHandler::PERSIST)) {
1723 eventFlags_ = EventHandler::NONE; // we're not registered after error
1724 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1725 withAddr("failed to update AsyncSocket event registration"));
1726 fail("updateEventRegistration", ex);
1733 bool AsyncSocket::updateEventRegistration(uint16_t enable,
1735 uint16_t oldFlags = eventFlags_;
1736 eventFlags_ |= enable;
1737 eventFlags_ &= ~disable;
1738 if (eventFlags_ == oldFlags) {
1741 return updateEventRegistration();
1745 void AsyncSocket::startFail() {
1746 // startFail() should only be called once
1747 assert(state_ != StateEnum::ERROR);
1748 assert(getDestructorGuardCount() > 0);
1749 state_ = StateEnum::ERROR;
1750 // Ensure that SHUT_READ and SHUT_WRITE are set,
1751 // so all future attempts to read or write will be rejected
1752 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1754 if (eventFlags_ != EventHandler::NONE) {
1755 eventFlags_ = EventHandler::NONE;
1756 ioHandler_.unregisterHandler();
1758 writeTimeout_.cancelTimeout();
1761 ioHandler_.changeHandlerFD(-1);
1766 void AsyncSocket::finishFail() {
1767 assert(state_ == StateEnum::ERROR);
1768 assert(getDestructorGuardCount() > 0);
1770 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1771 withAddr("socket closing after error"));
1772 if (connectCallback_) {
1773 ConnectCallback* callback = connectCallback_;
1774 connectCallback_ = nullptr;
1775 callback->connectErr(ex);
1780 if (readCallback_) {
1781 ReadCallback* callback = readCallback_;
1782 readCallback_ = nullptr;
1783 callback->readErr(ex);
1787 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
1788 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1789 << state_ << " host=" << addr_.describe()
1790 << "): failed in " << fn << "(): "
1796 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
1797 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1798 << state_ << " host=" << addr_.describe()
1799 << "): failed while connecting in " << fn << "(): "
1803 if (connectCallback_ != nullptr) {
1804 ConnectCallback* callback = connectCallback_;
1805 connectCallback_ = nullptr;
1806 callback->connectErr(ex);
1812 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
1813 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1814 << state_ << " host=" << addr_.describe()
1815 << "): failed while reading in " << fn << "(): "
1819 if (readCallback_ != nullptr) {
1820 ReadCallback* callback = readCallback_;
1821 readCallback_ = nullptr;
1822 callback->readErr(ex);
1828 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
1829 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1830 << state_ << " host=" << addr_.describe()
1831 << "): failed while writing in " << fn << "(): "
1835 // Only invoke the first write callback, since the error occurred while
1836 // writing this request. Let any other pending write callbacks be invoked in
1838 if (writeReqHead_ != nullptr) {
1839 WriteRequest* req = writeReqHead_;
1840 writeReqHead_ = req->getNext();
1841 WriteCallback* callback = req->getCallback();
1842 uint32_t bytesWritten = req->getBytesWritten();
1845 callback->writeErr(bytesWritten, ex);
1852 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
1853 size_t bytesWritten,
1854 const AsyncSocketException& ex) {
1855 // This version of failWrite() is used when the failure occurs before
1856 // we've added the callback to writeReqHead_.
1857 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1858 << state_ << " host=" << addr_.describe()
1859 <<"): failed while writing in " << fn << "(): "
1863 if (callback != nullptr) {
1864 callback->writeErr(bytesWritten, ex);
1870 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
1871 // Invoke writeError() on all write callbacks.
1872 // This is used when writes are forcibly shutdown with write requests
1873 // pending, or when an error occurs with writes pending.
1874 while (writeReqHead_ != nullptr) {
1875 WriteRequest* req = writeReqHead_;
1876 writeReqHead_ = req->getNext();
1877 WriteCallback* callback = req->getCallback();
1879 callback->writeErr(req->getBytesWritten(), ex);
1885 void AsyncSocket::invalidState(ConnectCallback* callback) {
1886 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
1887 << "): connect() called in invalid state " << state_;
1890 * The invalidState() methods don't use the normal failure mechanisms,
1891 * since we don't know what state we are in. We don't want to call
1892 * startFail()/finishFail() recursively if we are already in the middle of
1896 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
1897 "connect() called with socket in invalid state");
1898 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1900 callback->connectErr(ex);
1903 // We can't use failConnect() here since connectCallback_
1904 // may already be set to another callback. Invoke this ConnectCallback
1905 // here; any other connectCallback_ will be invoked in finishFail()
1908 callback->connectErr(ex);
1914 void AsyncSocket::invalidState(ReadCallback* callback) {
1915 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
1916 << "): setReadCallback(" << callback
1917 << ") called in invalid state " << state_;
1919 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1920 "setReadCallback() called with socket in "
1922 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1924 callback->readErr(ex);
1929 callback->readErr(ex);
1935 void AsyncSocket::invalidState(WriteCallback* callback) {
1936 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
1937 << "): write() called in invalid state " << state_;
1939 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1940 withAddr("write() called with socket in invalid state"));
1941 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1943 callback->writeErr(0, ex);
1948 callback->writeErr(0, ex);
1954 void AsyncSocket::doClose() {
1955 if (fd_ == -1) return;
1956 if (shutdownSocketSet_) {
1957 shutdownSocketSet_->close(fd_);
1964 std::ostream& operator << (std::ostream& os,
1965 const AsyncSocket::StateEnum& state) {
1966 os << static_cast<int>(state);
1970 std::string AsyncSocket::withAddr(const std::string& s) {
1971 // Don't use addr_ directly because it may not be initialized
1972 // e.g. if constructed from fd
1973 folly::SocketAddress peer, local;
1975 getPeerAddress(&peer);
1976 getLocalAddress(&local);
1977 } catch (const std::exception&) {
1982 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";