2 * Copyright 2015 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/io/async/AsyncSocket.h>
19 #include <folly/io/async/EventBase.h>
20 #include <folly/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;
41 const AsyncSocketException socketClosedLocallyEx(
42 AsyncSocketException::END_OF_FILE, "socket closed locally");
43 const AsyncSocketException socketShutdownForWritesEx(
44 AsyncSocketException::END_OF_FILE, "socket shutdown for writes");
46 // TODO: It might help performance to provide a version of WriteRequest that
47 // users could derive from, so we can avoid the extra allocation for each call
48 // to write()/writev(). We could templatize TFramedAsyncChannel just like the
49 // protocols are currently templatized for transports.
51 // We would need the version for external users where they provide the iovec
52 // storage space, and only our internal version would allocate it at the end of
56 * A WriteRequest object tracks information about a pending write() or writev()
59 * A new WriteRequest operation is allocated on the heap for all write
60 * operations that cannot be completed immediately.
62 class AsyncSocket::WriteRequest {
64 static WriteRequest* newRequest(WriteCallback* callback,
67 unique_ptr<IOBuf>&& ioBuf,
70 // Since we put a variable size iovec array at the end
71 // of each WriteRequest, we have to manually allocate the memory.
72 void* buf = malloc(sizeof(WriteRequest) +
73 (opCount * sizeof(struct iovec)));
75 throw std::bad_alloc();
78 return new(buf) WriteRequest(callback, ops, opCount, std::move(ioBuf),
83 this->~WriteRequest();
88 return isSet(flags_, WriteFlags::CORK);
91 WriteFlags flags() const {
95 WriteRequest* getNext() const {
99 WriteCallback* getCallback() const {
103 uint32_t getBytesWritten() const {
104 return bytesWritten_;
107 const struct iovec* getOps() const {
108 assert(opCount_ > opIndex_);
109 return writeOps_ + opIndex_;
112 uint32_t getOpCount() const {
113 assert(opCount_ > opIndex_);
114 return opCount_ - opIndex_;
117 void consume(uint32_t wholeOps, uint32_t partialBytes,
118 uint32_t totalBytesWritten) {
119 // Advance opIndex_ forward by wholeOps
120 opIndex_ += wholeOps;
121 assert(opIndex_ < opCount_);
123 // If we've finished writing any IOBufs, release them
125 for (uint32_t i = wholeOps; i != 0; --i) {
127 ioBuf_ = ioBuf_->pop();
131 // Move partialBytes forward into the current iovec buffer
132 struct iovec* currentOp = writeOps_ + opIndex_;
133 assert((partialBytes < currentOp->iov_len) || (currentOp->iov_len == 0));
134 currentOp->iov_base =
135 reinterpret_cast<uint8_t*>(currentOp->iov_base) + partialBytes;
136 currentOp->iov_len -= partialBytes;
138 // Increment the bytesWritten_ count by totalBytesWritten
139 bytesWritten_ += totalBytesWritten;
142 void append(WriteRequest* next) {
143 assert(next_ == nullptr);
148 WriteRequest(WriteCallback* callback,
149 const struct iovec* ops,
151 unique_ptr<IOBuf>&& ioBuf,
154 , callback_(callback)
159 , ioBuf_(std::move(ioBuf)) {
160 memcpy(writeOps_, ops, sizeof(*ops) * opCount_);
163 // Private destructor, to ensure callers use destroy()
166 WriteRequest* next_; ///< pointer to next WriteRequest
167 WriteCallback* callback_; ///< completion callback
168 uint32_t bytesWritten_; ///< bytes written
169 uint32_t opCount_; ///< number of entries in writeOps_
170 uint32_t opIndex_; ///< current index into writeOps_
171 WriteFlags flags_; ///< set for WriteFlags
172 unique_ptr<IOBuf> ioBuf_; ///< underlying IOBuf, or nullptr if N/A
173 struct iovec writeOps_[]; ///< write operation(s) list
176 AsyncSocket::AsyncSocket()
177 : eventBase_(nullptr)
178 , writeTimeout_(this, nullptr)
179 , ioHandler_(this, nullptr) {
180 VLOG(5) << "new AsyncSocket()";
184 AsyncSocket::AsyncSocket(EventBase* evb)
186 , writeTimeout_(this, evb)
187 , ioHandler_(this, evb) {
188 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
192 AsyncSocket::AsyncSocket(EventBase* evb,
193 const folly::SocketAddress& address,
194 uint32_t connectTimeout)
196 connect(nullptr, address, connectTimeout);
199 AsyncSocket::AsyncSocket(EventBase* evb,
200 const std::string& ip,
202 uint32_t connectTimeout)
204 connect(nullptr, ip, port, connectTimeout);
207 AsyncSocket::AsyncSocket(EventBase* evb, int fd)
209 , writeTimeout_(this, evb)
210 , ioHandler_(this, evb, fd) {
211 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ", fd="
216 state_ = StateEnum::ESTABLISHED;
219 // init() method, since constructor forwarding isn't supported in most
221 void AsyncSocket::init() {
222 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
224 state_ = StateEnum::UNINIT;
225 eventFlags_ = EventHandler::NONE;
228 maxReadsPerEvent_ = 16;
229 connectCallback_ = nullptr;
230 readCallback_ = nullptr;
231 writeReqHead_ = nullptr;
232 writeReqTail_ = nullptr;
233 shutdownSocketSet_ = nullptr;
234 appBytesWritten_ = 0;
235 appBytesReceived_ = 0;
238 AsyncSocket::~AsyncSocket() {
239 VLOG(7) << "actual destruction of AsyncSocket(this=" << this
240 << ", evb=" << eventBase_ << ", fd=" << fd_
241 << ", state=" << state_ << ")";
244 void AsyncSocket::destroy() {
245 VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
246 << ", fd=" << fd_ << ", state=" << state_;
247 // When destroy is called, close the socket immediately
250 // Then call DelayedDestruction::destroy() to take care of
251 // whether or not we need immediate or delayed destruction
252 DelayedDestruction::destroy();
255 int AsyncSocket::detachFd() {
256 VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
257 << ", evb=" << eventBase_ << ", state=" << state_
258 << ", events=" << std::hex << eventFlags_ << ")";
259 // Extract the fd, and set fd_ to -1 first, so closeNow() won't
260 // actually close the descriptor.
261 if (shutdownSocketSet_) {
262 shutdownSocketSet_->remove(fd_);
266 // Call closeNow() to invoke all pending callbacks with an error.
268 // Update the EventHandler to stop using this fd.
269 // This can only be done after closeNow() unregisters the handler.
270 ioHandler_.changeHandlerFD(-1);
274 const folly::SocketAddress& AsyncSocket::anyAddress() {
275 static const folly::SocketAddress anyAddress =
276 folly::SocketAddress("0.0.0.0", 0);
280 void AsyncSocket::setShutdownSocketSet(ShutdownSocketSet* newSS) {
281 if (shutdownSocketSet_ == newSS) {
284 if (shutdownSocketSet_ && fd_ != -1) {
285 shutdownSocketSet_->remove(fd_);
287 shutdownSocketSet_ = newSS;
288 if (shutdownSocketSet_ && fd_ != -1) {
289 shutdownSocketSet_->add(fd_);
293 void AsyncSocket::setCloseOnExec() {
294 int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
296 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
297 withAddr("failed to set close-on-exec flag"),
302 void AsyncSocket::connect(ConnectCallback* callback,
303 const folly::SocketAddress& address,
305 const OptionMap &options,
306 const folly::SocketAddress& bindAddr) noexcept {
307 DestructorGuard dg(this);
308 assert(eventBase_->isInEventBaseThread());
312 // Make sure we're in the uninitialized state
313 if (state_ != StateEnum::UNINIT) {
314 return invalidState(callback);
318 state_ = StateEnum::CONNECTING;
319 connectCallback_ = callback;
321 sockaddr_storage addrStorage;
322 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
326 // Technically the first parameter should actually be a protocol family
327 // constant (PF_xxx) rather than an address family (AF_xxx), but the
328 // distinction is mainly just historical. In pretty much all
329 // implementations the PF_foo and AF_foo constants are identical.
330 fd_ = socket(address.getFamily(), SOCK_STREAM, 0);
332 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
333 withAddr("failed to create socket"), errno);
335 if (shutdownSocketSet_) {
336 shutdownSocketSet_->add(fd_);
338 ioHandler_.changeHandlerFD(fd_);
342 // Put the socket in non-blocking mode
343 int flags = fcntl(fd_, F_GETFL, 0);
345 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
346 withAddr("failed to get socket flags"), errno);
348 int rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
350 throw AsyncSocketException(
351 AsyncSocketException::INTERNAL_ERROR,
352 withAddr("failed to put socket in non-blocking mode"),
356 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
357 // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
358 rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
360 throw AsyncSocketException(
361 AsyncSocketException::INTERNAL_ERROR,
362 "failed to enable F_SETNOSIGPIPE on socket",
367 // By default, turn on TCP_NODELAY
368 // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
369 // setNoDelay() will log an error message if it fails.
370 if (address.getFamily() != AF_UNIX) {
371 (void)setNoDelay(true);
374 VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
375 << ", fd=" << fd_ << ", host=" << address.describe().c_str();
378 if (bindAddr != anyAddress()) {
380 if (::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
382 throw AsyncSocketException(
383 AsyncSocketException::NOT_OPEN,
384 "failed to setsockopt prior to bind on " + bindAddr.describe(),
388 bindAddr.getAddress(&addrStorage);
390 if (::bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
392 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
393 "failed to bind to async socket: " +
399 // Apply the additional options if any.
400 for (const auto& opt: options) {
401 int rv = opt.first.apply(fd_, opt.second);
403 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
404 withAddr("failed to set socket option"),
409 // Perform the connect()
410 address.getAddress(&addrStorage);
412 rv = ::connect(fd_, saddr, address.getActualSize());
414 if (errno == EINPROGRESS) {
415 // Connection in progress.
417 // Start a timer in case the connection takes too long.
418 if (!writeTimeout_.scheduleTimeout(timeout)) {
419 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
420 withAddr("failed to schedule AsyncSocket connect timeout"));
424 // Register for write events, so we'll
425 // be notified when the connection finishes/fails.
426 // Note that we don't register for a persistent event here.
427 assert(eventFlags_ == EventHandler::NONE);
428 eventFlags_ = EventHandler::WRITE;
429 if (!ioHandler_.registerHandler(eventFlags_)) {
430 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
431 withAddr("failed to register AsyncSocket connect handler"));
435 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
436 "connect failed (immediately)", errno);
440 // If we're still here the connect() succeeded immediately.
441 // Fall through to call the callback outside of this try...catch block
442 } catch (const AsyncSocketException& ex) {
443 return failConnect(__func__, ex);
444 } catch (const std::exception& ex) {
445 // shouldn't happen, but handle it just in case
446 VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
447 << "): unexpected " << typeid(ex).name() << " exception: "
449 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
450 withAddr(string("unexpected exception: ") +
452 return failConnect(__func__, tex);
455 // The connection succeeded immediately
456 // The read callback may not have been set yet, and no writes may be pending
457 // yet, so we don't have to register for any events at the moment.
458 VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
459 assert(readCallback_ == nullptr);
460 assert(writeReqHead_ == nullptr);
461 state_ = StateEnum::ESTABLISHED;
463 connectCallback_ = nullptr;
464 callback->connectSuccess();
468 void AsyncSocket::connect(ConnectCallback* callback,
469 const string& ip, uint16_t port,
471 const OptionMap &options) noexcept {
472 DestructorGuard dg(this);
474 connectCallback_ = callback;
475 connect(callback, folly::SocketAddress(ip, port), timeout, options);
476 } catch (const std::exception& ex) {
477 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
479 return failConnect(__func__, tex);
483 void AsyncSocket::cancelConnect() {
484 connectCallback_ = nullptr;
485 if (state_ == StateEnum::CONNECTING) {
490 void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
491 sendTimeout_ = milliseconds;
492 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
494 // If we are currently pending on write requests, immediately update
495 // writeTimeout_ with the new value.
496 if ((eventFlags_ & EventHandler::WRITE) &&
497 (state_ != StateEnum::CONNECTING)) {
498 assert(state_ == StateEnum::ESTABLISHED);
499 assert((shutdownFlags_ & SHUT_WRITE) == 0);
500 if (sendTimeout_ > 0) {
501 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
502 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
503 withAddr("failed to reschedule send timeout in setSendTimeout"));
504 return failWrite(__func__, ex);
507 writeTimeout_.cancelTimeout();
512 void AsyncSocket::setReadCB(ReadCallback *callback) {
513 VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
514 << ", callback=" << callback << ", state=" << state_;
516 // Short circuit if callback is the same as the existing readCallback_.
518 // Note that this is needed for proper functioning during some cleanup cases.
519 // During cleanup we allow setReadCallback(nullptr) to be called even if the
520 // read callback is already unset and we have been detached from an event
521 // base. This check prevents us from asserting
522 // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
523 if (callback == readCallback_) {
527 if (shutdownFlags_ & SHUT_READ) {
528 // Reads have already been shut down on this socket.
530 // Allow setReadCallback(nullptr) to be called in this case, but don't
531 // allow a new callback to be set.
533 // For example, setReadCallback(nullptr) can happen after an error if we
534 // invoke some other error callback before invoking readError(). The other
535 // error callback that is invoked first may go ahead and clear the read
536 // callback before we get a chance to invoke readError().
537 if (callback != nullptr) {
538 return invalidState(callback);
540 assert((eventFlags_ & EventHandler::READ) == 0);
541 readCallback_ = nullptr;
545 DestructorGuard dg(this);
546 assert(eventBase_->isInEventBaseThread());
548 switch ((StateEnum)state_) {
549 case StateEnum::CONNECTING:
550 // For convenience, we allow the read callback to be set while we are
551 // still connecting. We just store the callback for now. Once the
552 // connection completes we'll register for read events.
553 readCallback_ = callback;
555 case StateEnum::ESTABLISHED:
557 readCallback_ = callback;
558 uint16_t oldFlags = eventFlags_;
560 eventFlags_ |= EventHandler::READ;
562 eventFlags_ &= ~EventHandler::READ;
565 // Update our registration if our flags have changed
566 if (eventFlags_ != oldFlags) {
567 // We intentionally ignore the return value here.
568 // updateEventRegistration() will move us into the error state if it
569 // fails, and we don't need to do anything else here afterwards.
570 (void)updateEventRegistration();
574 checkForImmediateRead();
578 case StateEnum::CLOSED:
579 case StateEnum::ERROR:
580 // We should never reach here. SHUT_READ should always be set
581 // if we are in STATE_CLOSED or STATE_ERROR.
583 return invalidState(callback);
584 case StateEnum::UNINIT:
585 // We do not allow setReadCallback() to be called before we start
587 return invalidState(callback);
590 // We don't put a default case in the switch statement, so that the compiler
591 // will warn us to update the switch statement if a new state is added.
592 return invalidState(callback);
595 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
596 return readCallback_;
599 void AsyncSocket::write(WriteCallback* callback,
600 const void* buf, size_t bytes, WriteFlags flags) {
602 op.iov_base = const_cast<void*>(buf);
604 writeImpl(callback, &op, 1, std::move(unique_ptr<IOBuf>()), flags);
607 void AsyncSocket::writev(WriteCallback* callback,
611 writeImpl(callback, vec, count, std::move(unique_ptr<IOBuf>()), flags);
614 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
616 size_t count = buf->countChainElements();
619 writeChainImpl(callback, vec, count, std::move(buf), flags);
621 iovec* vec = new iovec[count];
622 writeChainImpl(callback, vec, count, std::move(buf), flags);
627 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
628 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
629 size_t veclen = buf->fillIov(vec, count);
630 writeImpl(callback, vec, veclen, std::move(buf), flags);
633 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
634 size_t count, unique_ptr<IOBuf>&& buf,
636 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
637 << ", callback=" << callback << ", count=" << count
638 << ", state=" << state_;
639 DestructorGuard dg(this);
640 unique_ptr<IOBuf>ioBuf(std::move(buf));
641 assert(eventBase_->isInEventBaseThread());
643 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
644 // No new writes may be performed after the write side of the socket has
647 // We could just call callback->writeError() here to fail just this write.
648 // However, fail hard and use invalidState() to fail all outstanding
649 // callbacks and move the socket into the error state. There's most likely
650 // a bug in the caller's code, so we abort everything rather than trying to
651 // proceed as best we can.
652 return invalidState(callback);
655 uint32_t countWritten = 0;
656 uint32_t partialWritten = 0;
657 int bytesWritten = 0;
658 bool mustRegister = false;
659 if (state_ == StateEnum::ESTABLISHED && !connecting()) {
660 if (writeReqHead_ == nullptr) {
661 // If we are established and there are no other writes pending,
662 // we can attempt to perform the write immediately.
663 assert(writeReqTail_ == nullptr);
664 assert((eventFlags_ & EventHandler::WRITE) == 0);
666 bytesWritten = performWrite(vec, count, flags,
667 &countWritten, &partialWritten);
668 if (bytesWritten < 0) {
669 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
670 withAddr("writev failed"), errno);
671 return failWrite(__func__, callback, 0, ex);
672 } else if (countWritten == count) {
673 // We successfully wrote everything.
674 // Invoke the callback and return.
676 callback->writeSuccess();
679 } // else { continue writing the next writeReq }
682 } else if (!connecting()) {
683 // Invalid state for writing
684 return invalidState(callback);
687 // Create a new WriteRequest to add to the queue
690 req = WriteRequest::newRequest(callback, vec + countWritten,
691 count - countWritten, std::move(ioBuf),
693 } catch (const std::exception& ex) {
694 // we mainly expect to catch std::bad_alloc here
695 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
696 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
697 return failWrite(__func__, callback, bytesWritten, tex);
699 req->consume(0, partialWritten, bytesWritten);
700 if (writeReqTail_ == nullptr) {
701 assert(writeReqHead_ == nullptr);
702 writeReqHead_ = writeReqTail_ = req;
704 writeReqTail_->append(req);
708 // Register for write events if are established and not currently
709 // waiting on write events
711 assert(state_ == StateEnum::ESTABLISHED);
712 assert((eventFlags_ & EventHandler::WRITE) == 0);
713 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
714 assert(state_ == StateEnum::ERROR);
717 if (sendTimeout_ > 0) {
718 // Schedule a timeout to fire if the write takes too long.
719 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
720 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
721 withAddr("failed to schedule send timeout"));
722 return failWrite(__func__, ex);
728 void AsyncSocket::close() {
729 VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
730 << ", state=" << state_ << ", shutdownFlags="
731 << std::hex << (int) shutdownFlags_;
733 // close() is only different from closeNow() when there are pending writes
734 // that need to drain before we can close. In all other cases, just call
737 // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
738 // STATE_ERROR if close() is invoked while a previous closeNow() or failure
739 // is still running. (e.g., If there are multiple pending writes, and we
740 // call writeError() on the first one, it may call close(). In this case we
741 // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
742 // writes will still be in the queue.)
744 // We only need to drain pending writes if we are still in STATE_CONNECTING
745 // or STATE_ESTABLISHED
746 if ((writeReqHead_ == nullptr) ||
747 !(state_ == StateEnum::CONNECTING ||
748 state_ == StateEnum::ESTABLISHED)) {
753 // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
754 // destroyed until close() returns.
755 DestructorGuard dg(this);
756 assert(eventBase_->isInEventBaseThread());
758 // Since there are write requests pending, we have to set the
759 // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
760 // connect finishes and we finish writing these requests.
762 // Set SHUT_READ to indicate that reads are shut down, and set the
763 // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
764 // pending writes complete.
765 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
767 // If a read callback is set, invoke readEOF() immediately to inform it that
768 // the socket has been closed and no more data can be read.
770 // Disable reads if they are enabled
771 if (!updateEventRegistration(0, EventHandler::READ)) {
772 // We're now in the error state; callbacks have been cleaned up
773 assert(state_ == StateEnum::ERROR);
774 assert(readCallback_ == nullptr);
776 ReadCallback* callback = readCallback_;
777 readCallback_ = nullptr;
783 void AsyncSocket::closeNow() {
784 VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
785 << ", state=" << state_ << ", shutdownFlags="
786 << std::hex << (int) shutdownFlags_;
787 DestructorGuard dg(this);
788 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
791 case StateEnum::ESTABLISHED:
792 case StateEnum::CONNECTING:
794 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
795 state_ = StateEnum::CLOSED;
797 // If the write timeout was set, cancel it.
798 writeTimeout_.cancelTimeout();
800 // If we are registered for I/O events, unregister.
801 if (eventFlags_ != EventHandler::NONE) {
802 eventFlags_ = EventHandler::NONE;
803 if (!updateEventRegistration()) {
804 // We will have been moved into the error state.
805 assert(state_ == StateEnum::ERROR);
811 ioHandler_.changeHandlerFD(-1);
815 if (connectCallback_) {
816 ConnectCallback* callback = connectCallback_;
817 connectCallback_ = nullptr;
818 callback->connectErr(socketClosedLocallyEx);
821 failAllWrites(socketClosedLocallyEx);
824 ReadCallback* callback = readCallback_;
825 readCallback_ = nullptr;
830 case StateEnum::CLOSED:
831 // Do nothing. It's possible that we are being called recursively
832 // from inside a callback that we invoked inside another call to close()
833 // that is still running.
835 case StateEnum::ERROR:
836 // Do nothing. The error handling code has performed (or is performing)
839 case StateEnum::UNINIT:
840 assert(eventFlags_ == EventHandler::NONE);
841 assert(connectCallback_ == nullptr);
842 assert(readCallback_ == nullptr);
843 assert(writeReqHead_ == nullptr);
844 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
845 state_ = StateEnum::CLOSED;
849 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
850 << ") called in unknown state " << state_;
853 void AsyncSocket::closeWithReset() {
854 // Enable SO_LINGER, with the linger timeout set to 0.
855 // This will trigger a TCP reset when we close the socket.
857 struct linger optLinger = {1, 0};
858 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
859 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
860 << "on " << fd_ << ": errno=" << errno;
864 // Then let closeNow() take care of the rest
868 void AsyncSocket::shutdownWrite() {
869 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
870 << ", state=" << state_ << ", shutdownFlags="
871 << std::hex << (int) shutdownFlags_;
873 // If there are no pending writes, shutdownWrite() is identical to
874 // shutdownWriteNow().
875 if (writeReqHead_ == nullptr) {
880 assert(eventBase_->isInEventBaseThread());
882 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
883 // shutdown will be performed once all writes complete.
884 shutdownFlags_ |= SHUT_WRITE_PENDING;
887 void AsyncSocket::shutdownWriteNow() {
888 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
889 << ", fd=" << fd_ << ", state=" << state_
890 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
892 if (shutdownFlags_ & SHUT_WRITE) {
893 // Writes are already shutdown; nothing else to do.
897 // If SHUT_READ is already set, just call closeNow() to completely
898 // close the socket. This can happen if close() was called with writes
899 // pending, and then shutdownWriteNow() is called before all pending writes
901 if (shutdownFlags_ & SHUT_READ) {
906 DestructorGuard dg(this);
907 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
909 switch (static_cast<StateEnum>(state_)) {
910 case StateEnum::ESTABLISHED:
912 shutdownFlags_ |= SHUT_WRITE;
914 // If the write timeout was set, cancel it.
915 writeTimeout_.cancelTimeout();
917 // If we are registered for write events, unregister.
918 if (!updateEventRegistration(0, EventHandler::WRITE)) {
919 // We will have been moved into the error state.
920 assert(state_ == StateEnum::ERROR);
924 // Shutdown writes on the file descriptor
925 ::shutdown(fd_, SHUT_WR);
927 // Immediately fail all write requests
928 failAllWrites(socketShutdownForWritesEx);
931 case StateEnum::CONNECTING:
933 // Set the SHUT_WRITE_PENDING flag.
934 // When the connection completes, it will check this flag,
935 // shutdown the write half of the socket, and then set SHUT_WRITE.
936 shutdownFlags_ |= SHUT_WRITE_PENDING;
938 // Immediately fail all write requests
939 failAllWrites(socketShutdownForWritesEx);
942 case StateEnum::UNINIT:
943 // Callers normally shouldn't call shutdownWriteNow() before the socket
944 // even starts connecting. Nonetheless, go ahead and set
945 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
946 // immediately shut down the write side of the socket.
947 shutdownFlags_ |= SHUT_WRITE_PENDING;
949 case StateEnum::CLOSED:
950 case StateEnum::ERROR:
951 // We should never get here. SHUT_WRITE should always be set
952 // in STATE_CLOSED and STATE_ERROR.
953 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
954 << ", fd=" << fd_ << ") in unexpected state " << state_
955 << " with SHUT_WRITE not set ("
956 << std::hex << (int) shutdownFlags_ << ")";
961 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
962 << fd_ << ") called in unknown state " << state_;
965 bool AsyncSocket::readable() const {
969 struct pollfd fds[1];
971 fds[0].events = POLLIN;
973 int rc = poll(fds, 1, 0);
977 bool AsyncSocket::isPending() const {
978 return ioHandler_.isPending();
981 bool AsyncSocket::hangup() const {
983 // sanity check, no one should ask for hangup if we are not connected.
987 #ifdef POLLRDHUP // Linux-only
988 struct pollfd fds[1];
990 fds[0].events = POLLRDHUP|POLLHUP;
993 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
999 bool AsyncSocket::good() const {
1000 return ((state_ == StateEnum::CONNECTING ||
1001 state_ == StateEnum::ESTABLISHED) &&
1002 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1005 bool AsyncSocket::error() const {
1006 return (state_ == StateEnum::ERROR);
1009 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1010 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1011 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1012 << ", state=" << state_ << ", events="
1013 << std::hex << eventFlags_ << ")";
1014 assert(eventBase_ == nullptr);
1015 assert(eventBase->isInEventBaseThread());
1017 eventBase_ = eventBase;
1018 ioHandler_.attachEventBase(eventBase);
1019 writeTimeout_.attachEventBase(eventBase);
1022 void AsyncSocket::detachEventBase() {
1023 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1024 << ", old evb=" << eventBase_ << ", state=" << state_
1025 << ", events=" << std::hex << eventFlags_ << ")";
1026 assert(eventBase_ != nullptr);
1027 assert(eventBase_->isInEventBaseThread());
1029 eventBase_ = nullptr;
1030 ioHandler_.detachEventBase();
1031 writeTimeout_.detachEventBase();
1034 bool AsyncSocket::isDetachable() const {
1035 DCHECK(eventBase_ != nullptr);
1036 DCHECK(eventBase_->isInEventBaseThread());
1038 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1041 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1042 address->setFromLocalAddress(fd_);
1045 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1046 if (!addr_.isInitialized()) {
1047 addr_.setFromPeerAddress(fd_);
1052 int AsyncSocket::setNoDelay(bool noDelay) {
1054 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1055 << this << "(state=" << state_ << ")";
1060 int value = noDelay ? 1 : 0;
1061 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1062 int errnoCopy = errno;
1063 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1064 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1065 << strerror(errnoCopy);
1072 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1074 #ifndef TCP_CONGESTION
1075 #define TCP_CONGESTION 13
1079 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1080 << "socket " << this << "(state=" << state_ << ")";
1085 if (setsockopt(fd_, IPPROTO_TCP, TCP_CONGESTION, cname.c_str(),
1086 cname.length() + 1) != 0) {
1087 int errnoCopy = errno;
1088 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1089 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1090 << strerror(errnoCopy);
1097 int AsyncSocket::setQuickAck(bool quickack) {
1099 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1100 << this << "(state=" << state_ << ")";
1105 #ifdef TCP_QUICKACK // Linux-only
1106 int value = quickack ? 1 : 0;
1107 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1108 int errnoCopy = errno;
1109 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1110 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1111 << strerror(errnoCopy);
1121 int AsyncSocket::setSendBufSize(size_t bufsize) {
1123 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1124 << this << "(state=" << state_ << ")";
1128 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1129 int errnoCopy = errno;
1130 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1131 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1132 << strerror(errnoCopy);
1139 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1141 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1142 << this << "(state=" << state_ << ")";
1146 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1147 int errnoCopy = errno;
1148 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1149 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1150 << strerror(errnoCopy);
1157 int AsyncSocket::setTCPProfile(int profd) {
1159 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1160 << this << "(state=" << state_ << ")";
1164 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1165 int errnoCopy = errno;
1166 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1167 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1168 << strerror(errnoCopy);
1175 void AsyncSocket::ioReady(uint16_t events) noexcept {
1176 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd" << fd_
1177 << ", events=" << std::hex << events << ", state=" << state_;
1178 DestructorGuard dg(this);
1179 assert(events & EventHandler::READ_WRITE);
1180 assert(eventBase_->isInEventBaseThread());
1182 uint16_t relevantEvents = events & EventHandler::READ_WRITE;
1183 if (relevantEvents == EventHandler::READ) {
1185 } else if (relevantEvents == EventHandler::WRITE) {
1187 } else if (relevantEvents == EventHandler::READ_WRITE) {
1188 EventBase* originalEventBase = eventBase_;
1189 // If both read and write events are ready, process writes first.
1192 // Return now if handleWrite() detached us from our EventBase
1193 if (eventBase_ != originalEventBase) {
1197 // Only call handleRead() if a read callback is still installed.
1198 // (It's possible that the read callback was uninstalled during
1200 if (readCallback_) {
1204 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1205 << std::hex << events << "(this=" << this << ")";
1210 ssize_t AsyncSocket::performRead(void* buf, size_t buflen) {
1211 ssize_t bytes = recv(fd_, buf, buflen, MSG_DONTWAIT);
1213 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1214 // No more data to read right now.
1215 return READ_BLOCKING;
1220 appBytesReceived_ += bytes;
1225 void AsyncSocket::handleRead() noexcept {
1226 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1227 << ", state=" << state_;
1228 assert(state_ == StateEnum::ESTABLISHED);
1229 assert((shutdownFlags_ & SHUT_READ) == 0);
1230 assert(readCallback_ != nullptr);
1231 assert(eventFlags_ & EventHandler::READ);
1234 // - a read attempt would block
1235 // - readCallback_ is uninstalled
1236 // - the number of loop iterations exceeds the optional maximum
1237 // - this AsyncSocket is moved to another EventBase
1239 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1240 // which is why need to check for it here.
1242 // The last bullet point is slightly subtle. readDataAvailable() may also
1243 // detach this socket from this EventBase. However, before
1244 // readDataAvailable() returns another thread may pick it up, attach it to
1245 // a different EventBase, and install another readCallback_. We need to
1246 // exit immediately after readDataAvailable() returns if the eventBase_ has
1247 // changed. (The caller must perform some sort of locking to transfer the
1248 // AsyncSocket between threads properly. This will be sufficient to ensure
1249 // that this thread sees the updated eventBase_ variable after
1250 // readDataAvailable() returns.)
1251 uint16_t numReads = 0;
1252 EventBase* originalEventBase = eventBase_;
1253 while (readCallback_ && eventBase_ == originalEventBase) {
1254 // Get the buffer to read into.
1255 void* buf = nullptr;
1258 readCallback_->getReadBuffer(&buf, &buflen);
1259 } catch (const AsyncSocketException& ex) {
1260 return failRead(__func__, ex);
1261 } catch (const std::exception& ex) {
1262 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1263 string("ReadCallback::getReadBuffer() "
1264 "threw exception: ") +
1266 return failRead(__func__, tex);
1268 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1269 "ReadCallback::getReadBuffer() threw "
1270 "non-exception type");
1271 return failRead(__func__, ex);
1273 if (buf == nullptr || buflen == 0) {
1274 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1275 "ReadCallback::getReadBuffer() returned "
1277 return failRead(__func__, ex);
1281 ssize_t bytesRead = performRead(buf, buflen);
1282 if (bytesRead > 0) {
1283 readCallback_->readDataAvailable(bytesRead);
1284 // Fall through and continue around the loop if the read
1285 // completely filled the available buffer.
1286 // Note that readCallback_ may have been uninstalled or changed inside
1287 // readDataAvailable().
1288 if (size_t(bytesRead) < buflen) {
1291 } else if (bytesRead == READ_BLOCKING) {
1292 // No more data to read right now.
1294 } else if (bytesRead == READ_ERROR) {
1295 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1296 withAddr("recv() failed"), errno);
1297 return failRead(__func__, ex);
1299 assert(bytesRead == READ_EOF);
1301 shutdownFlags_ |= SHUT_READ;
1302 if (!updateEventRegistration(0, EventHandler::READ)) {
1303 // we've already been moved into STATE_ERROR
1304 assert(state_ == StateEnum::ERROR);
1305 assert(readCallback_ == nullptr);
1309 ReadCallback* callback = readCallback_;
1310 readCallback_ = nullptr;
1311 callback->readEOF();
1314 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1321 * This function attempts to write as much data as possible, until no more data
1324 * - If it sends all available data, it unregisters for write events, and stops
1325 * the writeTimeout_.
1327 * - If not all of the data can be sent immediately, it reschedules
1328 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1329 * registered for write events.
1331 void AsyncSocket::handleWrite() noexcept {
1332 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1333 << ", state=" << state_;
1334 if (state_ == StateEnum::CONNECTING) {
1340 assert(state_ == StateEnum::ESTABLISHED);
1341 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1342 assert(writeReqHead_ != nullptr);
1344 // Loop until we run out of write requests,
1345 // or until this socket is moved to another EventBase.
1346 // (See the comment in handleRead() explaining how this can happen.)
1347 EventBase* originalEventBase = eventBase_;
1348 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1349 uint32_t countWritten;
1350 uint32_t partialWritten;
1351 WriteFlags writeFlags = writeReqHead_->flags();
1352 if (writeReqHead_->getNext() != nullptr) {
1353 writeFlags = writeFlags | WriteFlags::CORK;
1355 int bytesWritten = performWrite(writeReqHead_->getOps(),
1356 writeReqHead_->getOpCount(),
1357 writeFlags, &countWritten, &partialWritten);
1358 if (bytesWritten < 0) {
1359 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1360 withAddr("writev() failed"), errno);
1361 return failWrite(__func__, ex);
1362 } else if (countWritten == writeReqHead_->getOpCount()) {
1363 // We finished this request
1364 WriteRequest* req = writeReqHead_;
1365 writeReqHead_ = req->getNext();
1367 if (writeReqHead_ == nullptr) {
1368 writeReqTail_ = nullptr;
1369 // This is the last write request.
1370 // Unregister for write events and cancel the send timer
1371 // before we invoke the callback. We have to update the state properly
1372 // before calling the callback, since it may want to detach us from
1374 if (eventFlags_ & EventHandler::WRITE) {
1375 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1376 assert(state_ == StateEnum::ERROR);
1379 // Stop the send timeout
1380 writeTimeout_.cancelTimeout();
1382 assert(!writeTimeout_.isScheduled());
1384 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
1385 // we finish sending the last write request.
1387 // We have to do this before invoking writeSuccess(), since
1388 // writeSuccess() may detach us from our EventBase.
1389 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
1390 assert(connectCallback_ == nullptr);
1391 shutdownFlags_ |= SHUT_WRITE;
1393 if (shutdownFlags_ & SHUT_READ) {
1394 // Reads have already been shutdown. Fully close the socket and
1395 // move to STATE_CLOSED.
1397 // Note: This code currently moves us to STATE_CLOSED even if
1398 // close() hasn't ever been called. This can occur if we have
1399 // received EOF from the peer and shutdownWrite() has been called
1400 // locally. Should we bother staying in STATE_ESTABLISHED in this
1401 // case, until close() is actually called? I can't think of a
1402 // reason why we would need to do so. No other operations besides
1403 // calling close() or destroying the socket can be performed at
1405 assert(readCallback_ == nullptr);
1406 state_ = StateEnum::CLOSED;
1408 ioHandler_.changeHandlerFD(-1);
1412 // Reads are still enabled, so we are only doing a half-shutdown
1413 ::shutdown(fd_, SHUT_WR);
1418 // Invoke the callback
1419 WriteCallback* callback = req->getCallback();
1422 callback->writeSuccess();
1424 // We'll continue around the loop, trying to write another request
1427 writeReqHead_->consume(countWritten, partialWritten, bytesWritten);
1428 // Stop after a partial write; it's highly likely that a subsequent write
1429 // attempt will just return EAGAIN.
1431 // Ensure that we are registered for write events.
1432 if ((eventFlags_ & EventHandler::WRITE) == 0) {
1433 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1434 assert(state_ == StateEnum::ERROR);
1439 // Reschedule the send timeout, since we have made some write progress.
1440 if (sendTimeout_ > 0) {
1441 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1442 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1443 withAddr("failed to reschedule write timeout"));
1444 return failWrite(__func__, ex);
1452 void AsyncSocket::checkForImmediateRead() noexcept {
1453 // We currently don't attempt to perform optimistic reads in AsyncSocket.
1454 // (However, note that some subclasses do override this method.)
1456 // Simply calling handleRead() here would be bad, as this would call
1457 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
1458 // buffer even though no data may be available. This would waste lots of
1459 // memory, since the buffer will sit around unused until the socket actually
1460 // becomes readable.
1462 // Checking if the socket is readable now also seems like it would probably
1463 // be a pessimism. In most cases it probably wouldn't be readable, and we
1464 // would just waste an extra system call. Even if it is readable, waiting to
1465 // find out from libevent on the next event loop doesn't seem that bad.
1468 void AsyncSocket::handleInitialReadWrite() noexcept {
1469 // Our callers should already be holding a DestructorGuard, but grab
1470 // one here just to make sure, in case one of our calling code paths ever
1472 DestructorGuard dg(this);
1474 // If we have a readCallback_, make sure we enable read events. We
1475 // may already be registered for reads if connectSuccess() set
1476 // the read calback.
1477 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
1478 assert(state_ == StateEnum::ESTABLISHED);
1479 assert((shutdownFlags_ & SHUT_READ) == 0);
1480 if (!updateEventRegistration(EventHandler::READ, 0)) {
1481 assert(state_ == StateEnum::ERROR);
1484 checkForImmediateRead();
1485 } else if (readCallback_ == nullptr) {
1486 // Unregister for read events.
1487 updateEventRegistration(0, EventHandler::READ);
1490 // If we have write requests pending, try to send them immediately.
1491 // Since we just finished accepting, there is a very good chance that we can
1492 // write without blocking.
1494 // However, we only process them if EventHandler::WRITE is not already set,
1495 // which means that we're already blocked on a write attempt. (This can
1496 // happen if connectSuccess() called write() before returning.)
1497 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
1498 // Call handleWrite() to perform write processing.
1500 } else if (writeReqHead_ == nullptr) {
1501 // Unregister for write event.
1502 updateEventRegistration(0, EventHandler::WRITE);
1506 void AsyncSocket::handleConnect() noexcept {
1507 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
1508 << ", state=" << state_;
1509 assert(state_ == StateEnum::CONNECTING);
1510 // SHUT_WRITE can never be set while we are still connecting;
1511 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
1513 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1515 // In case we had a connect timeout, cancel the timeout
1516 writeTimeout_.cancelTimeout();
1517 // We don't use a persistent registration when waiting on a connect event,
1518 // so we have been automatically unregistered now. Update eventFlags_ to
1520 assert(eventFlags_ == EventHandler::WRITE);
1521 eventFlags_ = EventHandler::NONE;
1523 // Call getsockopt() to check if the connect succeeded
1525 socklen_t len = sizeof(error);
1526 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
1528 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1529 withAddr("error calling getsockopt() after connect"),
1531 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1532 << fd_ << " host=" << addr_.describe()
1533 << ") exception:" << ex.what();
1534 return failConnect(__func__, ex);
1538 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1539 "connect failed", error);
1540 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1541 << fd_ << " host=" << addr_.describe()
1542 << ") exception: " << ex.what();
1543 return failConnect(__func__, ex);
1546 // Move into STATE_ESTABLISHED
1547 state_ = StateEnum::ESTABLISHED;
1549 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
1550 // perform, immediately shutdown the write half of the socket.
1551 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
1552 // SHUT_READ shouldn't be set. If close() is called on the socket while we
1553 // are still connecting we just abort the connect rather than waiting for
1555 assert((shutdownFlags_ & SHUT_READ) == 0);
1556 ::shutdown(fd_, SHUT_WR);
1557 shutdownFlags_ |= SHUT_WRITE;
1560 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
1561 << "successfully connected; state=" << state_;
1563 // Remember the EventBase we are attached to, before we start invoking any
1564 // callbacks (since the callbacks may call detachEventBase()).
1565 EventBase* originalEventBase = eventBase_;
1567 // Call the connect callback.
1568 if (connectCallback_) {
1569 ConnectCallback* callback = connectCallback_;
1570 connectCallback_ = nullptr;
1571 callback->connectSuccess();
1574 // Note that the connect callback may have changed our state.
1575 // (set or unset the read callback, called write(), closed the socket, etc.)
1576 // The following code needs to handle these situations correctly.
1578 // If the socket has been closed, readCallback_ and writeReqHead_ will
1579 // always be nullptr, so that will prevent us from trying to read or write.
1581 // The main thing to check for is if eventBase_ is still originalEventBase.
1582 // If not, we have been detached from this event base, so we shouldn't
1583 // perform any more operations.
1584 if (eventBase_ != originalEventBase) {
1588 handleInitialReadWrite();
1591 void AsyncSocket::timeoutExpired() noexcept {
1592 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
1593 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
1594 DestructorGuard dg(this);
1595 assert(eventBase_->isInEventBaseThread());
1597 if (state_ == StateEnum::CONNECTING) {
1598 // connect() timed out
1599 // Unregister for I/O events.
1600 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
1601 "connect timed out");
1602 failConnect(__func__, ex);
1604 // a normal write operation timed out
1605 assert(state_ == StateEnum::ESTABLISHED);
1606 AsyncSocketException ex(AsyncSocketException::TIMED_OUT, "write timed out");
1607 failWrite(__func__, ex);
1611 ssize_t AsyncSocket::performWrite(const iovec* vec,
1614 uint32_t* countWritten,
1615 uint32_t* partialWritten) {
1616 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
1617 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
1618 // (since it may terminate the program if the main program doesn't explicitly
1621 msg.msg_name = nullptr;
1622 msg.msg_namelen = 0;
1623 msg.msg_iov = const_cast<iovec *>(vec);
1624 #ifdef IOV_MAX // not defined on Android
1625 msg.msg_iovlen = std::min(count, (uint32_t)IOV_MAX);
1627 msg.msg_iovlen = std::min(count, (uint32_t)UIO_MAXIOV);
1629 msg.msg_control = nullptr;
1630 msg.msg_controllen = 0;
1633 int msg_flags = MSG_DONTWAIT;
1635 #ifdef MSG_NOSIGNAL // Linux-only
1636 msg_flags |= MSG_NOSIGNAL;
1637 if (isSet(flags, WriteFlags::CORK)) {
1638 // MSG_MORE tells the kernel we have more data to send, so wait for us to
1639 // give it the rest of the data rather than immediately sending a partial
1640 // frame, even when TCP_NODELAY is enabled.
1641 msg_flags |= MSG_MORE;
1644 if (isSet(flags, WriteFlags::EOR)) {
1645 // marks that this is the last byte of a record (response)
1646 msg_flags |= MSG_EOR;
1648 ssize_t totalWritten = ::sendmsg(fd_, &msg, msg_flags);
1649 if (totalWritten < 0) {
1650 if (errno == EAGAIN) {
1651 // TCP buffer is full; we can't write any more data right now.
1653 *partialWritten = 0;
1658 *partialWritten = 0;
1662 appBytesWritten_ += totalWritten;
1664 uint32_t bytesWritten;
1666 for (bytesWritten = totalWritten, n = 0; n < count; ++n) {
1667 const iovec* v = vec + n;
1668 if (v->iov_len > bytesWritten) {
1669 // Partial write finished in the middle of this iovec
1671 *partialWritten = bytesWritten;
1672 return totalWritten;
1675 bytesWritten -= v->iov_len;
1678 assert(bytesWritten == 0);
1680 *partialWritten = 0;
1681 return totalWritten;
1685 * Re-register the EventHandler after eventFlags_ has changed.
1687 * If an error occurs, fail() is called to move the socket into the error state
1688 * and call all currently installed callbacks. After an error, the
1689 * AsyncSocket is completely unregistered.
1691 * @return Returns true on succcess, or false on error.
1693 bool AsyncSocket::updateEventRegistration() {
1694 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
1695 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
1696 << ", events=" << std::hex << eventFlags_;
1697 assert(eventBase_->isInEventBaseThread());
1698 if (eventFlags_ == EventHandler::NONE) {
1699 ioHandler_.unregisterHandler();
1703 // Always register for persistent events, so we don't have to re-register
1704 // after being called back.
1705 if (!ioHandler_.registerHandler(eventFlags_ | EventHandler::PERSIST)) {
1706 eventFlags_ = EventHandler::NONE; // we're not registered after error
1707 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1708 withAddr("failed to update AsyncSocket event registration"));
1709 fail("updateEventRegistration", ex);
1716 bool AsyncSocket::updateEventRegistration(uint16_t enable,
1718 uint16_t oldFlags = eventFlags_;
1719 eventFlags_ |= enable;
1720 eventFlags_ &= ~disable;
1721 if (eventFlags_ == oldFlags) {
1724 return updateEventRegistration();
1728 void AsyncSocket::startFail() {
1729 // startFail() should only be called once
1730 assert(state_ != StateEnum::ERROR);
1731 assert(getDestructorGuardCount() > 0);
1732 state_ = StateEnum::ERROR;
1733 // Ensure that SHUT_READ and SHUT_WRITE are set,
1734 // so all future attempts to read or write will be rejected
1735 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1737 if (eventFlags_ != EventHandler::NONE) {
1738 eventFlags_ = EventHandler::NONE;
1739 ioHandler_.unregisterHandler();
1741 writeTimeout_.cancelTimeout();
1744 ioHandler_.changeHandlerFD(-1);
1749 void AsyncSocket::finishFail() {
1750 assert(state_ == StateEnum::ERROR);
1751 assert(getDestructorGuardCount() > 0);
1753 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1754 withAddr("socket closing after error"));
1755 if (connectCallback_) {
1756 ConnectCallback* callback = connectCallback_;
1757 connectCallback_ = nullptr;
1758 callback->connectErr(ex);
1763 if (readCallback_) {
1764 ReadCallback* callback = readCallback_;
1765 readCallback_ = nullptr;
1766 callback->readErr(ex);
1770 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
1771 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1772 << state_ << " host=" << addr_.describe()
1773 << "): failed in " << fn << "(): "
1779 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
1780 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1781 << state_ << " host=" << addr_.describe()
1782 << "): failed while connecting in " << fn << "(): "
1786 if (connectCallback_ != nullptr) {
1787 ConnectCallback* callback = connectCallback_;
1788 connectCallback_ = nullptr;
1789 callback->connectErr(ex);
1795 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
1796 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1797 << state_ << " host=" << addr_.describe()
1798 << "): failed while reading in " << fn << "(): "
1802 if (readCallback_ != nullptr) {
1803 ReadCallback* callback = readCallback_;
1804 readCallback_ = nullptr;
1805 callback->readErr(ex);
1811 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
1812 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1813 << state_ << " host=" << addr_.describe()
1814 << "): failed while writing in " << fn << "(): "
1818 // Only invoke the first write callback, since the error occurred while
1819 // writing this request. Let any other pending write callbacks be invoked in
1821 if (writeReqHead_ != nullptr) {
1822 WriteRequest* req = writeReqHead_;
1823 writeReqHead_ = req->getNext();
1824 WriteCallback* callback = req->getCallback();
1825 uint32_t bytesWritten = req->getBytesWritten();
1828 callback->writeErr(bytesWritten, ex);
1835 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
1836 size_t bytesWritten,
1837 const AsyncSocketException& ex) {
1838 // This version of failWrite() is used when the failure occurs before
1839 // we've added the callback to writeReqHead_.
1840 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1841 << state_ << " host=" << addr_.describe()
1842 <<"): failed while writing in " << fn << "(): "
1846 if (callback != nullptr) {
1847 callback->writeErr(bytesWritten, ex);
1853 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
1854 // Invoke writeError() on all write callbacks.
1855 // This is used when writes are forcibly shutdown with write requests
1856 // pending, or when an error occurs with writes pending.
1857 while (writeReqHead_ != nullptr) {
1858 WriteRequest* req = writeReqHead_;
1859 writeReqHead_ = req->getNext();
1860 WriteCallback* callback = req->getCallback();
1862 callback->writeErr(req->getBytesWritten(), ex);
1868 void AsyncSocket::invalidState(ConnectCallback* callback) {
1869 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
1870 << "): connect() called in invalid state " << state_;
1873 * The invalidState() methods don't use the normal failure mechanisms,
1874 * since we don't know what state we are in. We don't want to call
1875 * startFail()/finishFail() recursively if we are already in the middle of
1879 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
1880 "connect() called with socket in invalid state");
1881 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1883 callback->connectErr(ex);
1886 // We can't use failConnect() here since connectCallback_
1887 // may already be set to another callback. Invoke this ConnectCallback
1888 // here; any other connectCallback_ will be invoked in finishFail()
1891 callback->connectErr(ex);
1897 void AsyncSocket::invalidState(ReadCallback* callback) {
1898 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
1899 << "): setReadCallback(" << callback
1900 << ") called in invalid state " << state_;
1902 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1903 "setReadCallback() called with socket in "
1905 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1907 callback->readErr(ex);
1912 callback->readErr(ex);
1918 void AsyncSocket::invalidState(WriteCallback* callback) {
1919 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
1920 << "): write() called in invalid state " << state_;
1922 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1923 withAddr("write() called with socket in invalid state"));
1924 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1926 callback->writeErr(0, ex);
1931 callback->writeErr(0, ex);
1937 void AsyncSocket::doClose() {
1938 if (fd_ == -1) return;
1939 if (shutdownSocketSet_) {
1940 shutdownSocketSet_->close(fd_);
1947 std::ostream& operator << (std::ostream& os,
1948 const AsyncSocket::StateEnum& state) {
1949 os << static_cast<int>(state);
1953 std::string AsyncSocket::withAddr(const std::string& s) {
1954 // Don't use addr_ directly because it may not be initialized
1955 // e.g. if constructed from fd
1956 folly::SocketAddress peer, local;
1958 getPeerAddress(&peer);
1959 getLocalAddress(&local);
1960 } catch (const std::exception&) {
1965 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";