2 * Copyright 2015 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/io/async/AsyncSocket.h>
19 #include <folly/io/async/EventBase.h>
20 #include <folly/io/async/EventHandler.h>
21 #include <folly/SocketAddress.h>
22 #include <folly/io/IOBuf.h>
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <netinet/in.h>
33 #include <netinet/tcp.h>
36 using std::unique_ptr;
40 // static members initializers
41 const AsyncSocket::OptionMap AsyncSocket::emptyOptionMap;
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 BytesWriteRequest 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
57 /* The default WriteRequest implementation, used for write(), writev() and
60 * A new BytesWriteRequest operation is allocated on the heap for all write
61 * operations that cannot be completed immediately.
63 class AsyncSocket::BytesWriteRequest : public AsyncSocket::WriteRequest {
65 static BytesWriteRequest* newRequest(AsyncSocket* socket,
66 WriteCallback* callback,
69 uint32_t partialWritten,
70 uint32_t bytesWritten,
71 unique_ptr<IOBuf>&& ioBuf,
74 // Since we put a variable size iovec array at the end
75 // of each BytesWriteRequest, we have to manually allocate the memory.
76 void* buf = malloc(sizeof(BytesWriteRequest) +
77 (opCount * sizeof(struct iovec)));
79 throw std::bad_alloc();
82 return new(buf) BytesWriteRequest(socket, callback, ops, opCount,
83 partialWritten, bytesWritten,
84 std::move(ioBuf), flags);
87 void destroy() override {
88 this->~BytesWriteRequest();
92 bool performWrite() override {
93 WriteFlags writeFlags = flags_;
94 if (getNext() != nullptr) {
95 writeFlags = writeFlags | WriteFlags::CORK;
97 bytesWritten_ = socket_->performWrite(getOps(), getOpCount(), writeFlags,
98 &opsWritten_, &partialBytes_);
99 return bytesWritten_ >= 0;
102 bool isComplete() override {
103 return opsWritten_ == getOpCount();
106 void consume() override {
107 // Advance opIndex_ forward by opsWritten_
108 opIndex_ += opsWritten_;
109 assert(opIndex_ < opCount_);
111 // If we've finished writing any IOBufs, release them
113 for (uint32_t i = opsWritten_; i != 0; --i) {
115 ioBuf_ = ioBuf_->pop();
119 // Move partialBytes_ forward into the current iovec buffer
120 struct iovec* currentOp = writeOps_ + opIndex_;
121 assert((partialBytes_ < currentOp->iov_len) || (currentOp->iov_len == 0));
122 currentOp->iov_base =
123 reinterpret_cast<uint8_t*>(currentOp->iov_base) + partialBytes_;
124 currentOp->iov_len -= partialBytes_;
126 // Increment the totalBytesWritten_ count by bytesWritten_;
127 totalBytesWritten_ += bytesWritten_;
131 BytesWriteRequest(AsyncSocket* socket,
132 WriteCallback* callback,
133 const struct iovec* ops,
135 uint32_t partialBytes,
136 uint32_t bytesWritten,
137 unique_ptr<IOBuf>&& ioBuf,
139 : AsyncSocket::WriteRequest(socket, callback)
143 , ioBuf_(std::move(ioBuf))
145 , partialBytes_(partialBytes)
146 , bytesWritten_(bytesWritten) {
147 memcpy(writeOps_, ops, sizeof(*ops) * opCount_);
150 // private destructor, to ensure callers use destroy()
151 virtual ~BytesWriteRequest() = default;
153 const struct iovec* getOps() const {
154 assert(opCount_ > opIndex_);
155 return writeOps_ + opIndex_;
158 uint32_t getOpCount() const {
159 assert(opCount_ > opIndex_);
160 return opCount_ - opIndex_;
163 uint32_t opCount_; ///< number of entries in writeOps_
164 uint32_t opIndex_; ///< current index into writeOps_
165 WriteFlags flags_; ///< set for WriteFlags
166 unique_ptr<IOBuf> ioBuf_; ///< underlying IOBuf, or nullptr if N/A
168 // for consume(), how much we wrote on the last write
169 uint32_t opsWritten_; ///< complete ops written
170 uint32_t partialBytes_; ///< partial bytes of incomplete op written
171 ssize_t bytesWritten_; ///< bytes written altogether
173 struct iovec writeOps_[]; ///< write operation(s) list
176 AsyncSocket::AsyncSocket()
177 : eventBase_(nullptr)
178 , writeTimeout_(this, nullptr)
179 , ioHandler_(this, nullptr)
180 , immediateReadHandler_(this) {
181 VLOG(5) << "new AsyncSocket()";
185 AsyncSocket::AsyncSocket(EventBase* evb)
187 , writeTimeout_(this, evb)
188 , ioHandler_(this, evb)
189 , immediateReadHandler_(this) {
190 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
194 AsyncSocket::AsyncSocket(EventBase* evb,
195 const folly::SocketAddress& address,
196 uint32_t connectTimeout)
198 connect(nullptr, address, connectTimeout);
201 AsyncSocket::AsyncSocket(EventBase* evb,
202 const std::string& ip,
204 uint32_t connectTimeout)
206 connect(nullptr, ip, port, connectTimeout);
209 AsyncSocket::AsyncSocket(EventBase* evb, int fd)
211 , writeTimeout_(this, evb)
212 , ioHandler_(this, evb, fd)
213 , immediateReadHandler_(this) {
214 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ", fd="
219 state_ = StateEnum::ESTABLISHED;
222 // init() method, since constructor forwarding isn't supported in most
224 void AsyncSocket::init() {
225 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
227 state_ = StateEnum::UNINIT;
228 eventFlags_ = EventHandler::NONE;
231 maxReadsPerEvent_ = 16;
232 connectCallback_ = nullptr;
233 readCallback_ = nullptr;
234 writeReqHead_ = nullptr;
235 writeReqTail_ = nullptr;
236 shutdownSocketSet_ = nullptr;
237 appBytesWritten_ = 0;
238 appBytesReceived_ = 0;
241 AsyncSocket::~AsyncSocket() {
242 VLOG(7) << "actual destruction of AsyncSocket(this=" << this
243 << ", evb=" << eventBase_ << ", fd=" << fd_
244 << ", state=" << state_ << ")";
247 void AsyncSocket::destroy() {
248 VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
249 << ", fd=" << fd_ << ", state=" << state_;
250 // When destroy is called, close the socket immediately
253 // Then call DelayedDestruction::destroy() to take care of
254 // whether or not we need immediate or delayed destruction
255 DelayedDestruction::destroy();
258 int AsyncSocket::detachFd() {
259 VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
260 << ", evb=" << eventBase_ << ", state=" << state_
261 << ", events=" << std::hex << eventFlags_ << ")";
262 // Extract the fd, and set fd_ to -1 first, so closeNow() won't
263 // actually close the descriptor.
264 if (shutdownSocketSet_) {
265 shutdownSocketSet_->remove(fd_);
269 // Call closeNow() to invoke all pending callbacks with an error.
271 // Update the EventHandler to stop using this fd.
272 // This can only be done after closeNow() unregisters the handler.
273 ioHandler_.changeHandlerFD(-1);
277 const folly::SocketAddress& AsyncSocket::anyAddress() {
278 static const folly::SocketAddress anyAddress =
279 folly::SocketAddress("0.0.0.0", 0);
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::setCloseOnExec() {
297 int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
299 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
300 withAddr("failed to set close-on-exec flag"),
305 void AsyncSocket::connect(ConnectCallback* callback,
306 const folly::SocketAddress& address,
308 const OptionMap &options,
309 const folly::SocketAddress& bindAddr) noexcept {
310 DestructorGuard dg(this);
311 assert(eventBase_->isInEventBaseThread());
315 // Make sure we're in the uninitialized state
316 if (state_ != StateEnum::UNINIT) {
317 return invalidState(callback);
321 state_ = StateEnum::CONNECTING;
322 connectCallback_ = callback;
324 sockaddr_storage addrStorage;
325 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
329 // Technically the first parameter should actually be a protocol family
330 // constant (PF_xxx) rather than an address family (AF_xxx), but the
331 // distinction is mainly just historical. In pretty much all
332 // implementations the PF_foo and AF_foo constants are identical.
333 fd_ = socket(address.getFamily(), SOCK_STREAM, 0);
335 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
336 withAddr("failed to create socket"), errno);
338 if (shutdownSocketSet_) {
339 shutdownSocketSet_->add(fd_);
341 ioHandler_.changeHandlerFD(fd_);
345 // Put the socket in non-blocking mode
346 int flags = fcntl(fd_, F_GETFL, 0);
348 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
349 withAddr("failed to get socket flags"), errno);
351 int rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
353 throw AsyncSocketException(
354 AsyncSocketException::INTERNAL_ERROR,
355 withAddr("failed to put socket in non-blocking mode"),
359 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
360 // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
361 rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
363 throw AsyncSocketException(
364 AsyncSocketException::INTERNAL_ERROR,
365 "failed to enable F_SETNOSIGPIPE on socket",
370 // By default, turn on TCP_NODELAY
371 // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
372 // setNoDelay() will log an error message if it fails.
373 if (address.getFamily() != AF_UNIX) {
374 (void)setNoDelay(true);
377 VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
378 << ", fd=" << fd_ << ", host=" << address.describe().c_str();
381 if (bindAddr != anyAddress()) {
383 if (::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
385 throw AsyncSocketException(
386 AsyncSocketException::NOT_OPEN,
387 "failed to setsockopt prior to bind on " + bindAddr.describe(),
391 bindAddr.getAddress(&addrStorage);
393 if (::bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
395 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
396 "failed to bind to async socket: " +
402 // Apply the additional options if any.
403 for (const auto& opt: options) {
404 int rv = opt.first.apply(fd_, opt.second);
406 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
407 withAddr("failed to set socket option"),
412 // Perform the connect()
413 address.getAddress(&addrStorage);
415 rv = ::connect(fd_, saddr, address.getActualSize());
417 if (errno == EINPROGRESS) {
418 // Connection in progress.
420 // Start a timer in case the connection takes too long.
421 if (!writeTimeout_.scheduleTimeout(timeout)) {
422 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
423 withAddr("failed to schedule AsyncSocket connect timeout"));
427 // Register for write events, so we'll
428 // be notified when the connection finishes/fails.
429 // Note that we don't register for a persistent event here.
430 assert(eventFlags_ == EventHandler::NONE);
431 eventFlags_ = EventHandler::WRITE;
432 if (!ioHandler_.registerHandler(eventFlags_)) {
433 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
434 withAddr("failed to register AsyncSocket connect handler"));
438 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
439 "connect failed (immediately)", errno);
443 // If we're still here the connect() succeeded immediately.
444 // Fall through to call the callback outside of this try...catch block
445 } catch (const AsyncSocketException& ex) {
446 return failConnect(__func__, ex);
447 } catch (const std::exception& ex) {
448 // shouldn't happen, but handle it just in case
449 VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
450 << "): unexpected " << typeid(ex).name() << " exception: "
452 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
453 withAddr(string("unexpected exception: ") +
455 return failConnect(__func__, tex);
458 // The connection succeeded immediately
459 // The read callback may not have been set yet, and no writes may be pending
460 // yet, so we don't have to register for any events at the moment.
461 VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
462 assert(readCallback_ == nullptr);
463 assert(writeReqHead_ == nullptr);
464 state_ = StateEnum::ESTABLISHED;
466 connectCallback_ = nullptr;
467 callback->connectSuccess();
471 void AsyncSocket::connect(ConnectCallback* callback,
472 const string& ip, uint16_t port,
474 const OptionMap &options) noexcept {
475 DestructorGuard dg(this);
477 connectCallback_ = callback;
478 connect(callback, folly::SocketAddress(ip, port), timeout, options);
479 } catch (const std::exception& ex) {
480 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
482 return failConnect(__func__, tex);
486 void AsyncSocket::cancelConnect() {
487 connectCallback_ = nullptr;
488 if (state_ == StateEnum::CONNECTING) {
493 void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
494 sendTimeout_ = milliseconds;
495 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
497 // If we are currently pending on write requests, immediately update
498 // writeTimeout_ with the new value.
499 if ((eventFlags_ & EventHandler::WRITE) &&
500 (state_ != StateEnum::CONNECTING)) {
501 assert(state_ == StateEnum::ESTABLISHED);
502 assert((shutdownFlags_ & SHUT_WRITE) == 0);
503 if (sendTimeout_ > 0) {
504 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
505 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
506 withAddr("failed to reschedule send timeout in setSendTimeout"));
507 return failWrite(__func__, ex);
510 writeTimeout_.cancelTimeout();
515 void AsyncSocket::setReadCB(ReadCallback *callback) {
516 VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
517 << ", callback=" << callback << ", state=" << state_;
519 // Short circuit if callback is the same as the existing readCallback_.
521 // Note that this is needed for proper functioning during some cleanup cases.
522 // During cleanup we allow setReadCallback(nullptr) to be called even if the
523 // read callback is already unset and we have been detached from an event
524 // base. This check prevents us from asserting
525 // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
526 if (callback == readCallback_) {
530 if (shutdownFlags_ & SHUT_READ) {
531 // Reads have already been shut down on this socket.
533 // Allow setReadCallback(nullptr) to be called in this case, but don't
534 // allow a new callback to be set.
536 // For example, setReadCallback(nullptr) can happen after an error if we
537 // invoke some other error callback before invoking readError(). The other
538 // error callback that is invoked first may go ahead and clear the read
539 // callback before we get a chance to invoke readError().
540 if (callback != nullptr) {
541 return invalidState(callback);
543 assert((eventFlags_ & EventHandler::READ) == 0);
544 readCallback_ = nullptr;
548 DestructorGuard dg(this);
549 assert(eventBase_->isInEventBaseThread());
551 switch ((StateEnum)state_) {
552 case StateEnum::CONNECTING:
553 // For convenience, we allow the read callback to be set while we are
554 // still connecting. We just store the callback for now. Once the
555 // connection completes we'll register for read events.
556 readCallback_ = callback;
558 case StateEnum::ESTABLISHED:
560 readCallback_ = callback;
561 uint16_t oldFlags = eventFlags_;
563 eventFlags_ |= EventHandler::READ;
565 eventFlags_ &= ~EventHandler::READ;
568 // Update our registration if our flags have changed
569 if (eventFlags_ != oldFlags) {
570 // We intentionally ignore the return value here.
571 // updateEventRegistration() will move us into the error state if it
572 // fails, and we don't need to do anything else here afterwards.
573 (void)updateEventRegistration();
577 checkForImmediateRead();
581 case StateEnum::CLOSED:
582 case StateEnum::ERROR:
583 // We should never reach here. SHUT_READ should always be set
584 // if we are in STATE_CLOSED or STATE_ERROR.
586 return invalidState(callback);
587 case StateEnum::UNINIT:
588 // We do not allow setReadCallback() to be called before we start
590 return invalidState(callback);
593 // We don't put a default case in the switch statement, so that the compiler
594 // will warn us to update the switch statement if a new state is added.
595 return invalidState(callback);
598 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
599 return readCallback_;
602 void AsyncSocket::write(WriteCallback* callback,
603 const void* buf, size_t bytes, WriteFlags flags) {
605 op.iov_base = const_cast<void*>(buf);
607 writeImpl(callback, &op, 1, std::move(unique_ptr<IOBuf>()), flags);
610 void AsyncSocket::writev(WriteCallback* callback,
614 writeImpl(callback, vec, count, std::move(unique_ptr<IOBuf>()), flags);
617 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
619 size_t count = buf->countChainElements();
622 writeChainImpl(callback, vec, count, std::move(buf), flags);
624 iovec* vec = new iovec[count];
625 writeChainImpl(callback, vec, count, std::move(buf), flags);
630 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
631 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
632 size_t veclen = buf->fillIov(vec, count);
633 writeImpl(callback, vec, veclen, std::move(buf), flags);
636 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
637 size_t count, unique_ptr<IOBuf>&& buf,
639 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
640 << ", callback=" << callback << ", count=" << count
641 << ", state=" << state_;
642 DestructorGuard dg(this);
643 unique_ptr<IOBuf>ioBuf(std::move(buf));
644 assert(eventBase_->isInEventBaseThread());
646 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
647 // No new writes may be performed after the write side of the socket has
650 // We could just call callback->writeError() here to fail just this write.
651 // However, fail hard and use invalidState() to fail all outstanding
652 // callbacks and move the socket into the error state. There's most likely
653 // a bug in the caller's code, so we abort everything rather than trying to
654 // proceed as best we can.
655 return invalidState(callback);
658 uint32_t countWritten = 0;
659 uint32_t partialWritten = 0;
660 int bytesWritten = 0;
661 bool mustRegister = false;
662 if (state_ == StateEnum::ESTABLISHED && !connecting()) {
663 if (writeReqHead_ == nullptr) {
664 // If we are established and there are no other writes pending,
665 // we can attempt to perform the write immediately.
666 assert(writeReqTail_ == nullptr);
667 assert((eventFlags_ & EventHandler::WRITE) == 0);
669 bytesWritten = performWrite(vec, count, flags,
670 &countWritten, &partialWritten);
671 if (bytesWritten < 0) {
672 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
673 withAddr("writev failed"), errno);
674 return failWrite(__func__, callback, 0, ex);
675 } else if (countWritten == count) {
676 // We successfully wrote everything.
677 // Invoke the callback and return.
679 callback->writeSuccess();
682 } // else { continue writing the next writeReq }
685 } else if (!connecting()) {
686 // Invalid state for writing
687 return invalidState(callback);
690 // Create a new WriteRequest to add to the queue
693 req = BytesWriteRequest::newRequest(this, callback, vec + countWritten,
694 count - countWritten, partialWritten,
695 bytesWritten, std::move(ioBuf), flags);
696 } catch (const std::exception& ex) {
697 // we mainly expect to catch std::bad_alloc here
698 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
699 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
700 return failWrite(__func__, callback, bytesWritten, tex);
703 if (writeReqTail_ == nullptr) {
704 assert(writeReqHead_ == nullptr);
705 writeReqHead_ = writeReqTail_ = req;
707 writeReqTail_->append(req);
711 // Register for write events if are established and not currently
712 // waiting on write events
714 assert(state_ == StateEnum::ESTABLISHED);
715 assert((eventFlags_ & EventHandler::WRITE) == 0);
716 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
717 assert(state_ == StateEnum::ERROR);
720 if (sendTimeout_ > 0) {
721 // Schedule a timeout to fire if the write takes too long.
722 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
723 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
724 withAddr("failed to schedule send timeout"));
725 return failWrite(__func__, ex);
731 void AsyncSocket::writeRequest(WriteRequest* req) {
732 if (writeReqTail_ == nullptr) {
733 assert(writeReqHead_ == nullptr);
734 writeReqHead_ = writeReqTail_ = req;
737 writeReqTail_->append(req);
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);
824 if (immediateReadHandler_.isLoopCallbackScheduled()) {
825 immediateReadHandler_.cancelLoopCallback();
829 ioHandler_.changeHandlerFD(-1);
833 if (connectCallback_) {
834 ConnectCallback* callback = connectCallback_;
835 connectCallback_ = nullptr;
836 callback->connectErr(socketClosedLocallyEx);
839 failAllWrites(socketClosedLocallyEx);
842 ReadCallback* callback = readCallback_;
843 readCallback_ = nullptr;
848 case StateEnum::CLOSED:
849 // Do nothing. It's possible that we are being called recursively
850 // from inside a callback that we invoked inside another call to close()
851 // that is still running.
853 case StateEnum::ERROR:
854 // Do nothing. The error handling code has performed (or is performing)
857 case StateEnum::UNINIT:
858 assert(eventFlags_ == EventHandler::NONE);
859 assert(connectCallback_ == nullptr);
860 assert(readCallback_ == nullptr);
861 assert(writeReqHead_ == nullptr);
862 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
863 state_ = StateEnum::CLOSED;
867 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
868 << ") called in unknown state " << state_;
871 void AsyncSocket::closeWithReset() {
872 // Enable SO_LINGER, with the linger timeout set to 0.
873 // This will trigger a TCP reset when we close the socket.
875 struct linger optLinger = {1, 0};
876 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
877 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
878 << "on " << fd_ << ": errno=" << errno;
882 // Then let closeNow() take care of the rest
886 void AsyncSocket::shutdownWrite() {
887 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
888 << ", state=" << state_ << ", shutdownFlags="
889 << std::hex << (int) shutdownFlags_;
891 // If there are no pending writes, shutdownWrite() is identical to
892 // shutdownWriteNow().
893 if (writeReqHead_ == nullptr) {
898 assert(eventBase_->isInEventBaseThread());
900 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
901 // shutdown will be performed once all writes complete.
902 shutdownFlags_ |= SHUT_WRITE_PENDING;
905 void AsyncSocket::shutdownWriteNow() {
906 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
907 << ", fd=" << fd_ << ", state=" << state_
908 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
910 if (shutdownFlags_ & SHUT_WRITE) {
911 // Writes are already shutdown; nothing else to do.
915 // If SHUT_READ is already set, just call closeNow() to completely
916 // close the socket. This can happen if close() was called with writes
917 // pending, and then shutdownWriteNow() is called before all pending writes
919 if (shutdownFlags_ & SHUT_READ) {
924 DestructorGuard dg(this);
925 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
927 switch (static_cast<StateEnum>(state_)) {
928 case StateEnum::ESTABLISHED:
930 shutdownFlags_ |= SHUT_WRITE;
932 // If the write timeout was set, cancel it.
933 writeTimeout_.cancelTimeout();
935 // If we are registered for write events, unregister.
936 if (!updateEventRegistration(0, EventHandler::WRITE)) {
937 // We will have been moved into the error state.
938 assert(state_ == StateEnum::ERROR);
942 // Shutdown writes on the file descriptor
943 ::shutdown(fd_, SHUT_WR);
945 // Immediately fail all write requests
946 failAllWrites(socketShutdownForWritesEx);
949 case StateEnum::CONNECTING:
951 // Set the SHUT_WRITE_PENDING flag.
952 // When the connection completes, it will check this flag,
953 // shutdown the write half of the socket, and then set SHUT_WRITE.
954 shutdownFlags_ |= SHUT_WRITE_PENDING;
956 // Immediately fail all write requests
957 failAllWrites(socketShutdownForWritesEx);
960 case StateEnum::UNINIT:
961 // Callers normally shouldn't call shutdownWriteNow() before the socket
962 // even starts connecting. Nonetheless, go ahead and set
963 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
964 // immediately shut down the write side of the socket.
965 shutdownFlags_ |= SHUT_WRITE_PENDING;
967 case StateEnum::CLOSED:
968 case StateEnum::ERROR:
969 // We should never get here. SHUT_WRITE should always be set
970 // in STATE_CLOSED and STATE_ERROR.
971 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
972 << ", fd=" << fd_ << ") in unexpected state " << state_
973 << " with SHUT_WRITE not set ("
974 << std::hex << (int) shutdownFlags_ << ")";
979 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
980 << fd_ << ") called in unknown state " << state_;
983 bool AsyncSocket::readable() const {
987 struct pollfd fds[1];
989 fds[0].events = POLLIN;
991 int rc = poll(fds, 1, 0);
995 bool AsyncSocket::isPending() const {
996 return ioHandler_.isPending();
999 bool AsyncSocket::hangup() const {
1001 // sanity check, no one should ask for hangup if we are not connected.
1005 #ifdef POLLRDHUP // Linux-only
1006 struct pollfd fds[1];
1008 fds[0].events = POLLRDHUP|POLLHUP;
1011 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1017 bool AsyncSocket::good() const {
1018 return ((state_ == StateEnum::CONNECTING ||
1019 state_ == StateEnum::ESTABLISHED) &&
1020 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1023 bool AsyncSocket::error() const {
1024 return (state_ == StateEnum::ERROR);
1027 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1028 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1029 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1030 << ", state=" << state_ << ", events="
1031 << std::hex << eventFlags_ << ")";
1032 assert(eventBase_ == nullptr);
1033 assert(eventBase->isInEventBaseThread());
1035 eventBase_ = eventBase;
1036 ioHandler_.attachEventBase(eventBase);
1037 writeTimeout_.attachEventBase(eventBase);
1040 void AsyncSocket::detachEventBase() {
1041 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1042 << ", old evb=" << eventBase_ << ", state=" << state_
1043 << ", events=" << std::hex << eventFlags_ << ")";
1044 assert(eventBase_ != nullptr);
1045 assert(eventBase_->isInEventBaseThread());
1047 eventBase_ = nullptr;
1048 ioHandler_.detachEventBase();
1049 writeTimeout_.detachEventBase();
1052 bool AsyncSocket::isDetachable() const {
1053 DCHECK(eventBase_ != nullptr);
1054 DCHECK(eventBase_->isInEventBaseThread());
1056 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1059 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1060 address->setFromLocalAddress(fd_);
1063 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1064 if (!addr_.isInitialized()) {
1065 addr_.setFromPeerAddress(fd_);
1070 int AsyncSocket::setNoDelay(bool noDelay) {
1072 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1073 << this << "(state=" << state_ << ")";
1078 int value = noDelay ? 1 : 0;
1079 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1080 int errnoCopy = errno;
1081 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1082 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1083 << strerror(errnoCopy);
1090 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1092 #ifndef TCP_CONGESTION
1093 #define TCP_CONGESTION 13
1097 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1098 << "socket " << this << "(state=" << state_ << ")";
1103 if (setsockopt(fd_, IPPROTO_TCP, TCP_CONGESTION, cname.c_str(),
1104 cname.length() + 1) != 0) {
1105 int errnoCopy = errno;
1106 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1107 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1108 << strerror(errnoCopy);
1115 int AsyncSocket::setQuickAck(bool quickack) {
1117 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1118 << this << "(state=" << state_ << ")";
1123 #ifdef TCP_QUICKACK // Linux-only
1124 int value = quickack ? 1 : 0;
1125 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1126 int errnoCopy = errno;
1127 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1128 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1129 << strerror(errnoCopy);
1139 int AsyncSocket::setSendBufSize(size_t bufsize) {
1141 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1142 << this << "(state=" << state_ << ")";
1146 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1147 int errnoCopy = errno;
1148 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1149 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1150 << strerror(errnoCopy);
1157 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1159 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1160 << this << "(state=" << state_ << ")";
1164 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1165 int errnoCopy = errno;
1166 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1167 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1168 << strerror(errnoCopy);
1175 int AsyncSocket::setTCPProfile(int profd) {
1177 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1178 << this << "(state=" << state_ << ")";
1182 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1183 int errnoCopy = errno;
1184 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1185 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1186 << strerror(errnoCopy);
1193 void AsyncSocket::ioReady(uint16_t events) noexcept {
1194 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd" << fd_
1195 << ", events=" << std::hex << events << ", state=" << state_;
1196 DestructorGuard dg(this);
1197 assert(events & EventHandler::READ_WRITE);
1198 assert(eventBase_->isInEventBaseThread());
1200 uint16_t relevantEvents = events & EventHandler::READ_WRITE;
1201 if (relevantEvents == EventHandler::READ) {
1203 } else if (relevantEvents == EventHandler::WRITE) {
1205 } else if (relevantEvents == EventHandler::READ_WRITE) {
1206 EventBase* originalEventBase = eventBase_;
1207 // If both read and write events are ready, process writes first.
1210 // Return now if handleWrite() detached us from our EventBase
1211 if (eventBase_ != originalEventBase) {
1215 // Only call handleRead() if a read callback is still installed.
1216 // (It's possible that the read callback was uninstalled during
1218 if (readCallback_) {
1222 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1223 << std::hex << events << "(this=" << this << ")";
1228 ssize_t AsyncSocket::performRead(void* buf, size_t buflen) {
1229 ssize_t bytes = recv(fd_, buf, buflen, MSG_DONTWAIT);
1231 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1232 // No more data to read right now.
1233 return READ_BLOCKING;
1238 appBytesReceived_ += bytes;
1243 void AsyncSocket::handleRead() noexcept {
1244 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1245 << ", state=" << state_;
1246 assert(state_ == StateEnum::ESTABLISHED);
1247 assert((shutdownFlags_ & SHUT_READ) == 0);
1248 assert(readCallback_ != nullptr);
1249 assert(eventFlags_ & EventHandler::READ);
1252 // - a read attempt would block
1253 // - readCallback_ is uninstalled
1254 // - the number of loop iterations exceeds the optional maximum
1255 // - this AsyncSocket is moved to another EventBase
1257 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1258 // which is why need to check for it here.
1260 // The last bullet point is slightly subtle. readDataAvailable() may also
1261 // detach this socket from this EventBase. However, before
1262 // readDataAvailable() returns another thread may pick it up, attach it to
1263 // a different EventBase, and install another readCallback_. We need to
1264 // exit immediately after readDataAvailable() returns if the eventBase_ has
1265 // changed. (The caller must perform some sort of locking to transfer the
1266 // AsyncSocket between threads properly. This will be sufficient to ensure
1267 // that this thread sees the updated eventBase_ variable after
1268 // readDataAvailable() returns.)
1269 uint16_t numReads = 0;
1270 EventBase* originalEventBase = eventBase_;
1271 while (readCallback_ && eventBase_ == originalEventBase) {
1272 // Get the buffer to read into.
1273 void* buf = nullptr;
1276 readCallback_->getReadBuffer(&buf, &buflen);
1277 } catch (const AsyncSocketException& ex) {
1278 return failRead(__func__, ex);
1279 } catch (const std::exception& ex) {
1280 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1281 string("ReadCallback::getReadBuffer() "
1282 "threw exception: ") +
1284 return failRead(__func__, tex);
1286 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1287 "ReadCallback::getReadBuffer() threw "
1288 "non-exception type");
1289 return failRead(__func__, ex);
1291 if (buf == nullptr || buflen == 0) {
1292 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1293 "ReadCallback::getReadBuffer() returned "
1295 return failRead(__func__, ex);
1299 ssize_t bytesRead = performRead(buf, buflen);
1300 if (bytesRead > 0) {
1301 readCallback_->readDataAvailable(bytesRead);
1302 // Fall through and continue around the loop if the read
1303 // completely filled the available buffer.
1304 // Note that readCallback_ may have been uninstalled or changed inside
1305 // readDataAvailable().
1306 if (size_t(bytesRead) < buflen) {
1309 } else if (bytesRead == READ_BLOCKING) {
1310 // No more data to read right now.
1312 } else if (bytesRead == READ_ERROR) {
1313 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1314 withAddr("recv() failed"), errno);
1315 return failRead(__func__, ex);
1317 assert(bytesRead == READ_EOF);
1319 shutdownFlags_ |= SHUT_READ;
1320 if (!updateEventRegistration(0, EventHandler::READ)) {
1321 // we've already been moved into STATE_ERROR
1322 assert(state_ == StateEnum::ERROR);
1323 assert(readCallback_ == nullptr);
1327 ReadCallback* callback = readCallback_;
1328 readCallback_ = nullptr;
1329 callback->readEOF();
1332 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1333 // We might still have data in the socket.
1334 // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
1335 scheduleImmediateRead();
1342 * This function attempts to write as much data as possible, until no more data
1345 * - If it sends all available data, it unregisters for write events, and stops
1346 * the writeTimeout_.
1348 * - If not all of the data can be sent immediately, it reschedules
1349 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1350 * registered for write events.
1352 void AsyncSocket::handleWrite() noexcept {
1353 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1354 << ", state=" << state_;
1355 if (state_ == StateEnum::CONNECTING) {
1361 assert(state_ == StateEnum::ESTABLISHED);
1362 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1363 assert(writeReqHead_ != nullptr);
1365 // Loop until we run out of write requests,
1366 // or until this socket is moved to another EventBase.
1367 // (See the comment in handleRead() explaining how this can happen.)
1368 EventBase* originalEventBase = eventBase_;
1369 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1370 if (!writeReqHead_->performWrite()) {
1371 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1372 withAddr("writev() failed"), errno);
1373 return failWrite(__func__, ex);
1374 } else if (writeReqHead_->isComplete()) {
1375 // We finished this request
1376 WriteRequest* req = writeReqHead_;
1377 writeReqHead_ = req->getNext();
1379 if (writeReqHead_ == nullptr) {
1380 writeReqTail_ = nullptr;
1381 // This is the last write request.
1382 // Unregister for write events and cancel the send timer
1383 // before we invoke the callback. We have to update the state properly
1384 // before calling the callback, since it may want to detach us from
1386 if (eventFlags_ & EventHandler::WRITE) {
1387 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1388 assert(state_ == StateEnum::ERROR);
1391 // Stop the send timeout
1392 writeTimeout_.cancelTimeout();
1394 assert(!writeTimeout_.isScheduled());
1396 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
1397 // we finish sending the last write request.
1399 // We have to do this before invoking writeSuccess(), since
1400 // writeSuccess() may detach us from our EventBase.
1401 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
1402 assert(connectCallback_ == nullptr);
1403 shutdownFlags_ |= SHUT_WRITE;
1405 if (shutdownFlags_ & SHUT_READ) {
1406 // Reads have already been shutdown. Fully close the socket and
1407 // move to STATE_CLOSED.
1409 // Note: This code currently moves us to STATE_CLOSED even if
1410 // close() hasn't ever been called. This can occur if we have
1411 // received EOF from the peer and shutdownWrite() has been called
1412 // locally. Should we bother staying in STATE_ESTABLISHED in this
1413 // case, until close() is actually called? I can't think of a
1414 // reason why we would need to do so. No other operations besides
1415 // calling close() or destroying the socket can be performed at
1417 assert(readCallback_ == nullptr);
1418 state_ = StateEnum::CLOSED;
1420 ioHandler_.changeHandlerFD(-1);
1424 // Reads are still enabled, so we are only doing a half-shutdown
1425 ::shutdown(fd_, SHUT_WR);
1430 // Invoke the callback
1431 WriteCallback* callback = req->getCallback();
1434 callback->writeSuccess();
1436 // We'll continue around the loop, trying to write another request
1439 writeReqHead_->consume();
1440 // Stop after a partial write; it's highly likely that a subsequent write
1441 // attempt will just return EAGAIN.
1443 // Ensure that we are registered for write events.
1444 if ((eventFlags_ & EventHandler::WRITE) == 0) {
1445 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1446 assert(state_ == StateEnum::ERROR);
1451 // Reschedule the send timeout, since we have made some write progress.
1452 if (sendTimeout_ > 0) {
1453 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1454 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1455 withAddr("failed to reschedule write timeout"));
1456 return failWrite(__func__, ex);
1464 void AsyncSocket::checkForImmediateRead() noexcept {
1465 // We currently don't attempt to perform optimistic reads in AsyncSocket.
1466 // (However, note that some subclasses do override this method.)
1468 // Simply calling handleRead() here would be bad, as this would call
1469 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
1470 // buffer even though no data may be available. This would waste lots of
1471 // memory, since the buffer will sit around unused until the socket actually
1472 // becomes readable.
1474 // Checking if the socket is readable now also seems like it would probably
1475 // be a pessimism. In most cases it probably wouldn't be readable, and we
1476 // would just waste an extra system call. Even if it is readable, waiting to
1477 // find out from libevent on the next event loop doesn't seem that bad.
1480 void AsyncSocket::handleInitialReadWrite() noexcept {
1481 // Our callers should already be holding a DestructorGuard, but grab
1482 // one here just to make sure, in case one of our calling code paths ever
1484 DestructorGuard dg(this);
1486 // If we have a readCallback_, make sure we enable read events. We
1487 // may already be registered for reads if connectSuccess() set
1488 // the read calback.
1489 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
1490 assert(state_ == StateEnum::ESTABLISHED);
1491 assert((shutdownFlags_ & SHUT_READ) == 0);
1492 if (!updateEventRegistration(EventHandler::READ, 0)) {
1493 assert(state_ == StateEnum::ERROR);
1496 checkForImmediateRead();
1497 } else if (readCallback_ == nullptr) {
1498 // Unregister for read events.
1499 updateEventRegistration(0, EventHandler::READ);
1502 // If we have write requests pending, try to send them immediately.
1503 // Since we just finished accepting, there is a very good chance that we can
1504 // write without blocking.
1506 // However, we only process them if EventHandler::WRITE is not already set,
1507 // which means that we're already blocked on a write attempt. (This can
1508 // happen if connectSuccess() called write() before returning.)
1509 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
1510 // Call handleWrite() to perform write processing.
1512 } else if (writeReqHead_ == nullptr) {
1513 // Unregister for write event.
1514 updateEventRegistration(0, EventHandler::WRITE);
1518 void AsyncSocket::handleConnect() noexcept {
1519 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
1520 << ", state=" << state_;
1521 assert(state_ == StateEnum::CONNECTING);
1522 // SHUT_WRITE can never be set while we are still connecting;
1523 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
1525 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1527 // In case we had a connect timeout, cancel the timeout
1528 writeTimeout_.cancelTimeout();
1529 // We don't use a persistent registration when waiting on a connect event,
1530 // so we have been automatically unregistered now. Update eventFlags_ to
1532 assert(eventFlags_ == EventHandler::WRITE);
1533 eventFlags_ = EventHandler::NONE;
1535 // Call getsockopt() to check if the connect succeeded
1537 socklen_t len = sizeof(error);
1538 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
1540 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1541 withAddr("error calling getsockopt() after connect"),
1543 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1544 << fd_ << " host=" << addr_.describe()
1545 << ") exception:" << ex.what();
1546 return failConnect(__func__, ex);
1550 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1551 "connect failed", error);
1552 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1553 << fd_ << " host=" << addr_.describe()
1554 << ") exception: " << ex.what();
1555 return failConnect(__func__, ex);
1558 // Move into STATE_ESTABLISHED
1559 state_ = StateEnum::ESTABLISHED;
1561 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
1562 // perform, immediately shutdown the write half of the socket.
1563 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
1564 // SHUT_READ shouldn't be set. If close() is called on the socket while we
1565 // are still connecting we just abort the connect rather than waiting for
1567 assert((shutdownFlags_ & SHUT_READ) == 0);
1568 ::shutdown(fd_, SHUT_WR);
1569 shutdownFlags_ |= SHUT_WRITE;
1572 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
1573 << "successfully connected; state=" << state_;
1575 // Remember the EventBase we are attached to, before we start invoking any
1576 // callbacks (since the callbacks may call detachEventBase()).
1577 EventBase* originalEventBase = eventBase_;
1579 // Call the connect callback.
1580 if (connectCallback_) {
1581 ConnectCallback* callback = connectCallback_;
1582 connectCallback_ = nullptr;
1583 callback->connectSuccess();
1586 // Note that the connect callback may have changed our state.
1587 // (set or unset the read callback, called write(), closed the socket, etc.)
1588 // The following code needs to handle these situations correctly.
1590 // If the socket has been closed, readCallback_ and writeReqHead_ will
1591 // always be nullptr, so that will prevent us from trying to read or write.
1593 // The main thing to check for is if eventBase_ is still originalEventBase.
1594 // If not, we have been detached from this event base, so we shouldn't
1595 // perform any more operations.
1596 if (eventBase_ != originalEventBase) {
1600 handleInitialReadWrite();
1603 void AsyncSocket::timeoutExpired() noexcept {
1604 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
1605 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
1606 DestructorGuard dg(this);
1607 assert(eventBase_->isInEventBaseThread());
1609 if (state_ == StateEnum::CONNECTING) {
1610 // connect() timed out
1611 // Unregister for I/O events.
1612 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
1613 "connect timed out");
1614 failConnect(__func__, ex);
1616 // a normal write operation timed out
1617 assert(state_ == StateEnum::ESTABLISHED);
1618 AsyncSocketException ex(AsyncSocketException::TIMED_OUT, "write timed out");
1619 failWrite(__func__, ex);
1623 ssize_t AsyncSocket::performWrite(const iovec* vec,
1626 uint32_t* countWritten,
1627 uint32_t* partialWritten) {
1628 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
1629 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
1630 // (since it may terminate the program if the main program doesn't explicitly
1633 msg.msg_name = nullptr;
1634 msg.msg_namelen = 0;
1635 msg.msg_iov = const_cast<iovec *>(vec);
1636 #ifdef IOV_MAX // not defined on Android
1637 msg.msg_iovlen = std::min(count, (uint32_t)IOV_MAX);
1639 msg.msg_iovlen = std::min(count, (uint32_t)UIO_MAXIOV);
1641 msg.msg_control = nullptr;
1642 msg.msg_controllen = 0;
1645 int msg_flags = MSG_DONTWAIT;
1647 #ifdef MSG_NOSIGNAL // Linux-only
1648 msg_flags |= MSG_NOSIGNAL;
1649 if (isSet(flags, WriteFlags::CORK)) {
1650 // MSG_MORE tells the kernel we have more data to send, so wait for us to
1651 // give it the rest of the data rather than immediately sending a partial
1652 // frame, even when TCP_NODELAY is enabled.
1653 msg_flags |= MSG_MORE;
1656 if (isSet(flags, WriteFlags::EOR)) {
1657 // marks that this is the last byte of a record (response)
1658 msg_flags |= MSG_EOR;
1660 ssize_t totalWritten = ::sendmsg(fd_, &msg, msg_flags);
1661 if (totalWritten < 0) {
1662 if (errno == EAGAIN) {
1663 // TCP buffer is full; we can't write any more data right now.
1665 *partialWritten = 0;
1670 *partialWritten = 0;
1674 appBytesWritten_ += totalWritten;
1676 uint32_t bytesWritten;
1678 for (bytesWritten = totalWritten, n = 0; n < count; ++n) {
1679 const iovec* v = vec + n;
1680 if (v->iov_len > bytesWritten) {
1681 // Partial write finished in the middle of this iovec
1683 *partialWritten = bytesWritten;
1684 return totalWritten;
1687 bytesWritten -= v->iov_len;
1690 assert(bytesWritten == 0);
1692 *partialWritten = 0;
1693 return totalWritten;
1697 * Re-register the EventHandler after eventFlags_ has changed.
1699 * If an error occurs, fail() is called to move the socket into the error state
1700 * and call all currently installed callbacks. After an error, the
1701 * AsyncSocket is completely unregistered.
1703 * @return Returns true on succcess, or false on error.
1705 bool AsyncSocket::updateEventRegistration() {
1706 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
1707 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
1708 << ", events=" << std::hex << eventFlags_;
1709 assert(eventBase_->isInEventBaseThread());
1710 if (eventFlags_ == EventHandler::NONE) {
1711 ioHandler_.unregisterHandler();
1715 // Always register for persistent events, so we don't have to re-register
1716 // after being called back.
1717 if (!ioHandler_.registerHandler(eventFlags_ | EventHandler::PERSIST)) {
1718 eventFlags_ = EventHandler::NONE; // we're not registered after error
1719 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1720 withAddr("failed to update AsyncSocket event registration"));
1721 fail("updateEventRegistration", ex);
1728 bool AsyncSocket::updateEventRegistration(uint16_t enable,
1730 uint16_t oldFlags = eventFlags_;
1731 eventFlags_ |= enable;
1732 eventFlags_ &= ~disable;
1733 if (eventFlags_ == oldFlags) {
1736 return updateEventRegistration();
1740 void AsyncSocket::startFail() {
1741 // startFail() should only be called once
1742 assert(state_ != StateEnum::ERROR);
1743 assert(getDestructorGuardCount() > 0);
1744 state_ = StateEnum::ERROR;
1745 // Ensure that SHUT_READ and SHUT_WRITE are set,
1746 // so all future attempts to read or write will be rejected
1747 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1749 if (eventFlags_ != EventHandler::NONE) {
1750 eventFlags_ = EventHandler::NONE;
1751 ioHandler_.unregisterHandler();
1753 writeTimeout_.cancelTimeout();
1756 ioHandler_.changeHandlerFD(-1);
1761 void AsyncSocket::finishFail() {
1762 assert(state_ == StateEnum::ERROR);
1763 assert(getDestructorGuardCount() > 0);
1765 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1766 withAddr("socket closing after error"));
1767 if (connectCallback_) {
1768 ConnectCallback* callback = connectCallback_;
1769 connectCallback_ = nullptr;
1770 callback->connectErr(ex);
1775 if (readCallback_) {
1776 ReadCallback* callback = readCallback_;
1777 readCallback_ = nullptr;
1778 callback->readErr(ex);
1782 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
1783 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1784 << state_ << " host=" << addr_.describe()
1785 << "): failed in " << fn << "(): "
1791 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
1792 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1793 << state_ << " host=" << addr_.describe()
1794 << "): failed while connecting in " << fn << "(): "
1798 if (connectCallback_ != nullptr) {
1799 ConnectCallback* callback = connectCallback_;
1800 connectCallback_ = nullptr;
1801 callback->connectErr(ex);
1807 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
1808 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1809 << state_ << " host=" << addr_.describe()
1810 << "): failed while reading in " << fn << "(): "
1814 if (readCallback_ != nullptr) {
1815 ReadCallback* callback = readCallback_;
1816 readCallback_ = nullptr;
1817 callback->readErr(ex);
1823 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
1824 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1825 << state_ << " host=" << addr_.describe()
1826 << "): failed while writing in " << fn << "(): "
1830 // Only invoke the first write callback, since the error occurred while
1831 // writing this request. Let any other pending write callbacks be invoked in
1833 if (writeReqHead_ != nullptr) {
1834 WriteRequest* req = writeReqHead_;
1835 writeReqHead_ = req->getNext();
1836 WriteCallback* callback = req->getCallback();
1837 uint32_t bytesWritten = req->getTotalBytesWritten();
1840 callback->writeErr(bytesWritten, ex);
1847 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
1848 size_t bytesWritten,
1849 const AsyncSocketException& ex) {
1850 // This version of failWrite() is used when the failure occurs before
1851 // we've added the callback to writeReqHead_.
1852 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1853 << state_ << " host=" << addr_.describe()
1854 <<"): failed while writing in " << fn << "(): "
1858 if (callback != nullptr) {
1859 callback->writeErr(bytesWritten, ex);
1865 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
1866 // Invoke writeError() on all write callbacks.
1867 // This is used when writes are forcibly shutdown with write requests
1868 // pending, or when an error occurs with writes pending.
1869 while (writeReqHead_ != nullptr) {
1870 WriteRequest* req = writeReqHead_;
1871 writeReqHead_ = req->getNext();
1872 WriteCallback* callback = req->getCallback();
1874 callback->writeErr(req->getTotalBytesWritten(), ex);
1880 void AsyncSocket::invalidState(ConnectCallback* callback) {
1881 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
1882 << "): connect() called in invalid state " << state_;
1885 * The invalidState() methods don't use the normal failure mechanisms,
1886 * since we don't know what state we are in. We don't want to call
1887 * startFail()/finishFail() recursively if we are already in the middle of
1891 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
1892 "connect() called with socket in invalid state");
1893 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1895 callback->connectErr(ex);
1898 // We can't use failConnect() here since connectCallback_
1899 // may already be set to another callback. Invoke this ConnectCallback
1900 // here; any other connectCallback_ will be invoked in finishFail()
1903 callback->connectErr(ex);
1909 void AsyncSocket::invalidState(ReadCallback* callback) {
1910 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
1911 << "): setReadCallback(" << callback
1912 << ") called in invalid state " << state_;
1914 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1915 "setReadCallback() called with socket in "
1917 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1919 callback->readErr(ex);
1924 callback->readErr(ex);
1930 void AsyncSocket::invalidState(WriteCallback* callback) {
1931 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
1932 << "): write() called in invalid state " << state_;
1934 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1935 withAddr("write() called with socket in invalid state"));
1936 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1938 callback->writeErr(0, ex);
1943 callback->writeErr(0, ex);
1949 void AsyncSocket::doClose() {
1950 if (fd_ == -1) return;
1951 if (shutdownSocketSet_) {
1952 shutdownSocketSet_->close(fd_);
1959 std::ostream& operator << (std::ostream& os,
1960 const AsyncSocket::StateEnum& state) {
1961 os << static_cast<int>(state);
1965 std::string AsyncSocket::withAddr(const std::string& s) {
1966 // Don't use addr_ directly because it may not be initialized
1967 // e.g. if constructed from fd
1968 folly::SocketAddress peer, local;
1970 getPeerAddress(&peer);
1971 getLocalAddress(&local);
1972 } catch (const std::exception&) {
1977 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";