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="
225 state_ = StateEnum::ESTABLISHED;
228 // init() method, since constructor forwarding isn't supported in most
230 void AsyncSocket::init() {
231 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
233 state_ = StateEnum::UNINIT;
234 eventFlags_ = EventHandler::NONE;
237 maxReadsPerEvent_ = 16;
238 connectCallback_ = nullptr;
239 readCallback_ = nullptr;
240 writeReqHead_ = nullptr;
241 writeReqTail_ = nullptr;
242 shutdownSocketSet_ = nullptr;
243 appBytesWritten_ = 0;
244 appBytesReceived_ = 0;
247 AsyncSocket::~AsyncSocket() {
248 VLOG(7) << "actual destruction of AsyncSocket(this=" << this
249 << ", evb=" << eventBase_ << ", fd=" << fd_
250 << ", state=" << state_ << ")";
253 void AsyncSocket::destroy() {
254 VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
255 << ", fd=" << fd_ << ", state=" << state_;
256 // When destroy is called, close the socket immediately
259 // Then call DelayedDestruction::destroy() to take care of
260 // whether or not we need immediate or delayed destruction
261 DelayedDestruction::destroy();
264 int AsyncSocket::detachFd() {
265 VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
266 << ", evb=" << eventBase_ << ", state=" << state_
267 << ", events=" << std::hex << eventFlags_ << ")";
268 // Extract the fd, and set fd_ to -1 first, so closeNow() won't
269 // actually close the descriptor.
270 if (shutdownSocketSet_) {
271 shutdownSocketSet_->remove(fd_);
275 // Call closeNow() to invoke all pending callbacks with an error.
277 // Update the EventHandler to stop using this fd.
278 // This can only be done after closeNow() unregisters the handler.
279 ioHandler_.changeHandlerFD(-1);
283 void AsyncSocket::setShutdownSocketSet(ShutdownSocketSet* newSS) {
284 if (shutdownSocketSet_ == newSS) {
287 if (shutdownSocketSet_ && fd_ != -1) {
288 shutdownSocketSet_->remove(fd_);
290 shutdownSocketSet_ = newSS;
291 if (shutdownSocketSet_ && fd_ != -1) {
292 shutdownSocketSet_->add(fd_);
296 void AsyncSocket::connect(ConnectCallback* callback,
297 const folly::SocketAddress& address,
299 const OptionMap &options,
300 const folly::SocketAddress& bindAddr) noexcept {
301 DestructorGuard dg(this);
302 assert(eventBase_->isInEventBaseThread());
306 // Make sure we're in the uninitialized state
307 if (state_ != StateEnum::UNINIT) {
308 return invalidState(callback);
312 state_ = StateEnum::CONNECTING;
313 connectCallback_ = callback;
315 sockaddr_storage addrStorage;
316 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
320 // Technically the first parameter should actually be a protocol family
321 // constant (PF_xxx) rather than an address family (AF_xxx), but the
322 // distinction is mainly just historical. In pretty much all
323 // implementations the PF_foo and AF_foo constants are identical.
324 fd_ = socket(address.getFamily(), SOCK_STREAM, 0);
326 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
327 withAddr("failed to create socket"), errno);
329 if (shutdownSocketSet_) {
330 shutdownSocketSet_->add(fd_);
332 ioHandler_.changeHandlerFD(fd_);
334 // Set the FD_CLOEXEC flag so that the socket will be closed if the program
335 // later forks and execs.
336 int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
338 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
339 withAddr("failed to set close-on-exec flag"),
343 // Put the socket in non-blocking mode
344 int flags = fcntl(fd_, F_GETFL, 0);
346 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
347 withAddr("failed to get socket flags"), errno);
349 rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
351 throw AsyncSocketException(
352 AsyncSocketException::INTERNAL_ERROR,
353 withAddr("failed to put socket in non-blocking mode"),
357 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
358 // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
359 rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
361 throw AsyncSocketException(
362 AsyncSocketException::INTERNAL_ERROR,
363 "failed to enable F_SETNOSIGPIPE on socket",
368 // By default, turn on TCP_NODELAY
369 // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
370 // setNoDelay() will log an error message if it fails.
371 if (address.getFamily() != AF_UNIX) {
372 (void)setNoDelay(true);
375 VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
376 << ", fd=" << fd_ << ", host=" << address.describe().c_str();
379 if (bindAddr != anyAddress) {
381 if (::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
383 throw AsyncSocketException(
384 AsyncSocketException::NOT_OPEN,
385 "failed to setsockopt prior to bind on " + bindAddr.describe(),
389 bindAddr.getAddress(&addrStorage);
391 if (::bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
393 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
394 "failed to bind to async socket: " +
400 // Apply the additional options if any.
401 for (const auto& opt: options) {
402 int rv = opt.first.apply(fd_, opt.second);
404 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
405 withAddr("failed to set socket option"),
410 // Perform the connect()
411 address.getAddress(&addrStorage);
413 rv = ::connect(fd_, saddr, address.getActualSize());
415 if (errno == EINPROGRESS) {
416 // Connection in progress.
418 // Start a timer in case the connection takes too long.
419 if (!writeTimeout_.scheduleTimeout(timeout)) {
420 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
421 withAddr("failed to schedule AsyncSocket connect timeout"));
425 // Register for write events, so we'll
426 // be notified when the connection finishes/fails.
427 // Note that we don't register for a persistent event here.
428 assert(eventFlags_ == EventHandler::NONE);
429 eventFlags_ = EventHandler::WRITE;
430 if (!ioHandler_.registerHandler(eventFlags_)) {
431 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
432 withAddr("failed to register AsyncSocket connect handler"));
436 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
437 "connect failed (immediately)", errno);
441 // If we're still here the connect() succeeded immediately.
442 // Fall through to call the callback outside of this try...catch block
443 } catch (const AsyncSocketException& ex) {
444 return failConnect(__func__, ex);
445 } catch (const std::exception& ex) {
446 // shouldn't happen, but handle it just in case
447 VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
448 << "): unexpected " << typeid(ex).name() << " exception: "
450 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
451 withAddr(string("unexpected exception: ") +
453 return failConnect(__func__, tex);
456 // The connection succeeded immediately
457 // The read callback may not have been set yet, and no writes may be pending
458 // yet, so we don't have to register for any events at the moment.
459 VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
460 assert(readCallback_ == nullptr);
461 assert(writeReqHead_ == nullptr);
462 state_ = StateEnum::ESTABLISHED;
464 connectCallback_ = nullptr;
465 callback->connectSuccess();
469 void AsyncSocket::connect(ConnectCallback* callback,
470 const string& ip, uint16_t port,
472 const OptionMap &options) noexcept {
473 DestructorGuard dg(this);
475 connectCallback_ = callback;
476 connect(callback, folly::SocketAddress(ip, port), timeout, options);
477 } catch (const std::exception& ex) {
478 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
480 return failConnect(__func__, tex);
484 void AsyncSocket::cancelConnect() {
485 connectCallback_ = nullptr;
486 if (state_ == StateEnum::CONNECTING) {
491 void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
492 sendTimeout_ = milliseconds;
493 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
495 // If we are currently pending on write requests, immediately update
496 // writeTimeout_ with the new value.
497 if ((eventFlags_ & EventHandler::WRITE) &&
498 (state_ != StateEnum::CONNECTING)) {
499 assert(state_ == StateEnum::ESTABLISHED);
500 assert((shutdownFlags_ & SHUT_WRITE) == 0);
501 if (sendTimeout_ > 0) {
502 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
503 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
504 withAddr("failed to reschedule send timeout in setSendTimeout"));
505 return failWrite(__func__, ex);
508 writeTimeout_.cancelTimeout();
513 void AsyncSocket::setReadCB(ReadCallback *callback) {
514 VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
515 << ", callback=" << callback << ", state=" << state_;
517 // Short circuit if callback is the same as the existing readCallback_.
519 // Note that this is needed for proper functioning during some cleanup cases.
520 // During cleanup we allow setReadCallback(nullptr) to be called even if the
521 // read callback is already unset and we have been detached from an event
522 // base. This check prevents us from asserting
523 // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
524 if (callback == readCallback_) {
528 if (shutdownFlags_ & SHUT_READ) {
529 // Reads have already been shut down on this socket.
531 // Allow setReadCallback(nullptr) to be called in this case, but don't
532 // allow a new callback to be set.
534 // For example, setReadCallback(nullptr) can happen after an error if we
535 // invoke some other error callback before invoking readError(). The other
536 // error callback that is invoked first may go ahead and clear the read
537 // callback before we get a chance to invoke readError().
538 if (callback != nullptr) {
539 return invalidState(callback);
541 assert((eventFlags_ & EventHandler::READ) == 0);
542 readCallback_ = nullptr;
546 DestructorGuard dg(this);
547 assert(eventBase_->isInEventBaseThread());
549 switch ((StateEnum)state_) {
550 case StateEnum::CONNECTING:
551 // For convenience, we allow the read callback to be set while we are
552 // still connecting. We just store the callback for now. Once the
553 // connection completes we'll register for read events.
554 readCallback_ = callback;
556 case StateEnum::ESTABLISHED:
558 readCallback_ = callback;
559 uint16_t oldFlags = eventFlags_;
561 eventFlags_ |= EventHandler::READ;
563 eventFlags_ &= ~EventHandler::READ;
566 // Update our registration if our flags have changed
567 if (eventFlags_ != oldFlags) {
568 // We intentionally ignore the return value here.
569 // updateEventRegistration() will move us into the error state if it
570 // fails, and we don't need to do anything else here afterwards.
571 (void)updateEventRegistration();
575 checkForImmediateRead();
579 case StateEnum::CLOSED:
580 case StateEnum::ERROR:
581 // We should never reach here. SHUT_READ should always be set
582 // if we are in STATE_CLOSED or STATE_ERROR.
584 return invalidState(callback);
585 case StateEnum::UNINIT:
586 // We do not allow setReadCallback() to be called before we start
588 return invalidState(callback);
591 // We don't put a default case in the switch statement, so that the compiler
592 // will warn us to update the switch statement if a new state is added.
593 return invalidState(callback);
596 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
597 return readCallback_;
600 void AsyncSocket::write(WriteCallback* callback,
601 const void* buf, size_t bytes, WriteFlags flags) {
603 op.iov_base = const_cast<void*>(buf);
605 writeImpl(callback, &op, 1, std::move(unique_ptr<IOBuf>()), flags);
608 void AsyncSocket::writev(WriteCallback* callback,
612 writeImpl(callback, vec, count, std::move(unique_ptr<IOBuf>()), flags);
615 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
617 size_t count = buf->countChainElements();
620 writeChainImpl(callback, vec, count, std::move(buf), flags);
622 iovec* vec = new iovec[count];
623 writeChainImpl(callback, vec, count, std::move(buf), flags);
628 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
629 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
630 const IOBuf* head = buf.get();
631 const IOBuf* next = head;
634 vec[i].iov_base = const_cast<uint8_t *>(next->data());
635 vec[i].iov_len = next->length();
636 // IOBuf can get confused by empty iovec buffers, so increment the
637 // output pointer only if the iovec buffer is non-empty. We could
638 // end the loop with i < count, but that's ok.
639 if (vec[i].iov_len != 0) {
643 } while (next != head);
644 writeImpl(callback, vec, i, std::move(buf), flags);
647 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
648 size_t count, unique_ptr<IOBuf>&& buf,
650 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
651 << ", callback=" << callback << ", count=" << count
652 << ", state=" << state_;
653 DestructorGuard dg(this);
654 unique_ptr<IOBuf>ioBuf(std::move(buf));
655 assert(eventBase_->isInEventBaseThread());
657 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
658 // No new writes may be performed after the write side of the socket has
661 // We could just call callback->writeError() here to fail just this write.
662 // However, fail hard and use invalidState() to fail all outstanding
663 // callbacks and move the socket into the error state. There's most likely
664 // a bug in the caller's code, so we abort everything rather than trying to
665 // proceed as best we can.
666 return invalidState(callback);
669 uint32_t countWritten = 0;
670 uint32_t partialWritten = 0;
671 int bytesWritten = 0;
672 bool mustRegister = false;
673 if (state_ == StateEnum::ESTABLISHED && !connecting()) {
674 if (writeReqHead_ == nullptr) {
675 // If we are established and there are no other writes pending,
676 // we can attempt to perform the write immediately.
677 assert(writeReqTail_ == nullptr);
678 assert((eventFlags_ & EventHandler::WRITE) == 0);
680 bytesWritten = performWrite(vec, count, flags,
681 &countWritten, &partialWritten);
682 if (bytesWritten < 0) {
683 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
684 withAddr("writev failed"), errno);
685 return failWrite(__func__, callback, 0, ex);
686 } else if (countWritten == count) {
687 // We successfully wrote everything.
688 // Invoke the callback and return.
690 callback->writeSuccess();
693 } // else { continue writing the next writeReq }
696 } else if (!connecting()) {
697 // Invalid state for writing
698 return invalidState(callback);
701 // Create a new WriteRequest to add to the queue
704 req = WriteRequest::newRequest(callback, vec + countWritten,
705 count - countWritten, std::move(ioBuf),
707 } catch (const std::exception& ex) {
708 // we mainly expect to catch std::bad_alloc here
709 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
710 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
711 return failWrite(__func__, callback, bytesWritten, tex);
713 req->consume(0, partialWritten, bytesWritten);
714 if (writeReqTail_ == nullptr) {
715 assert(writeReqHead_ == nullptr);
716 writeReqHead_ = writeReqTail_ = req;
718 writeReqTail_->append(req);
722 // Register for write events if are established and not currently
723 // waiting on write events
725 assert(state_ == StateEnum::ESTABLISHED);
726 assert((eventFlags_ & EventHandler::WRITE) == 0);
727 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
728 assert(state_ == StateEnum::ERROR);
731 if (sendTimeout_ > 0) {
732 // Schedule a timeout to fire if the write takes too long.
733 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
734 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
735 withAddr("failed to schedule send timeout"));
736 return failWrite(__func__, ex);
742 void AsyncSocket::close() {
743 VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
744 << ", state=" << state_ << ", shutdownFlags="
745 << std::hex << (int) shutdownFlags_;
747 // close() is only different from closeNow() when there are pending writes
748 // that need to drain before we can close. In all other cases, just call
751 // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
752 // STATE_ERROR if close() is invoked while a previous closeNow() or failure
753 // is still running. (e.g., If there are multiple pending writes, and we
754 // call writeError() on the first one, it may call close(). In this case we
755 // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
756 // writes will still be in the queue.)
758 // We only need to drain pending writes if we are still in STATE_CONNECTING
759 // or STATE_ESTABLISHED
760 if ((writeReqHead_ == nullptr) ||
761 !(state_ == StateEnum::CONNECTING ||
762 state_ == StateEnum::ESTABLISHED)) {
767 // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
768 // destroyed until close() returns.
769 DestructorGuard dg(this);
770 assert(eventBase_->isInEventBaseThread());
772 // Since there are write requests pending, we have to set the
773 // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
774 // connect finishes and we finish writing these requests.
776 // Set SHUT_READ to indicate that reads are shut down, and set the
777 // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
778 // pending writes complete.
779 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
781 // If a read callback is set, invoke readEOF() immediately to inform it that
782 // the socket has been closed and no more data can be read.
784 // Disable reads if they are enabled
785 if (!updateEventRegistration(0, EventHandler::READ)) {
786 // We're now in the error state; callbacks have been cleaned up
787 assert(state_ == StateEnum::ERROR);
788 assert(readCallback_ == nullptr);
790 ReadCallback* callback = readCallback_;
791 readCallback_ = nullptr;
797 void AsyncSocket::closeNow() {
798 VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
799 << ", state=" << state_ << ", shutdownFlags="
800 << std::hex << (int) shutdownFlags_;
801 DestructorGuard dg(this);
802 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
805 case StateEnum::ESTABLISHED:
806 case StateEnum::CONNECTING:
808 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
809 state_ = StateEnum::CLOSED;
811 // If the write timeout was set, cancel it.
812 writeTimeout_.cancelTimeout();
814 // If we are registered for I/O events, unregister.
815 if (eventFlags_ != EventHandler::NONE) {
816 eventFlags_ = EventHandler::NONE;
817 if (!updateEventRegistration()) {
818 // We will have been moved into the error state.
819 assert(state_ == StateEnum::ERROR);
825 ioHandler_.changeHandlerFD(-1);
829 if (connectCallback_) {
830 ConnectCallback* callback = connectCallback_;
831 connectCallback_ = nullptr;
832 callback->connectErr(socketClosedLocallyEx);
835 failAllWrites(socketClosedLocallyEx);
838 ReadCallback* callback = readCallback_;
839 readCallback_ = nullptr;
844 case StateEnum::CLOSED:
845 // Do nothing. It's possible that we are being called recursively
846 // from inside a callback that we invoked inside another call to close()
847 // that is still running.
849 case StateEnum::ERROR:
850 // Do nothing. The error handling code has performed (or is performing)
853 case StateEnum::UNINIT:
854 assert(eventFlags_ == EventHandler::NONE);
855 assert(connectCallback_ == nullptr);
856 assert(readCallback_ == nullptr);
857 assert(writeReqHead_ == nullptr);
858 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
859 state_ = StateEnum::CLOSED;
863 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
864 << ") called in unknown state " << state_;
867 void AsyncSocket::closeWithReset() {
868 // Enable SO_LINGER, with the linger timeout set to 0.
869 // This will trigger a TCP reset when we close the socket.
871 struct linger optLinger = {1, 0};
872 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
873 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
874 << "on " << fd_ << ": errno=" << errno;
878 // Then let closeNow() take care of the rest
882 void AsyncSocket::shutdownWrite() {
883 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
884 << ", state=" << state_ << ", shutdownFlags="
885 << std::hex << (int) shutdownFlags_;
887 // If there are no pending writes, shutdownWrite() is identical to
888 // shutdownWriteNow().
889 if (writeReqHead_ == nullptr) {
894 assert(eventBase_->isInEventBaseThread());
896 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
897 // shutdown will be performed once all writes complete.
898 shutdownFlags_ |= SHUT_WRITE_PENDING;
901 void AsyncSocket::shutdownWriteNow() {
902 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
903 << ", fd=" << fd_ << ", state=" << state_
904 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
906 if (shutdownFlags_ & SHUT_WRITE) {
907 // Writes are already shutdown; nothing else to do.
911 // If SHUT_READ is already set, just call closeNow() to completely
912 // close the socket. This can happen if close() was called with writes
913 // pending, and then shutdownWriteNow() is called before all pending writes
915 if (shutdownFlags_ & SHUT_READ) {
920 DestructorGuard dg(this);
921 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
923 switch (static_cast<StateEnum>(state_)) {
924 case StateEnum::ESTABLISHED:
926 shutdownFlags_ |= SHUT_WRITE;
928 // If the write timeout was set, cancel it.
929 writeTimeout_.cancelTimeout();
931 // If we are registered for write events, unregister.
932 if (!updateEventRegistration(0, EventHandler::WRITE)) {
933 // We will have been moved into the error state.
934 assert(state_ == StateEnum::ERROR);
938 // Shutdown writes on the file descriptor
939 ::shutdown(fd_, SHUT_WR);
941 // Immediately fail all write requests
942 failAllWrites(socketShutdownForWritesEx);
945 case StateEnum::CONNECTING:
947 // Set the SHUT_WRITE_PENDING flag.
948 // When the connection completes, it will check this flag,
949 // shutdown the write half of the socket, and then set SHUT_WRITE.
950 shutdownFlags_ |= SHUT_WRITE_PENDING;
952 // Immediately fail all write requests
953 failAllWrites(socketShutdownForWritesEx);
956 case StateEnum::UNINIT:
957 // Callers normally shouldn't call shutdownWriteNow() before the socket
958 // even starts connecting. Nonetheless, go ahead and set
959 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
960 // immediately shut down the write side of the socket.
961 shutdownFlags_ |= SHUT_WRITE_PENDING;
963 case StateEnum::CLOSED:
964 case StateEnum::ERROR:
965 // We should never get here. SHUT_WRITE should always be set
966 // in STATE_CLOSED and STATE_ERROR.
967 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
968 << ", fd=" << fd_ << ") in unexpected state " << state_
969 << " with SHUT_WRITE not set ("
970 << std::hex << (int) shutdownFlags_ << ")";
975 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
976 << fd_ << ") called in unknown state " << state_;
979 bool AsyncSocket::readable() const {
983 struct pollfd fds[1];
985 fds[0].events = POLLIN;
987 int rc = poll(fds, 1, 0);
991 bool AsyncSocket::isPending() const {
992 return ioHandler_.isPending();
995 bool AsyncSocket::hangup() const {
997 // sanity check, no one should ask for hangup if we are not connected.
1001 #ifdef POLLRDHUP // Linux-only
1002 struct pollfd fds[1];
1004 fds[0].events = POLLRDHUP|POLLHUP;
1007 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1013 bool AsyncSocket::good() const {
1014 return ((state_ == StateEnum::CONNECTING ||
1015 state_ == StateEnum::ESTABLISHED) &&
1016 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1019 bool AsyncSocket::error() const {
1020 return (state_ == StateEnum::ERROR);
1023 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1024 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1025 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1026 << ", state=" << state_ << ", events="
1027 << std::hex << eventFlags_ << ")";
1028 assert(eventBase_ == nullptr);
1029 assert(eventBase->isInEventBaseThread());
1031 eventBase_ = eventBase;
1032 ioHandler_.attachEventBase(eventBase);
1033 writeTimeout_.attachEventBase(eventBase);
1036 void AsyncSocket::detachEventBase() {
1037 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1038 << ", old evb=" << eventBase_ << ", state=" << state_
1039 << ", events=" << std::hex << eventFlags_ << ")";
1040 assert(eventBase_ != nullptr);
1041 assert(eventBase_->isInEventBaseThread());
1043 eventBase_ = nullptr;
1044 ioHandler_.detachEventBase();
1045 writeTimeout_.detachEventBase();
1048 bool AsyncSocket::isDetachable() const {
1049 DCHECK(eventBase_ != nullptr);
1050 DCHECK(eventBase_->isInEventBaseThread());
1052 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1055 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1056 address->setFromLocalAddress(fd_);
1059 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1060 if (!addr_.isInitialized()) {
1061 addr_.setFromPeerAddress(fd_);
1066 int AsyncSocket::setNoDelay(bool noDelay) {
1068 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1069 << this << "(state=" << state_ << ")";
1074 int value = noDelay ? 1 : 0;
1075 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1076 int errnoCopy = errno;
1077 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1078 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1079 << strerror(errnoCopy);
1086 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1088 #ifndef TCP_CONGESTION
1089 #define TCP_CONGESTION 13
1093 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1094 << "socket " << this << "(state=" << state_ << ")";
1099 if (setsockopt(fd_, IPPROTO_TCP, TCP_CONGESTION, cname.c_str(),
1100 cname.length() + 1) != 0) {
1101 int errnoCopy = errno;
1102 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1103 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1104 << strerror(errnoCopy);
1111 int AsyncSocket::setQuickAck(bool quickack) {
1113 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1114 << this << "(state=" << state_ << ")";
1119 #ifdef TCP_QUICKACK // Linux-only
1120 int value = quickack ? 1 : 0;
1121 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1122 int errnoCopy = errno;
1123 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1124 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1125 << strerror(errnoCopy);
1135 int AsyncSocket::setSendBufSize(size_t bufsize) {
1137 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1138 << this << "(state=" << state_ << ")";
1142 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1143 int errnoCopy = errno;
1144 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1145 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1146 << strerror(errnoCopy);
1153 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1155 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1156 << this << "(state=" << state_ << ")";
1160 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1161 int errnoCopy = errno;
1162 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1163 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1164 << strerror(errnoCopy);
1171 int AsyncSocket::setTCPProfile(int profd) {
1173 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1174 << this << "(state=" << state_ << ")";
1178 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1179 int errnoCopy = errno;
1180 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1181 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1182 << strerror(errnoCopy);
1189 void AsyncSocket::ioReady(uint16_t events) noexcept {
1190 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd" << fd_
1191 << ", events=" << std::hex << events << ", state=" << state_;
1192 DestructorGuard dg(this);
1193 assert(events & EventHandler::READ_WRITE);
1194 assert(eventBase_->isInEventBaseThread());
1196 uint16_t relevantEvents = events & EventHandler::READ_WRITE;
1197 if (relevantEvents == EventHandler::READ) {
1199 } else if (relevantEvents == EventHandler::WRITE) {
1201 } else if (relevantEvents == EventHandler::READ_WRITE) {
1202 EventBase* originalEventBase = eventBase_;
1203 // If both read and write events are ready, process writes first.
1206 // Return now if handleWrite() detached us from our EventBase
1207 if (eventBase_ != originalEventBase) {
1211 // Only call handleRead() if a read callback is still installed.
1212 // (It's possible that the read callback was uninstalled during
1214 if (readCallback_) {
1218 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1219 << std::hex << events << "(this=" << this << ")";
1224 ssize_t AsyncSocket::performRead(void* buf, size_t buflen) {
1225 ssize_t bytes = recv(fd_, buf, buflen, MSG_DONTWAIT);
1227 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1228 // No more data to read right now.
1229 return READ_BLOCKING;
1234 appBytesReceived_ += bytes;
1239 void AsyncSocket::handleRead() noexcept {
1240 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1241 << ", state=" << state_;
1242 assert(state_ == StateEnum::ESTABLISHED);
1243 assert((shutdownFlags_ & SHUT_READ) == 0);
1244 assert(readCallback_ != nullptr);
1245 assert(eventFlags_ & EventHandler::READ);
1248 // - a read attempt would block
1249 // - readCallback_ is uninstalled
1250 // - the number of loop iterations exceeds the optional maximum
1251 // - this AsyncSocket is moved to another EventBase
1253 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1254 // which is why need to check for it here.
1256 // The last bullet point is slightly subtle. readDataAvailable() may also
1257 // detach this socket from this EventBase. However, before
1258 // readDataAvailable() returns another thread may pick it up, attach it to
1259 // a different EventBase, and install another readCallback_. We need to
1260 // exit immediately after readDataAvailable() returns if the eventBase_ has
1261 // changed. (The caller must perform some sort of locking to transfer the
1262 // AsyncSocket between threads properly. This will be sufficient to ensure
1263 // that this thread sees the updated eventBase_ variable after
1264 // readDataAvailable() returns.)
1265 uint16_t numReads = 0;
1266 EventBase* originalEventBase = eventBase_;
1267 while (readCallback_ && eventBase_ == originalEventBase) {
1268 // Get the buffer to read into.
1269 void* buf = nullptr;
1272 readCallback_->getReadBuffer(&buf, &buflen);
1273 } catch (const AsyncSocketException& ex) {
1274 return failRead(__func__, ex);
1275 } catch (const std::exception& ex) {
1276 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1277 string("ReadCallback::getReadBuffer() "
1278 "threw exception: ") +
1280 return failRead(__func__, tex);
1282 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1283 "ReadCallback::getReadBuffer() threw "
1284 "non-exception type");
1285 return failRead(__func__, ex);
1287 if (buf == nullptr || buflen == 0) {
1288 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1289 "ReadCallback::getReadBuffer() returned "
1291 return failRead(__func__, ex);
1295 ssize_t bytesRead = performRead(buf, buflen);
1296 if (bytesRead > 0) {
1297 readCallback_->readDataAvailable(bytesRead);
1298 // Fall through and continue around the loop if the read
1299 // completely filled the available buffer.
1300 // Note that readCallback_ may have been uninstalled or changed inside
1301 // readDataAvailable().
1302 if (size_t(bytesRead) < buflen) {
1305 } else if (bytesRead == READ_BLOCKING) {
1306 // No more data to read right now.
1308 } else if (bytesRead == READ_ERROR) {
1309 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1310 withAddr("recv() failed"), errno);
1311 return failRead(__func__, ex);
1313 assert(bytesRead == READ_EOF);
1315 shutdownFlags_ |= SHUT_READ;
1316 if (!updateEventRegistration(0, EventHandler::READ)) {
1317 // we've already been moved into STATE_ERROR
1318 assert(state_ == StateEnum::ERROR);
1319 assert(readCallback_ == nullptr);
1323 ReadCallback* callback = readCallback_;
1324 readCallback_ = nullptr;
1325 callback->readEOF();
1328 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1335 * This function attempts to write as much data as possible, until no more data
1338 * - If it sends all available data, it unregisters for write events, and stops
1339 * the writeTimeout_.
1341 * - If not all of the data can be sent immediately, it reschedules
1342 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1343 * registered for write events.
1345 void AsyncSocket::handleWrite() noexcept {
1346 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1347 << ", state=" << state_;
1348 if (state_ == StateEnum::CONNECTING) {
1354 assert(state_ == StateEnum::ESTABLISHED);
1355 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1356 assert(writeReqHead_ != nullptr);
1358 // Loop until we run out of write requests,
1359 // or until this socket is moved to another EventBase.
1360 // (See the comment in handleRead() explaining how this can happen.)
1361 EventBase* originalEventBase = eventBase_;
1362 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1363 uint32_t countWritten;
1364 uint32_t partialWritten;
1365 WriteFlags writeFlags = writeReqHead_->flags();
1366 if (writeReqHead_->getNext() != nullptr) {
1367 writeFlags = writeFlags | WriteFlags::CORK;
1369 int bytesWritten = performWrite(writeReqHead_->getOps(),
1370 writeReqHead_->getOpCount(),
1371 writeFlags, &countWritten, &partialWritten);
1372 if (bytesWritten < 0) {
1373 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1374 withAddr("writev() failed"), errno);
1375 return failWrite(__func__, ex);
1376 } else if (countWritten == writeReqHead_->getOpCount()) {
1377 // We finished this request
1378 WriteRequest* req = writeReqHead_;
1379 writeReqHead_ = req->getNext();
1381 if (writeReqHead_ == nullptr) {
1382 writeReqTail_ = nullptr;
1383 // This is the last write request.
1384 // Unregister for write events and cancel the send timer
1385 // before we invoke the callback. We have to update the state properly
1386 // before calling the callback, since it may want to detach us from
1388 if (eventFlags_ & EventHandler::WRITE) {
1389 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1390 assert(state_ == StateEnum::ERROR);
1393 // Stop the send timeout
1394 writeTimeout_.cancelTimeout();
1396 assert(!writeTimeout_.isScheduled());
1398 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
1399 // we finish sending the last write request.
1401 // We have to do this before invoking writeSuccess(), since
1402 // writeSuccess() may detach us from our EventBase.
1403 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
1404 assert(connectCallback_ == nullptr);
1405 shutdownFlags_ |= SHUT_WRITE;
1407 if (shutdownFlags_ & SHUT_READ) {
1408 // Reads have already been shutdown. Fully close the socket and
1409 // move to STATE_CLOSED.
1411 // Note: This code currently moves us to STATE_CLOSED even if
1412 // close() hasn't ever been called. This can occur if we have
1413 // received EOF from the peer and shutdownWrite() has been called
1414 // locally. Should we bother staying in STATE_ESTABLISHED in this
1415 // case, until close() is actually called? I can't think of a
1416 // reason why we would need to do so. No other operations besides
1417 // calling close() or destroying the socket can be performed at
1419 assert(readCallback_ == nullptr);
1420 state_ = StateEnum::CLOSED;
1422 ioHandler_.changeHandlerFD(-1);
1426 // Reads are still enabled, so we are only doing a half-shutdown
1427 ::shutdown(fd_, SHUT_WR);
1432 // Invoke the callback
1433 WriteCallback* callback = req->getCallback();
1436 callback->writeSuccess();
1438 // We'll continue around the loop, trying to write another request
1441 writeReqHead_->consume(countWritten, partialWritten, bytesWritten);
1442 // Stop after a partial write; it's highly likely that a subsequent write
1443 // attempt will just return EAGAIN.
1445 // Ensure that we are registered for write events.
1446 if ((eventFlags_ & EventHandler::WRITE) == 0) {
1447 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1448 assert(state_ == StateEnum::ERROR);
1453 // Reschedule the send timeout, since we have made some write progress.
1454 if (sendTimeout_ > 0) {
1455 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1456 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1457 withAddr("failed to reschedule write timeout"));
1458 return failWrite(__func__, ex);
1466 void AsyncSocket::checkForImmediateRead() noexcept {
1467 // We currently don't attempt to perform optimistic reads in AsyncSocket.
1468 // (However, note that some subclasses do override this method.)
1470 // Simply calling handleRead() here would be bad, as this would call
1471 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
1472 // buffer even though no data may be available. This would waste lots of
1473 // memory, since the buffer will sit around unused until the socket actually
1474 // becomes readable.
1476 // Checking if the socket is readable now also seems like it would probably
1477 // be a pessimism. In most cases it probably wouldn't be readable, and we
1478 // would just waste an extra system call. Even if it is readable, waiting to
1479 // find out from libevent on the next event loop doesn't seem that bad.
1482 void AsyncSocket::handleInitialReadWrite() noexcept {
1483 // Our callers should already be holding a DestructorGuard, but grab
1484 // one here just to make sure, in case one of our calling code paths ever
1486 DestructorGuard dg(this);
1488 // If we have a readCallback_, make sure we enable read events. We
1489 // may already be registered for reads if connectSuccess() set
1490 // the read calback.
1491 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
1492 assert(state_ == StateEnum::ESTABLISHED);
1493 assert((shutdownFlags_ & SHUT_READ) == 0);
1494 if (!updateEventRegistration(EventHandler::READ, 0)) {
1495 assert(state_ == StateEnum::ERROR);
1498 checkForImmediateRead();
1499 } else if (readCallback_ == nullptr) {
1500 // Unregister for read events.
1501 updateEventRegistration(0, EventHandler::READ);
1504 // If we have write requests pending, try to send them immediately.
1505 // Since we just finished accepting, there is a very good chance that we can
1506 // write without blocking.
1508 // However, we only process them if EventHandler::WRITE is not already set,
1509 // which means that we're already blocked on a write attempt. (This can
1510 // happen if connectSuccess() called write() before returning.)
1511 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
1512 // Call handleWrite() to perform write processing.
1514 } else if (writeReqHead_ == nullptr) {
1515 // Unregister for write event.
1516 updateEventRegistration(0, EventHandler::WRITE);
1520 void AsyncSocket::handleConnect() noexcept {
1521 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
1522 << ", state=" << state_;
1523 assert(state_ == StateEnum::CONNECTING);
1524 // SHUT_WRITE can never be set while we are still connecting;
1525 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
1527 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1529 // In case we had a connect timeout, cancel the timeout
1530 writeTimeout_.cancelTimeout();
1531 // We don't use a persistent registration when waiting on a connect event,
1532 // so we have been automatically unregistered now. Update eventFlags_ to
1534 assert(eventFlags_ == EventHandler::WRITE);
1535 eventFlags_ = EventHandler::NONE;
1537 // Call getsockopt() to check if the connect succeeded
1539 socklen_t len = sizeof(error);
1540 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
1542 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1543 withAddr("error calling getsockopt() after connect"),
1545 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1546 << fd_ << " host=" << addr_.describe()
1547 << ") exception:" << ex.what();
1548 return failConnect(__func__, ex);
1552 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1553 "connect failed", error);
1554 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1555 << fd_ << " host=" << addr_.describe()
1556 << ") exception: " << ex.what();
1557 return failConnect(__func__, ex);
1560 // Move into STATE_ESTABLISHED
1561 state_ = StateEnum::ESTABLISHED;
1563 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
1564 // perform, immediately shutdown the write half of the socket.
1565 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
1566 // SHUT_READ shouldn't be set. If close() is called on the socket while we
1567 // are still connecting we just abort the connect rather than waiting for
1569 assert((shutdownFlags_ & SHUT_READ) == 0);
1570 ::shutdown(fd_, SHUT_WR);
1571 shutdownFlags_ |= SHUT_WRITE;
1574 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
1575 << "successfully connected; state=" << state_;
1577 // Remember the EventBase we are attached to, before we start invoking any
1578 // callbacks (since the callbacks may call detachEventBase()).
1579 EventBase* originalEventBase = eventBase_;
1581 // Call the connect callback.
1582 if (connectCallback_) {
1583 ConnectCallback* callback = connectCallback_;
1584 connectCallback_ = nullptr;
1585 callback->connectSuccess();
1588 // Note that the connect callback may have changed our state.
1589 // (set or unset the read callback, called write(), closed the socket, etc.)
1590 // The following code needs to handle these situations correctly.
1592 // If the socket has been closed, readCallback_ and writeReqHead_ will
1593 // always be nullptr, so that will prevent us from trying to read or write.
1595 // The main thing to check for is if eventBase_ is still originalEventBase.
1596 // If not, we have been detached from this event base, so we shouldn't
1597 // perform any more operations.
1598 if (eventBase_ != originalEventBase) {
1602 handleInitialReadWrite();
1605 void AsyncSocket::timeoutExpired() noexcept {
1606 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
1607 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
1608 DestructorGuard dg(this);
1609 assert(eventBase_->isInEventBaseThread());
1611 if (state_ == StateEnum::CONNECTING) {
1612 // connect() timed out
1613 // Unregister for I/O events.
1614 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
1615 "connect timed out");
1616 failConnect(__func__, ex);
1618 // a normal write operation timed out
1619 assert(state_ == StateEnum::ESTABLISHED);
1620 AsyncSocketException ex(AsyncSocketException::TIMED_OUT, "write timed out");
1621 failWrite(__func__, ex);
1625 ssize_t AsyncSocket::performWrite(const iovec* vec,
1628 uint32_t* countWritten,
1629 uint32_t* partialWritten) {
1630 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
1631 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
1632 // (since it may terminate the program if the main program doesn't explicitly
1635 msg.msg_name = nullptr;
1636 msg.msg_namelen = 0;
1637 msg.msg_iov = const_cast<iovec *>(vec);
1638 #ifdef IOV_MAX // not defined on Android
1639 msg.msg_iovlen = std::min(count, (uint32_t)IOV_MAX);
1641 msg.msg_iovlen = std::min(count, (uint32_t)UIO_MAXIOV);
1643 msg.msg_control = nullptr;
1644 msg.msg_controllen = 0;
1647 int msg_flags = MSG_DONTWAIT;
1649 #ifdef MSG_NOSIGNAL // Linux-only
1650 msg_flags |= MSG_NOSIGNAL;
1651 if (isSet(flags, WriteFlags::CORK)) {
1652 // MSG_MORE tells the kernel we have more data to send, so wait for us to
1653 // give it the rest of the data rather than immediately sending a partial
1654 // frame, even when TCP_NODELAY is enabled.
1655 msg_flags |= MSG_MORE;
1658 if (isSet(flags, WriteFlags::EOR)) {
1659 // marks that this is the last byte of a record (response)
1660 msg_flags |= MSG_EOR;
1662 ssize_t totalWritten = ::sendmsg(fd_, &msg, msg_flags);
1663 if (totalWritten < 0) {
1664 if (errno == EAGAIN) {
1665 // TCP buffer is full; we can't write any more data right now.
1667 *partialWritten = 0;
1672 *partialWritten = 0;
1676 appBytesWritten_ += totalWritten;
1678 uint32_t bytesWritten;
1680 for (bytesWritten = totalWritten, n = 0; n < count; ++n) {
1681 const iovec* v = vec + n;
1682 if (v->iov_len > bytesWritten) {
1683 // Partial write finished in the middle of this iovec
1685 *partialWritten = bytesWritten;
1686 return totalWritten;
1689 bytesWritten -= v->iov_len;
1692 assert(bytesWritten == 0);
1694 *partialWritten = 0;
1695 return totalWritten;
1699 * Re-register the EventHandler after eventFlags_ has changed.
1701 * If an error occurs, fail() is called to move the socket into the error state
1702 * and call all currently installed callbacks. After an error, the
1703 * AsyncSocket is completely unregistered.
1705 * @return Returns true on succcess, or false on error.
1707 bool AsyncSocket::updateEventRegistration() {
1708 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
1709 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
1710 << ", events=" << std::hex << eventFlags_;
1711 assert(eventBase_->isInEventBaseThread());
1712 if (eventFlags_ == EventHandler::NONE) {
1713 ioHandler_.unregisterHandler();
1717 // Always register for persistent events, so we don't have to re-register
1718 // after being called back.
1719 if (!ioHandler_.registerHandler(eventFlags_ | EventHandler::PERSIST)) {
1720 eventFlags_ = EventHandler::NONE; // we're not registered after error
1721 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1722 withAddr("failed to update AsyncSocket event registration"));
1723 fail("updateEventRegistration", ex);
1730 bool AsyncSocket::updateEventRegistration(uint16_t enable,
1732 uint16_t oldFlags = eventFlags_;
1733 eventFlags_ |= enable;
1734 eventFlags_ &= ~disable;
1735 if (eventFlags_ == oldFlags) {
1738 return updateEventRegistration();
1742 void AsyncSocket::startFail() {
1743 // startFail() should only be called once
1744 assert(state_ != StateEnum::ERROR);
1745 assert(getDestructorGuardCount() > 0);
1746 state_ = StateEnum::ERROR;
1747 // Ensure that SHUT_READ and SHUT_WRITE are set,
1748 // so all future attempts to read or write will be rejected
1749 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1751 if (eventFlags_ != EventHandler::NONE) {
1752 eventFlags_ = EventHandler::NONE;
1753 ioHandler_.unregisterHandler();
1755 writeTimeout_.cancelTimeout();
1758 ioHandler_.changeHandlerFD(-1);
1763 void AsyncSocket::finishFail() {
1764 assert(state_ == StateEnum::ERROR);
1765 assert(getDestructorGuardCount() > 0);
1767 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1768 withAddr("socket closing after error"));
1769 if (connectCallback_) {
1770 ConnectCallback* callback = connectCallback_;
1771 connectCallback_ = nullptr;
1772 callback->connectErr(ex);
1777 if (readCallback_) {
1778 ReadCallback* callback = readCallback_;
1779 readCallback_ = nullptr;
1780 callback->readErr(ex);
1784 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
1785 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1786 << state_ << " host=" << addr_.describe()
1787 << "): failed in " << fn << "(): "
1793 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
1794 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1795 << state_ << " host=" << addr_.describe()
1796 << "): failed while connecting in " << fn << "(): "
1800 if (connectCallback_ != nullptr) {
1801 ConnectCallback* callback = connectCallback_;
1802 connectCallback_ = nullptr;
1803 callback->connectErr(ex);
1809 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
1810 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1811 << state_ << " host=" << addr_.describe()
1812 << "): failed while reading in " << fn << "(): "
1816 if (readCallback_ != nullptr) {
1817 ReadCallback* callback = readCallback_;
1818 readCallback_ = nullptr;
1819 callback->readErr(ex);
1825 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
1826 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1827 << state_ << " host=" << addr_.describe()
1828 << "): failed while writing in " << fn << "(): "
1832 // Only invoke the first write callback, since the error occurred while
1833 // writing this request. Let any other pending write callbacks be invoked in
1835 if (writeReqHead_ != nullptr) {
1836 WriteRequest* req = writeReqHead_;
1837 writeReqHead_ = req->getNext();
1838 WriteCallback* callback = req->getCallback();
1839 uint32_t bytesWritten = req->getBytesWritten();
1842 callback->writeErr(bytesWritten, ex);
1849 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
1850 size_t bytesWritten,
1851 const AsyncSocketException& ex) {
1852 // This version of failWrite() is used when the failure occurs before
1853 // we've added the callback to writeReqHead_.
1854 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1855 << state_ << " host=" << addr_.describe()
1856 <<"): failed while writing in " << fn << "(): "
1860 if (callback != nullptr) {
1861 callback->writeErr(bytesWritten, ex);
1867 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
1868 // Invoke writeError() on all write callbacks.
1869 // This is used when writes are forcibly shutdown with write requests
1870 // pending, or when an error occurs with writes pending.
1871 while (writeReqHead_ != nullptr) {
1872 WriteRequest* req = writeReqHead_;
1873 writeReqHead_ = req->getNext();
1874 WriteCallback* callback = req->getCallback();
1876 callback->writeErr(req->getBytesWritten(), ex);
1882 void AsyncSocket::invalidState(ConnectCallback* callback) {
1883 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
1884 << "): connect() called in invalid state " << state_;
1887 * The invalidState() methods don't use the normal failure mechanisms,
1888 * since we don't know what state we are in. We don't want to call
1889 * startFail()/finishFail() recursively if we are already in the middle of
1893 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
1894 "connect() called with socket in invalid state");
1895 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1897 callback->connectErr(ex);
1900 // We can't use failConnect() here since connectCallback_
1901 // may already be set to another callback. Invoke this ConnectCallback
1902 // here; any other connectCallback_ will be invoked in finishFail()
1905 callback->connectErr(ex);
1911 void AsyncSocket::invalidState(ReadCallback* callback) {
1912 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
1913 << "): setReadCallback(" << callback
1914 << ") called in invalid state " << state_;
1916 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1917 "setReadCallback() called with socket in "
1919 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1921 callback->readErr(ex);
1926 callback->readErr(ex);
1932 void AsyncSocket::invalidState(WriteCallback* callback) {
1933 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
1934 << "): write() called in invalid state " << state_;
1936 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1937 withAddr("write() called with socket in invalid state"));
1938 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1940 callback->writeErr(0, ex);
1945 callback->writeErr(0, ex);
1951 void AsyncSocket::doClose() {
1952 if (fd_ == -1) return;
1953 if (shutdownSocketSet_) {
1954 shutdownSocketSet_->close(fd_);
1961 std::ostream& operator << (std::ostream& os,
1962 const AsyncSocket::StateEnum& state) {
1963 os << static_cast<int>(state);
1967 std::string AsyncSocket::withAddr(const std::string& s) {
1968 // Don't use addr_ directly because it may not be initialized
1969 // e.g. if constructed from fd
1970 folly::SocketAddress peer, local;
1972 getPeerAddress(&peer);
1973 getLocalAddress(&local);
1974 } catch (const std::exception&) {
1979 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";