2 * Copyright 2016 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>
23 #include <folly/portability/SysUio.h>
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <netinet/tcp.h>
35 #include <boost/preprocessor/control/if.hpp>
38 using std::unique_ptr;
42 // static members initializers
43 const AsyncSocket::OptionMap AsyncSocket::emptyOptionMap;
45 const AsyncSocketException socketClosedLocallyEx(
46 AsyncSocketException::END_OF_FILE, "socket closed locally");
47 const AsyncSocketException socketShutdownForWritesEx(
48 AsyncSocketException::END_OF_FILE, "socket shutdown for writes");
50 // TODO: It might help performance to provide a version of BytesWriteRequest that
51 // users could derive from, so we can avoid the extra allocation for each call
52 // to write()/writev(). We could templatize TFramedAsyncChannel just like the
53 // protocols are currently templatized for transports.
55 // We would need the version for external users where they provide the iovec
56 // storage space, and only our internal version would allocate it at the end of
59 /* The default WriteRequest implementation, used for write(), writev() and
62 * A new BytesWriteRequest operation is allocated on the heap for all write
63 * operations that cannot be completed immediately.
65 class AsyncSocket::BytesWriteRequest : public AsyncSocket::WriteRequest {
67 static BytesWriteRequest* newRequest(AsyncSocket* socket,
68 WriteCallback* callback,
71 uint32_t partialWritten,
72 uint32_t bytesWritten,
73 unique_ptr<IOBuf>&& ioBuf,
76 // Since we put a variable size iovec array at the end
77 // of each BytesWriteRequest, we have to manually allocate the memory.
78 void* buf = malloc(sizeof(BytesWriteRequest) +
79 (opCount * sizeof(struct iovec)));
81 throw std::bad_alloc();
84 return new(buf) BytesWriteRequest(socket, callback, ops, opCount,
85 partialWritten, bytesWritten,
86 std::move(ioBuf), flags);
89 void destroy() override {
90 this->~BytesWriteRequest();
94 bool performWrite() override {
95 WriteFlags writeFlags = flags_;
96 if (getNext() != nullptr) {
97 writeFlags = writeFlags | WriteFlags::CORK;
99 bytesWritten_ = socket_->performWrite(getOps(), getOpCount(), writeFlags,
100 &opsWritten_, &partialBytes_);
101 return bytesWritten_ >= 0;
104 bool isComplete() override {
105 return opsWritten_ == getOpCount();
108 void consume() override {
109 // Advance opIndex_ forward by opsWritten_
110 opIndex_ += opsWritten_;
111 assert(opIndex_ < opCount_);
113 // If we've finished writing any IOBufs, release them
115 for (uint32_t i = opsWritten_; i != 0; --i) {
117 ioBuf_ = ioBuf_->pop();
121 // Move partialBytes_ forward into the current iovec buffer
122 struct iovec* currentOp = writeOps_ + opIndex_;
123 assert((partialBytes_ < currentOp->iov_len) || (currentOp->iov_len == 0));
124 currentOp->iov_base =
125 reinterpret_cast<uint8_t*>(currentOp->iov_base) + partialBytes_;
126 currentOp->iov_len -= partialBytes_;
128 // Increment the totalBytesWritten_ count by bytesWritten_;
129 totalBytesWritten_ += bytesWritten_;
133 BytesWriteRequest(AsyncSocket* socket,
134 WriteCallback* callback,
135 const struct iovec* ops,
137 uint32_t partialBytes,
138 uint32_t bytesWritten,
139 unique_ptr<IOBuf>&& ioBuf,
141 : AsyncSocket::WriteRequest(socket, callback)
145 , ioBuf_(std::move(ioBuf))
147 , partialBytes_(partialBytes)
148 , bytesWritten_(bytesWritten) {
149 memcpy(writeOps_, ops, sizeof(*ops) * opCount_);
152 // private destructor, to ensure callers use destroy()
153 ~BytesWriteRequest() override = default;
155 const struct iovec* getOps() const {
156 assert(opCount_ > opIndex_);
157 return writeOps_ + opIndex_;
160 uint32_t getOpCount() const {
161 assert(opCount_ > opIndex_);
162 return opCount_ - opIndex_;
165 uint32_t opCount_; ///< number of entries in writeOps_
166 uint32_t opIndex_; ///< current index into writeOps_
167 WriteFlags flags_; ///< set for WriteFlags
168 unique_ptr<IOBuf> ioBuf_; ///< underlying IOBuf, or nullptr if N/A
170 // for consume(), how much we wrote on the last write
171 uint32_t opsWritten_; ///< complete ops written
172 uint32_t partialBytes_; ///< partial bytes of incomplete op written
173 ssize_t bytesWritten_; ///< bytes written altogether
175 struct iovec writeOps_[]; ///< write operation(s) list
178 AsyncSocket::AsyncSocket()
179 : eventBase_(nullptr)
180 , writeTimeout_(this, nullptr)
181 , ioHandler_(this, nullptr)
182 , immediateReadHandler_(this) {
183 VLOG(5) << "new AsyncSocket()";
187 AsyncSocket::AsyncSocket(EventBase* evb)
189 , writeTimeout_(this, evb)
190 , ioHandler_(this, evb)
191 , immediateReadHandler_(this) {
192 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
196 AsyncSocket::AsyncSocket(EventBase* evb,
197 const folly::SocketAddress& address,
198 uint32_t connectTimeout)
200 connect(nullptr, address, connectTimeout);
203 AsyncSocket::AsyncSocket(EventBase* evb,
204 const std::string& ip,
206 uint32_t connectTimeout)
208 connect(nullptr, ip, port, connectTimeout);
211 AsyncSocket::AsyncSocket(EventBase* evb, int fd)
213 , writeTimeout_(this, evb)
214 , ioHandler_(this, evb, fd)
215 , immediateReadHandler_(this) {
216 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ", fd="
221 state_ = StateEnum::ESTABLISHED;
224 // init() method, since constructor forwarding isn't supported in most
226 void AsyncSocket::init() {
227 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
229 state_ = StateEnum::UNINIT;
230 eventFlags_ = EventHandler::NONE;
233 maxReadsPerEvent_ = 16;
234 connectCallback_ = nullptr;
235 readCallback_ = nullptr;
236 writeReqHead_ = nullptr;
237 writeReqTail_ = nullptr;
238 shutdownSocketSet_ = nullptr;
239 appBytesWritten_ = 0;
240 appBytesReceived_ = 0;
243 AsyncSocket::~AsyncSocket() {
244 VLOG(7) << "actual destruction of AsyncSocket(this=" << this
245 << ", evb=" << eventBase_ << ", fd=" << fd_
246 << ", state=" << state_ << ")";
249 void AsyncSocket::destroy() {
250 VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
251 << ", fd=" << fd_ << ", state=" << state_;
252 // When destroy is called, close the socket immediately
255 // Then call DelayedDestruction::destroy() to take care of
256 // whether or not we need immediate or delayed destruction
257 DelayedDestruction::destroy();
260 int AsyncSocket::detachFd() {
261 VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
262 << ", evb=" << eventBase_ << ", state=" << state_
263 << ", events=" << std::hex << eventFlags_ << ")";
264 // Extract the fd, and set fd_ to -1 first, so closeNow() won't
265 // actually close the descriptor.
266 if (shutdownSocketSet_) {
267 shutdownSocketSet_->remove(fd_);
271 // Call closeNow() to invoke all pending callbacks with an error.
273 // Update the EventHandler to stop using this fd.
274 // This can only be done after closeNow() unregisters the handler.
275 ioHandler_.changeHandlerFD(-1);
279 const folly::SocketAddress& AsyncSocket::anyAddress() {
280 static const folly::SocketAddress anyAddress =
281 folly::SocketAddress("0.0.0.0", 0);
285 void AsyncSocket::setShutdownSocketSet(ShutdownSocketSet* newSS) {
286 if (shutdownSocketSet_ == newSS) {
289 if (shutdownSocketSet_ && fd_ != -1) {
290 shutdownSocketSet_->remove(fd_);
292 shutdownSocketSet_ = newSS;
293 if (shutdownSocketSet_ && fd_ != -1) {
294 shutdownSocketSet_->add(fd_);
298 void AsyncSocket::setCloseOnExec() {
299 int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
301 auto errnoCopy = errno;
302 throw AsyncSocketException(
303 AsyncSocketException::INTERNAL_ERROR,
304 withAddr("failed to set close-on-exec flag"),
309 void AsyncSocket::connect(ConnectCallback* callback,
310 const folly::SocketAddress& address,
312 const OptionMap &options,
313 const folly::SocketAddress& bindAddr) noexcept {
314 DestructorGuard dg(this);
315 assert(eventBase_->isInEventBaseThread());
319 // Make sure we're in the uninitialized state
320 if (state_ != StateEnum::UNINIT) {
321 return invalidState(callback);
324 connectStartTime_ = std::chrono::steady_clock::now();
325 // Make connect end time at least >= connectStartTime.
326 connectEndTime_ = connectStartTime_;
329 state_ = StateEnum::CONNECTING;
330 connectCallback_ = callback;
332 sockaddr_storage addrStorage;
333 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
337 // Technically the first parameter should actually be a protocol family
338 // constant (PF_xxx) rather than an address family (AF_xxx), but the
339 // distinction is mainly just historical. In pretty much all
340 // implementations the PF_foo and AF_foo constants are identical.
341 fd_ = socket(address.getFamily(), SOCK_STREAM, 0);
343 auto errnoCopy = errno;
344 throw AsyncSocketException(
345 AsyncSocketException::INTERNAL_ERROR,
346 withAddr("failed to create socket"),
349 if (shutdownSocketSet_) {
350 shutdownSocketSet_->add(fd_);
352 ioHandler_.changeHandlerFD(fd_);
356 // Put the socket in non-blocking mode
357 int flags = fcntl(fd_, F_GETFL, 0);
359 auto errnoCopy = errno;
360 throw AsyncSocketException(
361 AsyncSocketException::INTERNAL_ERROR,
362 withAddr("failed to get socket flags"),
365 int rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
367 auto errnoCopy = errno;
368 throw AsyncSocketException(
369 AsyncSocketException::INTERNAL_ERROR,
370 withAddr("failed to put socket in non-blocking mode"),
374 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
375 // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
376 rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
378 auto errnoCopy = errno;
379 throw AsyncSocketException(
380 AsyncSocketException::INTERNAL_ERROR,
381 "failed to enable F_SETNOSIGPIPE on socket",
386 // By default, turn on TCP_NODELAY
387 // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
388 // setNoDelay() will log an error message if it fails.
389 if (address.getFamily() != AF_UNIX) {
390 (void)setNoDelay(true);
393 VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
394 << ", fd=" << fd_ << ", host=" << address.describe().c_str();
397 if (bindAddr != anyAddress()) {
399 if (::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
400 auto errnoCopy = errno;
402 throw AsyncSocketException(
403 AsyncSocketException::NOT_OPEN,
404 "failed to setsockopt prior to bind on " + bindAddr.describe(),
408 bindAddr.getAddress(&addrStorage);
410 if (::bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
411 auto errnoCopy = errno;
413 throw AsyncSocketException(
414 AsyncSocketException::NOT_OPEN,
415 "failed to bind to async socket: " + bindAddr.describe(),
420 // Apply the additional options if any.
421 for (const auto& opt: options) {
422 int rv = opt.first.apply(fd_, opt.second);
424 auto errnoCopy = errno;
425 throw AsyncSocketException(
426 AsyncSocketException::INTERNAL_ERROR,
427 withAddr("failed to set socket option"),
432 // Perform the connect()
433 address.getAddress(&addrStorage);
435 rv = ::connect(fd_, saddr, address.getActualSize());
437 auto errnoCopy = errno;
438 if (errnoCopy == EINPROGRESS) {
439 // Connection in progress.
441 // Start a timer in case the connection takes too long.
442 if (!writeTimeout_.scheduleTimeout(timeout)) {
443 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
444 withAddr("failed to schedule AsyncSocket connect timeout"));
448 // Register for write events, so we'll
449 // be notified when the connection finishes/fails.
450 // Note that we don't register for a persistent event here.
451 assert(eventFlags_ == EventHandler::NONE);
452 eventFlags_ = EventHandler::WRITE;
453 if (!ioHandler_.registerHandler(eventFlags_)) {
454 throw AsyncSocketException(AsyncSocketException::INTERNAL_ERROR,
455 withAddr("failed to register AsyncSocket connect handler"));
459 throw AsyncSocketException(
460 AsyncSocketException::NOT_OPEN,
461 "connect failed (immediately)",
466 // If we're still here the connect() succeeded immediately.
467 // Fall through to call the callback outside of this try...catch block
468 } catch (const AsyncSocketException& ex) {
469 return failConnect(__func__, ex);
470 } catch (const std::exception& ex) {
471 // shouldn't happen, but handle it just in case
472 VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
473 << "): unexpected " << typeid(ex).name() << " exception: "
475 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
476 withAddr(string("unexpected exception: ") +
478 return failConnect(__func__, tex);
481 // The connection succeeded immediately
482 // The read callback may not have been set yet, and no writes may be pending
483 // yet, so we don't have to register for any events at the moment.
484 VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
485 assert(readCallback_ == nullptr);
486 assert(writeReqHead_ == nullptr);
487 state_ = StateEnum::ESTABLISHED;
488 invokeConnectSuccess();
491 void AsyncSocket::connect(ConnectCallback* callback,
492 const string& ip, uint16_t port,
494 const OptionMap &options) noexcept {
495 DestructorGuard dg(this);
497 connectCallback_ = callback;
498 connect(callback, folly::SocketAddress(ip, port), timeout, options);
499 } catch (const std::exception& ex) {
500 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
502 return failConnect(__func__, tex);
506 void AsyncSocket::cancelConnect() {
507 connectCallback_ = nullptr;
508 if (state_ == StateEnum::CONNECTING) {
513 void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
514 sendTimeout_ = milliseconds;
515 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
517 // If we are currently pending on write requests, immediately update
518 // writeTimeout_ with the new value.
519 if ((eventFlags_ & EventHandler::WRITE) &&
520 (state_ != StateEnum::CONNECTING)) {
521 assert(state_ == StateEnum::ESTABLISHED);
522 assert((shutdownFlags_ & SHUT_WRITE) == 0);
523 if (sendTimeout_ > 0) {
524 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
525 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
526 withAddr("failed to reschedule send timeout in setSendTimeout"));
527 return failWrite(__func__, ex);
530 writeTimeout_.cancelTimeout();
535 void AsyncSocket::setReadCB(ReadCallback *callback) {
536 VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
537 << ", callback=" << callback << ", state=" << state_;
539 // Short circuit if callback is the same as the existing readCallback_.
541 // Note that this is needed for proper functioning during some cleanup cases.
542 // During cleanup we allow setReadCallback(nullptr) to be called even if the
543 // read callback is already unset and we have been detached from an event
544 // base. This check prevents us from asserting
545 // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
546 if (callback == readCallback_) {
550 /* We are removing a read callback */
551 if (callback == nullptr &&
552 immediateReadHandler_.isLoopCallbackScheduled()) {
553 immediateReadHandler_.cancelLoopCallback();
556 if (shutdownFlags_ & SHUT_READ) {
557 // Reads have already been shut down on this socket.
559 // Allow setReadCallback(nullptr) to be called in this case, but don't
560 // allow a new callback to be set.
562 // For example, setReadCallback(nullptr) can happen after an error if we
563 // invoke some other error callback before invoking readError(). The other
564 // error callback that is invoked first may go ahead and clear the read
565 // callback before we get a chance to invoke readError().
566 if (callback != nullptr) {
567 return invalidState(callback);
569 assert((eventFlags_ & EventHandler::READ) == 0);
570 readCallback_ = nullptr;
574 DestructorGuard dg(this);
575 assert(eventBase_->isInEventBaseThread());
577 switch ((StateEnum)state_) {
578 case StateEnum::CONNECTING:
579 // For convenience, we allow the read callback to be set while we are
580 // still connecting. We just store the callback for now. Once the
581 // connection completes we'll register for read events.
582 readCallback_ = callback;
584 case StateEnum::ESTABLISHED:
586 readCallback_ = callback;
587 uint16_t oldFlags = eventFlags_;
589 eventFlags_ |= EventHandler::READ;
591 eventFlags_ &= ~EventHandler::READ;
594 // Update our registration if our flags have changed
595 if (eventFlags_ != oldFlags) {
596 // We intentionally ignore the return value here.
597 // updateEventRegistration() will move us into the error state if it
598 // fails, and we don't need to do anything else here afterwards.
599 (void)updateEventRegistration();
603 checkForImmediateRead();
607 case StateEnum::CLOSED:
608 case StateEnum::ERROR:
609 // We should never reach here. SHUT_READ should always be set
610 // if we are in STATE_CLOSED or STATE_ERROR.
612 return invalidState(callback);
613 case StateEnum::UNINIT:
614 // We do not allow setReadCallback() to be called before we start
616 return invalidState(callback);
619 // We don't put a default case in the switch statement, so that the compiler
620 // will warn us to update the switch statement if a new state is added.
621 return invalidState(callback);
624 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
625 return readCallback_;
628 void AsyncSocket::write(WriteCallback* callback,
629 const void* buf, size_t bytes, WriteFlags flags) {
631 op.iov_base = const_cast<void*>(buf);
633 writeImpl(callback, &op, 1, unique_ptr<IOBuf>(), flags);
636 void AsyncSocket::writev(WriteCallback* callback,
640 writeImpl(callback, vec, count, unique_ptr<IOBuf>(), flags);
643 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
645 constexpr size_t kSmallSizeMax = 64;
646 size_t count = buf->countChainElements();
647 if (count <= kSmallSizeMax) {
648 iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA, count, kSmallSizeMax)];
649 writeChainImpl(callback, vec, count, std::move(buf), flags);
651 iovec* vec = new iovec[count];
652 writeChainImpl(callback, vec, count, std::move(buf), flags);
657 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
658 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
659 size_t veclen = buf->fillIov(vec, count);
660 writeImpl(callback, vec, veclen, std::move(buf), flags);
663 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
664 size_t count, unique_ptr<IOBuf>&& buf,
666 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
667 << ", callback=" << callback << ", count=" << count
668 << ", state=" << state_;
669 DestructorGuard dg(this);
670 unique_ptr<IOBuf>ioBuf(std::move(buf));
671 assert(eventBase_->isInEventBaseThread());
673 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
674 // No new writes may be performed after the write side of the socket has
677 // We could just call callback->writeError() here to fail just this write.
678 // However, fail hard and use invalidState() to fail all outstanding
679 // callbacks and move the socket into the error state. There's most likely
680 // a bug in the caller's code, so we abort everything rather than trying to
681 // proceed as best we can.
682 return invalidState(callback);
685 uint32_t countWritten = 0;
686 uint32_t partialWritten = 0;
687 int bytesWritten = 0;
688 bool mustRegister = false;
689 if (state_ == StateEnum::ESTABLISHED && !connecting()) {
690 if (writeReqHead_ == nullptr) {
691 // If we are established and there are no other writes pending,
692 // we can attempt to perform the write immediately.
693 assert(writeReqTail_ == nullptr);
694 assert((eventFlags_ & EventHandler::WRITE) == 0);
696 bytesWritten = performWrite(vec, count, flags,
697 &countWritten, &partialWritten);
698 if (bytesWritten < 0) {
699 auto errnoCopy = errno;
700 AsyncSocketException ex(
701 AsyncSocketException::INTERNAL_ERROR,
702 withAddr("writev failed"),
704 return failWrite(__func__, callback, 0, ex);
705 } else if (countWritten == count) {
706 // We successfully wrote everything.
707 // Invoke the callback and return.
709 callback->writeSuccess();
712 } else { // continue writing the next writeReq
713 if (bufferCallback_) {
714 bufferCallback_->onEgressBuffered();
719 } else if (!connecting()) {
720 // Invalid state for writing
721 return invalidState(callback);
724 // Create a new WriteRequest to add to the queue
727 req = BytesWriteRequest::newRequest(this, callback, vec + countWritten,
728 count - countWritten, partialWritten,
729 bytesWritten, std::move(ioBuf), flags);
730 } catch (const std::exception& ex) {
731 // we mainly expect to catch std::bad_alloc here
732 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
733 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
734 return failWrite(__func__, callback, bytesWritten, tex);
737 if (writeReqTail_ == nullptr) {
738 assert(writeReqHead_ == nullptr);
739 writeReqHead_ = writeReqTail_ = req;
741 writeReqTail_->append(req);
745 // Register for write events if are established and not currently
746 // waiting on write events
748 assert(state_ == StateEnum::ESTABLISHED);
749 assert((eventFlags_ & EventHandler::WRITE) == 0);
750 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
751 assert(state_ == StateEnum::ERROR);
754 if (sendTimeout_ > 0) {
755 // Schedule a timeout to fire if the write takes too long.
756 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
757 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
758 withAddr("failed to schedule send timeout"));
759 return failWrite(__func__, ex);
765 void AsyncSocket::writeRequest(WriteRequest* req) {
766 if (writeReqTail_ == nullptr) {
767 assert(writeReqHead_ == nullptr);
768 writeReqHead_ = writeReqTail_ = req;
771 writeReqTail_->append(req);
776 void AsyncSocket::close() {
777 VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
778 << ", state=" << state_ << ", shutdownFlags="
779 << std::hex << (int) shutdownFlags_;
781 // close() is only different from closeNow() when there are pending writes
782 // that need to drain before we can close. In all other cases, just call
785 // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
786 // STATE_ERROR if close() is invoked while a previous closeNow() or failure
787 // is still running. (e.g., If there are multiple pending writes, and we
788 // call writeError() on the first one, it may call close(). In this case we
789 // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
790 // writes will still be in the queue.)
792 // We only need to drain pending writes if we are still in STATE_CONNECTING
793 // or STATE_ESTABLISHED
794 if ((writeReqHead_ == nullptr) ||
795 !(state_ == StateEnum::CONNECTING ||
796 state_ == StateEnum::ESTABLISHED)) {
801 // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
802 // destroyed until close() returns.
803 DestructorGuard dg(this);
804 assert(eventBase_->isInEventBaseThread());
806 // Since there are write requests pending, we have to set the
807 // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
808 // connect finishes and we finish writing these requests.
810 // Set SHUT_READ to indicate that reads are shut down, and set the
811 // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
812 // pending writes complete.
813 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
815 // If a read callback is set, invoke readEOF() immediately to inform it that
816 // the socket has been closed and no more data can be read.
818 // Disable reads if they are enabled
819 if (!updateEventRegistration(0, EventHandler::READ)) {
820 // We're now in the error state; callbacks have been cleaned up
821 assert(state_ == StateEnum::ERROR);
822 assert(readCallback_ == nullptr);
824 ReadCallback* callback = readCallback_;
825 readCallback_ = nullptr;
831 void AsyncSocket::closeNow() {
832 VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
833 << ", state=" << state_ << ", shutdownFlags="
834 << std::hex << (int) shutdownFlags_;
835 DestructorGuard dg(this);
836 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
839 case StateEnum::ESTABLISHED:
840 case StateEnum::CONNECTING:
842 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
843 state_ = StateEnum::CLOSED;
845 // If the write timeout was set, cancel it.
846 writeTimeout_.cancelTimeout();
848 // If we are registered for I/O events, unregister.
849 if (eventFlags_ != EventHandler::NONE) {
850 eventFlags_ = EventHandler::NONE;
851 if (!updateEventRegistration()) {
852 // We will have been moved into the error state.
853 assert(state_ == StateEnum::ERROR);
858 if (immediateReadHandler_.isLoopCallbackScheduled()) {
859 immediateReadHandler_.cancelLoopCallback();
863 ioHandler_.changeHandlerFD(-1);
867 invokeConnectErr(socketClosedLocallyEx);
869 failAllWrites(socketClosedLocallyEx);
872 ReadCallback* callback = readCallback_;
873 readCallback_ = nullptr;
878 case StateEnum::CLOSED:
879 // Do nothing. It's possible that we are being called recursively
880 // from inside a callback that we invoked inside another call to close()
881 // that is still running.
883 case StateEnum::ERROR:
884 // Do nothing. The error handling code has performed (or is performing)
887 case StateEnum::UNINIT:
888 assert(eventFlags_ == EventHandler::NONE);
889 assert(connectCallback_ == nullptr);
890 assert(readCallback_ == nullptr);
891 assert(writeReqHead_ == nullptr);
892 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
893 state_ = StateEnum::CLOSED;
897 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
898 << ") called in unknown state " << state_;
901 void AsyncSocket::closeWithReset() {
902 // Enable SO_LINGER, with the linger timeout set to 0.
903 // This will trigger a TCP reset when we close the socket.
905 struct linger optLinger = {1, 0};
906 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
907 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
908 << "on " << fd_ << ": errno=" << errno;
912 // Then let closeNow() take care of the rest
916 void AsyncSocket::shutdownWrite() {
917 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
918 << ", state=" << state_ << ", shutdownFlags="
919 << std::hex << (int) shutdownFlags_;
921 // If there are no pending writes, shutdownWrite() is identical to
922 // shutdownWriteNow().
923 if (writeReqHead_ == nullptr) {
928 assert(eventBase_->isInEventBaseThread());
930 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
931 // shutdown will be performed once all writes complete.
932 shutdownFlags_ |= SHUT_WRITE_PENDING;
935 void AsyncSocket::shutdownWriteNow() {
936 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
937 << ", fd=" << fd_ << ", state=" << state_
938 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
940 if (shutdownFlags_ & SHUT_WRITE) {
941 // Writes are already shutdown; nothing else to do.
945 // If SHUT_READ is already set, just call closeNow() to completely
946 // close the socket. This can happen if close() was called with writes
947 // pending, and then shutdownWriteNow() is called before all pending writes
949 if (shutdownFlags_ & SHUT_READ) {
954 DestructorGuard dg(this);
955 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
957 switch (static_cast<StateEnum>(state_)) {
958 case StateEnum::ESTABLISHED:
960 shutdownFlags_ |= SHUT_WRITE;
962 // If the write timeout was set, cancel it.
963 writeTimeout_.cancelTimeout();
965 // If we are registered for write events, unregister.
966 if (!updateEventRegistration(0, EventHandler::WRITE)) {
967 // We will have been moved into the error state.
968 assert(state_ == StateEnum::ERROR);
972 // Shutdown writes on the file descriptor
973 ::shutdown(fd_, SHUT_WR);
975 // Immediately fail all write requests
976 failAllWrites(socketShutdownForWritesEx);
979 case StateEnum::CONNECTING:
981 // Set the SHUT_WRITE_PENDING flag.
982 // When the connection completes, it will check this flag,
983 // shutdown the write half of the socket, and then set SHUT_WRITE.
984 shutdownFlags_ |= SHUT_WRITE_PENDING;
986 // Immediately fail all write requests
987 failAllWrites(socketShutdownForWritesEx);
990 case StateEnum::UNINIT:
991 // Callers normally shouldn't call shutdownWriteNow() before the socket
992 // even starts connecting. Nonetheless, go ahead and set
993 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
994 // immediately shut down the write side of the socket.
995 shutdownFlags_ |= SHUT_WRITE_PENDING;
997 case StateEnum::CLOSED:
998 case StateEnum::ERROR:
999 // We should never get here. SHUT_WRITE should always be set
1000 // in STATE_CLOSED and STATE_ERROR.
1001 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
1002 << ", fd=" << fd_ << ") in unexpected state " << state_
1003 << " with SHUT_WRITE not set ("
1004 << std::hex << (int) shutdownFlags_ << ")";
1009 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
1010 << fd_ << ") called in unknown state " << state_;
1013 bool AsyncSocket::readable() const {
1017 struct pollfd fds[1];
1019 fds[0].events = POLLIN;
1021 int rc = poll(fds, 1, 0);
1025 bool AsyncSocket::isPending() const {
1026 return ioHandler_.isPending();
1029 bool AsyncSocket::hangup() const {
1031 // sanity check, no one should ask for hangup if we are not connected.
1035 #ifdef POLLRDHUP // Linux-only
1036 struct pollfd fds[1];
1038 fds[0].events = POLLRDHUP|POLLHUP;
1041 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1047 bool AsyncSocket::good() const {
1048 return ((state_ == StateEnum::CONNECTING ||
1049 state_ == StateEnum::ESTABLISHED) &&
1050 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1053 bool AsyncSocket::error() const {
1054 return (state_ == StateEnum::ERROR);
1057 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1058 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1059 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1060 << ", state=" << state_ << ", events="
1061 << std::hex << eventFlags_ << ")";
1062 assert(eventBase_ == nullptr);
1063 assert(eventBase->isInEventBaseThread());
1065 eventBase_ = eventBase;
1066 ioHandler_.attachEventBase(eventBase);
1067 writeTimeout_.attachEventBase(eventBase);
1070 void AsyncSocket::detachEventBase() {
1071 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1072 << ", old evb=" << eventBase_ << ", state=" << state_
1073 << ", events=" << std::hex << eventFlags_ << ")";
1074 assert(eventBase_ != nullptr);
1075 assert(eventBase_->isInEventBaseThread());
1077 eventBase_ = nullptr;
1078 ioHandler_.detachEventBase();
1079 writeTimeout_.detachEventBase();
1082 bool AsyncSocket::isDetachable() const {
1083 DCHECK(eventBase_ != nullptr);
1084 DCHECK(eventBase_->isInEventBaseThread());
1086 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1089 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1090 if (!localAddr_.isInitialized()) {
1091 localAddr_.setFromLocalAddress(fd_);
1093 *address = localAddr_;
1096 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1097 if (!addr_.isInitialized()) {
1098 addr_.setFromPeerAddress(fd_);
1103 int AsyncSocket::setNoDelay(bool noDelay) {
1105 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1106 << this << "(state=" << state_ << ")";
1111 int value = noDelay ? 1 : 0;
1112 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1113 int errnoCopy = errno;
1114 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1115 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1116 << strerror(errnoCopy);
1123 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1125 #ifndef TCP_CONGESTION
1126 #define TCP_CONGESTION 13
1130 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1131 << "socket " << this << "(state=" << state_ << ")";
1136 if (setsockopt(fd_, IPPROTO_TCP, TCP_CONGESTION, cname.c_str(),
1137 cname.length() + 1) != 0) {
1138 int errnoCopy = errno;
1139 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1140 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1141 << strerror(errnoCopy);
1148 int AsyncSocket::setQuickAck(bool quickack) {
1150 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1151 << this << "(state=" << state_ << ")";
1156 #ifdef TCP_QUICKACK // Linux-only
1157 int value = quickack ? 1 : 0;
1158 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1159 int errnoCopy = errno;
1160 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1161 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1162 << strerror(errnoCopy);
1172 int AsyncSocket::setSendBufSize(size_t bufsize) {
1174 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1175 << this << "(state=" << state_ << ")";
1179 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1180 int errnoCopy = errno;
1181 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1182 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1183 << strerror(errnoCopy);
1190 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1192 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1193 << this << "(state=" << state_ << ")";
1197 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1198 int errnoCopy = errno;
1199 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1200 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1201 << strerror(errnoCopy);
1208 int AsyncSocket::setTCPProfile(int profd) {
1210 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1211 << this << "(state=" << state_ << ")";
1215 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1216 int errnoCopy = errno;
1217 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1218 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1219 << strerror(errnoCopy);
1226 void AsyncSocket::ioReady(uint16_t events) noexcept {
1227 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd" << fd_
1228 << ", events=" << std::hex << events << ", state=" << state_;
1229 DestructorGuard dg(this);
1230 assert(events & EventHandler::READ_WRITE);
1231 assert(eventBase_->isInEventBaseThread());
1233 uint16_t relevantEvents = events & EventHandler::READ_WRITE;
1234 if (relevantEvents == EventHandler::READ) {
1236 } else if (relevantEvents == EventHandler::WRITE) {
1238 } else if (relevantEvents == EventHandler::READ_WRITE) {
1239 EventBase* originalEventBase = eventBase_;
1240 // If both read and write events are ready, process writes first.
1243 // Return now if handleWrite() detached us from our EventBase
1244 if (eventBase_ != originalEventBase) {
1248 // Only call handleRead() if a read callback is still installed.
1249 // (It's possible that the read callback was uninstalled during
1251 if (readCallback_) {
1255 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1256 << std::hex << events << "(this=" << this << ")";
1261 ssize_t AsyncSocket::performRead(void** buf,
1263 size_t* /* offset */) {
1264 VLOG(5) << "AsyncSocket::performRead() this=" << this
1265 << ", buf=" << *buf << ", buflen=" << *buflen;
1269 recvFlags |= MSG_PEEK;
1272 ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT | recvFlags);
1274 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1275 // No more data to read right now.
1276 return READ_BLOCKING;
1281 appBytesReceived_ += bytes;
1286 void AsyncSocket::prepareReadBuffer(void** buf, size_t* buflen) noexcept {
1287 // no matter what, buffer should be preapared for non-ssl socket
1288 CHECK(readCallback_);
1289 readCallback_->getReadBuffer(buf, buflen);
1292 void AsyncSocket::handleRead() noexcept {
1293 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1294 << ", state=" << state_;
1295 assert(state_ == StateEnum::ESTABLISHED);
1296 assert((shutdownFlags_ & SHUT_READ) == 0);
1297 assert(readCallback_ != nullptr);
1298 assert(eventFlags_ & EventHandler::READ);
1301 // - a read attempt would block
1302 // - readCallback_ is uninstalled
1303 // - the number of loop iterations exceeds the optional maximum
1304 // - this AsyncSocket is moved to another EventBase
1306 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1307 // which is why need to check for it here.
1309 // The last bullet point is slightly subtle. readDataAvailable() may also
1310 // detach this socket from this EventBase. However, before
1311 // readDataAvailable() returns another thread may pick it up, attach it to
1312 // a different EventBase, and install another readCallback_. We need to
1313 // exit immediately after readDataAvailable() returns if the eventBase_ has
1314 // changed. (The caller must perform some sort of locking to transfer the
1315 // AsyncSocket between threads properly. This will be sufficient to ensure
1316 // that this thread sees the updated eventBase_ variable after
1317 // readDataAvailable() returns.)
1318 uint16_t numReads = 0;
1319 EventBase* originalEventBase = eventBase_;
1320 while (readCallback_ && eventBase_ == originalEventBase) {
1321 // Get the buffer to read into.
1322 void* buf = nullptr;
1323 size_t buflen = 0, offset = 0;
1325 prepareReadBuffer(&buf, &buflen);
1326 VLOG(5) << "prepareReadBuffer() buf=" << buf << ", buflen=" << buflen;
1327 } catch (const AsyncSocketException& ex) {
1328 return failRead(__func__, ex);
1329 } catch (const std::exception& ex) {
1330 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1331 string("ReadCallback::getReadBuffer() "
1332 "threw exception: ") +
1334 return failRead(__func__, tex);
1336 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1337 "ReadCallback::getReadBuffer() threw "
1338 "non-exception type");
1339 return failRead(__func__, ex);
1341 if (!isBufferMovable_ && (buf == nullptr || buflen == 0)) {
1342 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1343 "ReadCallback::getReadBuffer() returned "
1345 return failRead(__func__, ex);
1349 ssize_t bytesRead = performRead(&buf, &buflen, &offset);
1350 VLOG(4) << "this=" << this << ", AsyncSocket::handleRead() got "
1351 << bytesRead << " bytes";
1352 if (bytesRead > 0) {
1353 if (!isBufferMovable_) {
1354 readCallback_->readDataAvailable(bytesRead);
1356 CHECK(kOpenSslModeMoveBufferOwnership);
1357 VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
1358 << "buf=" << buf << ", " << bytesRead << "/" << buflen
1359 << ", offset=" << offset;
1360 auto readBuf = folly::IOBuf::takeOwnership(buf, buflen);
1361 readBuf->trimStart(offset);
1362 readBuf->trimEnd(buflen - offset - bytesRead);
1363 readCallback_->readBufferAvailable(std::move(readBuf));
1366 // Fall through and continue around the loop if the read
1367 // completely filled the available buffer.
1368 // Note that readCallback_ may have been uninstalled or changed inside
1369 // readDataAvailable().
1370 if (size_t(bytesRead) < buflen) {
1373 } else if (bytesRead == READ_BLOCKING) {
1374 // No more data to read right now.
1376 } else if (bytesRead == READ_ERROR) {
1377 readErr_ = READ_ERROR;
1378 auto errnoCopy = errno;
1379 AsyncSocketException ex(
1380 AsyncSocketException::INTERNAL_ERROR,
1381 withAddr("recv() failed"),
1383 return failRead(__func__, ex);
1385 assert(bytesRead == READ_EOF);
1386 readErr_ = READ_EOF;
1388 shutdownFlags_ |= SHUT_READ;
1389 if (!updateEventRegistration(0, EventHandler::READ)) {
1390 // we've already been moved into STATE_ERROR
1391 assert(state_ == StateEnum::ERROR);
1392 assert(readCallback_ == nullptr);
1396 ReadCallback* callback = readCallback_;
1397 readCallback_ = nullptr;
1398 callback->readEOF();
1401 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1402 if (readCallback_ != nullptr) {
1403 // We might still have data in the socket.
1404 // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
1405 scheduleImmediateRead();
1413 * This function attempts to write as much data as possible, until no more data
1416 * - If it sends all available data, it unregisters for write events, and stops
1417 * the writeTimeout_.
1419 * - If not all of the data can be sent immediately, it reschedules
1420 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1421 * registered for write events.
1423 void AsyncSocket::handleWrite() noexcept {
1424 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1425 << ", state=" << state_;
1426 if (state_ == StateEnum::CONNECTING) {
1432 assert(state_ == StateEnum::ESTABLISHED);
1433 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1434 assert(writeReqHead_ != nullptr);
1436 // Loop until we run out of write requests,
1437 // or until this socket is moved to another EventBase.
1438 // (See the comment in handleRead() explaining how this can happen.)
1439 EventBase* originalEventBase = eventBase_;
1440 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1441 if (!writeReqHead_->performWrite()) {
1442 auto errnoCopy = errno;
1443 AsyncSocketException ex(
1444 AsyncSocketException::INTERNAL_ERROR,
1445 withAddr("writev() failed"),
1447 return failWrite(__func__, ex);
1448 } else if (writeReqHead_->isComplete()) {
1449 // We finished this request
1450 WriteRequest* req = writeReqHead_;
1451 writeReqHead_ = req->getNext();
1453 if (writeReqHead_ == nullptr) {
1454 writeReqTail_ = nullptr;
1455 // This is the last write request.
1456 // Unregister for write events and cancel the send timer
1457 // before we invoke the callback. We have to update the state properly
1458 // before calling the callback, since it may want to detach us from
1460 if (eventFlags_ & EventHandler::WRITE) {
1461 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1462 assert(state_ == StateEnum::ERROR);
1465 // Stop the send timeout
1466 writeTimeout_.cancelTimeout();
1468 assert(!writeTimeout_.isScheduled());
1470 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
1471 // we finish sending the last write request.
1473 // We have to do this before invoking writeSuccess(), since
1474 // writeSuccess() may detach us from our EventBase.
1475 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
1476 assert(connectCallback_ == nullptr);
1477 shutdownFlags_ |= SHUT_WRITE;
1479 if (shutdownFlags_ & SHUT_READ) {
1480 // Reads have already been shutdown. Fully close the socket and
1481 // move to STATE_CLOSED.
1483 // Note: This code currently moves us to STATE_CLOSED even if
1484 // close() hasn't ever been called. This can occur if we have
1485 // received EOF from the peer and shutdownWrite() has been called
1486 // locally. Should we bother staying in STATE_ESTABLISHED in this
1487 // case, until close() is actually called? I can't think of a
1488 // reason why we would need to do so. No other operations besides
1489 // calling close() or destroying the socket can be performed at
1491 assert(readCallback_ == nullptr);
1492 state_ = StateEnum::CLOSED;
1494 ioHandler_.changeHandlerFD(-1);
1498 // Reads are still enabled, so we are only doing a half-shutdown
1499 ::shutdown(fd_, SHUT_WR);
1504 // Invoke the callback
1505 WriteCallback* callback = req->getCallback();
1508 callback->writeSuccess();
1510 // We'll continue around the loop, trying to write another request
1513 if (bufferCallback_) {
1514 bufferCallback_->onEgressBuffered();
1516 writeReqHead_->consume();
1517 // Stop after a partial write; it's highly likely that a subsequent write
1518 // attempt will just return EAGAIN.
1520 // Ensure that we are registered for write events.
1521 if ((eventFlags_ & EventHandler::WRITE) == 0) {
1522 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1523 assert(state_ == StateEnum::ERROR);
1528 // Reschedule the send timeout, since we have made some write progress.
1529 if (sendTimeout_ > 0) {
1530 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1531 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1532 withAddr("failed to reschedule write timeout"));
1533 return failWrite(__func__, ex);
1539 if (!writeReqHead_ && bufferCallback_) {
1540 bufferCallback_->onEgressBufferCleared();
1544 void AsyncSocket::checkForImmediateRead() noexcept {
1545 // We currently don't attempt to perform optimistic reads in AsyncSocket.
1546 // (However, note that some subclasses do override this method.)
1548 // Simply calling handleRead() here would be bad, as this would call
1549 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
1550 // buffer even though no data may be available. This would waste lots of
1551 // memory, since the buffer will sit around unused until the socket actually
1552 // becomes readable.
1554 // Checking if the socket is readable now also seems like it would probably
1555 // be a pessimism. In most cases it probably wouldn't be readable, and we
1556 // would just waste an extra system call. Even if it is readable, waiting to
1557 // find out from libevent on the next event loop doesn't seem that bad.
1560 void AsyncSocket::handleInitialReadWrite() noexcept {
1561 // Our callers should already be holding a DestructorGuard, but grab
1562 // one here just to make sure, in case one of our calling code paths ever
1564 DestructorGuard dg(this);
1566 // If we have a readCallback_, make sure we enable read events. We
1567 // may already be registered for reads if connectSuccess() set
1568 // the read calback.
1569 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
1570 assert(state_ == StateEnum::ESTABLISHED);
1571 assert((shutdownFlags_ & SHUT_READ) == 0);
1572 if (!updateEventRegistration(EventHandler::READ, 0)) {
1573 assert(state_ == StateEnum::ERROR);
1576 checkForImmediateRead();
1577 } else if (readCallback_ == nullptr) {
1578 // Unregister for read events.
1579 updateEventRegistration(0, EventHandler::READ);
1582 // If we have write requests pending, try to send them immediately.
1583 // Since we just finished accepting, there is a very good chance that we can
1584 // write without blocking.
1586 // However, we only process them if EventHandler::WRITE is not already set,
1587 // which means that we're already blocked on a write attempt. (This can
1588 // happen if connectSuccess() called write() before returning.)
1589 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
1590 // Call handleWrite() to perform write processing.
1592 } else if (writeReqHead_ == nullptr) {
1593 // Unregister for write event.
1594 updateEventRegistration(0, EventHandler::WRITE);
1598 void AsyncSocket::handleConnect() noexcept {
1599 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
1600 << ", state=" << state_;
1601 assert(state_ == StateEnum::CONNECTING);
1602 // SHUT_WRITE can never be set while we are still connecting;
1603 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
1605 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1607 // In case we had a connect timeout, cancel the timeout
1608 writeTimeout_.cancelTimeout();
1609 // We don't use a persistent registration when waiting on a connect event,
1610 // so we have been automatically unregistered now. Update eventFlags_ to
1612 assert(eventFlags_ == EventHandler::WRITE);
1613 eventFlags_ = EventHandler::NONE;
1615 // Call getsockopt() to check if the connect succeeded
1617 socklen_t len = sizeof(error);
1618 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
1620 auto errnoCopy = errno;
1621 AsyncSocketException ex(
1622 AsyncSocketException::INTERNAL_ERROR,
1623 withAddr("error calling getsockopt() after connect"),
1625 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1626 << fd_ << " host=" << addr_.describe()
1627 << ") exception:" << ex.what();
1628 return failConnect(__func__, ex);
1632 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1633 "connect failed", error);
1634 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1635 << fd_ << " host=" << addr_.describe()
1636 << ") exception: " << ex.what();
1637 return failConnect(__func__, ex);
1640 // Move into STATE_ESTABLISHED
1641 state_ = StateEnum::ESTABLISHED;
1643 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
1644 // perform, immediately shutdown the write half of the socket.
1645 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
1646 // SHUT_READ shouldn't be set. If close() is called on the socket while we
1647 // are still connecting we just abort the connect rather than waiting for
1649 assert((shutdownFlags_ & SHUT_READ) == 0);
1650 ::shutdown(fd_, SHUT_WR);
1651 shutdownFlags_ |= SHUT_WRITE;
1654 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
1655 << "successfully connected; state=" << state_;
1657 // Remember the EventBase we are attached to, before we start invoking any
1658 // callbacks (since the callbacks may call detachEventBase()).
1659 EventBase* originalEventBase = eventBase_;
1661 invokeConnectSuccess();
1662 // Note that the connect callback may have changed our state.
1663 // (set or unset the read callback, called write(), closed the socket, etc.)
1664 // The following code needs to handle these situations correctly.
1666 // If the socket has been closed, readCallback_ and writeReqHead_ will
1667 // always be nullptr, so that will prevent us from trying to read or write.
1669 // The main thing to check for is if eventBase_ is still originalEventBase.
1670 // If not, we have been detached from this event base, so we shouldn't
1671 // perform any more operations.
1672 if (eventBase_ != originalEventBase) {
1676 handleInitialReadWrite();
1679 void AsyncSocket::timeoutExpired() noexcept {
1680 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
1681 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
1682 DestructorGuard dg(this);
1683 assert(eventBase_->isInEventBaseThread());
1685 if (state_ == StateEnum::CONNECTING) {
1686 // connect() timed out
1687 // Unregister for I/O events.
1688 AsyncSocketException ex(AsyncSocketException::TIMED_OUT,
1689 "connect timed out");
1690 failConnect(__func__, ex);
1692 // a normal write operation timed out
1693 assert(state_ == StateEnum::ESTABLISHED);
1694 AsyncSocketException ex(AsyncSocketException::TIMED_OUT, "write timed out");
1695 failWrite(__func__, ex);
1699 ssize_t AsyncSocket::performWrite(const iovec* vec,
1702 uint32_t* countWritten,
1703 uint32_t* partialWritten) {
1704 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
1705 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
1706 // (since it may terminate the program if the main program doesn't explicitly
1709 msg.msg_name = nullptr;
1710 msg.msg_namelen = 0;
1711 msg.msg_iov = const_cast<iovec *>(vec);
1712 msg.msg_iovlen = std::min<size_t>(count, kIovMax);
1713 msg.msg_control = nullptr;
1714 msg.msg_controllen = 0;
1717 int msg_flags = MSG_DONTWAIT;
1719 #ifdef MSG_NOSIGNAL // Linux-only
1720 msg_flags |= MSG_NOSIGNAL;
1721 if (isSet(flags, WriteFlags::CORK)) {
1722 // MSG_MORE tells the kernel we have more data to send, so wait for us to
1723 // give it the rest of the data rather than immediately sending a partial
1724 // frame, even when TCP_NODELAY is enabled.
1725 msg_flags |= MSG_MORE;
1728 if (isSet(flags, WriteFlags::EOR)) {
1729 // marks that this is the last byte of a record (response)
1730 msg_flags |= MSG_EOR;
1732 ssize_t totalWritten = ::sendmsg(fd_, &msg, msg_flags);
1733 if (totalWritten < 0) {
1734 if (errno == EAGAIN) {
1735 // TCP buffer is full; we can't write any more data right now.
1737 *partialWritten = 0;
1742 *partialWritten = 0;
1746 appBytesWritten_ += totalWritten;
1748 uint32_t bytesWritten;
1750 for (bytesWritten = totalWritten, n = 0; n < count; ++n) {
1751 const iovec* v = vec + n;
1752 if (v->iov_len > bytesWritten) {
1753 // Partial write finished in the middle of this iovec
1755 *partialWritten = bytesWritten;
1756 return totalWritten;
1759 bytesWritten -= v->iov_len;
1762 assert(bytesWritten == 0);
1764 *partialWritten = 0;
1765 return totalWritten;
1769 * Re-register the EventHandler after eventFlags_ has changed.
1771 * If an error occurs, fail() is called to move the socket into the error state
1772 * and call all currently installed callbacks. After an error, the
1773 * AsyncSocket is completely unregistered.
1775 * @return Returns true on succcess, or false on error.
1777 bool AsyncSocket::updateEventRegistration() {
1778 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
1779 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
1780 << ", events=" << std::hex << eventFlags_;
1781 assert(eventBase_->isInEventBaseThread());
1782 if (eventFlags_ == EventHandler::NONE) {
1783 ioHandler_.unregisterHandler();
1787 // Always register for persistent events, so we don't have to re-register
1788 // after being called back.
1789 if (!ioHandler_.registerHandler(eventFlags_ | EventHandler::PERSIST)) {
1790 eventFlags_ = EventHandler::NONE; // we're not registered after error
1791 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1792 withAddr("failed to update AsyncSocket event registration"));
1793 fail("updateEventRegistration", ex);
1800 bool AsyncSocket::updateEventRegistration(uint16_t enable,
1802 uint16_t oldFlags = eventFlags_;
1803 eventFlags_ |= enable;
1804 eventFlags_ &= ~disable;
1805 if (eventFlags_ == oldFlags) {
1808 return updateEventRegistration();
1812 void AsyncSocket::startFail() {
1813 // startFail() should only be called once
1814 assert(state_ != StateEnum::ERROR);
1815 assert(getDestructorGuardCount() > 0);
1816 state_ = StateEnum::ERROR;
1817 // Ensure that SHUT_READ and SHUT_WRITE are set,
1818 // so all future attempts to read or write will be rejected
1819 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1821 if (eventFlags_ != EventHandler::NONE) {
1822 eventFlags_ = EventHandler::NONE;
1823 ioHandler_.unregisterHandler();
1825 writeTimeout_.cancelTimeout();
1828 ioHandler_.changeHandlerFD(-1);
1833 void AsyncSocket::finishFail() {
1834 assert(state_ == StateEnum::ERROR);
1835 assert(getDestructorGuardCount() > 0);
1837 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1838 withAddr("socket closing after error"));
1839 invokeConnectErr(ex);
1842 if (readCallback_) {
1843 ReadCallback* callback = readCallback_;
1844 readCallback_ = nullptr;
1845 callback->readErr(ex);
1849 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
1850 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1851 << state_ << " host=" << addr_.describe()
1852 << "): failed in " << fn << "(): "
1858 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
1859 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1860 << state_ << " host=" << addr_.describe()
1861 << "): failed while connecting in " << fn << "(): "
1865 invokeConnectErr(ex);
1869 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
1870 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1871 << state_ << " host=" << addr_.describe()
1872 << "): failed while reading in " << fn << "(): "
1876 if (readCallback_ != nullptr) {
1877 ReadCallback* callback = readCallback_;
1878 readCallback_ = nullptr;
1879 callback->readErr(ex);
1885 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
1886 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1887 << state_ << " host=" << addr_.describe()
1888 << "): failed while writing in " << fn << "(): "
1892 // Only invoke the first write callback, since the error occurred while
1893 // writing this request. Let any other pending write callbacks be invoked in
1895 if (writeReqHead_ != nullptr) {
1896 WriteRequest* req = writeReqHead_;
1897 writeReqHead_ = req->getNext();
1898 WriteCallback* callback = req->getCallback();
1899 uint32_t bytesWritten = req->getTotalBytesWritten();
1902 callback->writeErr(bytesWritten, ex);
1909 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
1910 size_t bytesWritten,
1911 const AsyncSocketException& ex) {
1912 // This version of failWrite() is used when the failure occurs before
1913 // we've added the callback to writeReqHead_.
1914 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
1915 << state_ << " host=" << addr_.describe()
1916 <<"): failed while writing in " << fn << "(): "
1920 if (callback != nullptr) {
1921 callback->writeErr(bytesWritten, ex);
1927 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
1928 // Invoke writeError() on all write callbacks.
1929 // This is used when writes are forcibly shutdown with write requests
1930 // pending, or when an error occurs with writes pending.
1931 while (writeReqHead_ != nullptr) {
1932 WriteRequest* req = writeReqHead_;
1933 writeReqHead_ = req->getNext();
1934 WriteCallback* callback = req->getCallback();
1936 callback->writeErr(req->getTotalBytesWritten(), ex);
1942 void AsyncSocket::invalidState(ConnectCallback* callback) {
1943 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
1944 << "): connect() called in invalid state " << state_;
1947 * The invalidState() methods don't use the normal failure mechanisms,
1948 * since we don't know what state we are in. We don't want to call
1949 * startFail()/finishFail() recursively if we are already in the middle of
1953 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
1954 "connect() called with socket in invalid state");
1955 connectEndTime_ = std::chrono::steady_clock::now();
1956 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
1958 callback->connectErr(ex);
1961 // We can't use failConnect() here since connectCallback_
1962 // may already be set to another callback. Invoke this ConnectCallback
1963 // here; any other connectCallback_ will be invoked in finishFail()
1966 callback->connectErr(ex);
1972 void AsyncSocket::invokeConnectErr(const AsyncSocketException& ex) {
1973 connectEndTime_ = std::chrono::steady_clock::now();
1974 if (connectCallback_) {
1975 ConnectCallback* callback = connectCallback_;
1976 connectCallback_ = nullptr;
1977 callback->connectErr(ex);
1981 void AsyncSocket::invokeConnectSuccess() {
1982 connectEndTime_ = std::chrono::steady_clock::now();
1983 if (connectCallback_) {
1984 ConnectCallback* callback = connectCallback_;
1985 connectCallback_ = nullptr;
1986 callback->connectSuccess();
1990 void AsyncSocket::invalidState(ReadCallback* callback) {
1991 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
1992 << "): setReadCallback(" << callback
1993 << ") called in invalid state " << state_;
1995 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1996 "setReadCallback() called with socket in "
1998 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2000 callback->readErr(ex);
2005 callback->readErr(ex);
2011 void AsyncSocket::invalidState(WriteCallback* callback) {
2012 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2013 << "): write() called in invalid state " << state_;
2015 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2016 withAddr("write() called with socket in invalid state"));
2017 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2019 callback->writeErr(0, ex);
2024 callback->writeErr(0, ex);
2030 void AsyncSocket::doClose() {
2031 if (fd_ == -1) return;
2032 if (shutdownSocketSet_) {
2033 shutdownSocketSet_->close(fd_);
2040 std::ostream& operator << (std::ostream& os,
2041 const AsyncSocket::StateEnum& state) {
2042 os << static_cast<int>(state);
2046 std::string AsyncSocket::withAddr(const std::string& s) {
2047 // Don't use addr_ directly because it may not be initialized
2048 // e.g. if constructed from fd
2049 folly::SocketAddress peer, local;
2051 getPeerAddress(&peer);
2052 getLocalAddress(&local);
2053 } catch (const std::exception&) {
2058 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";
2061 void AsyncSocket::setBufferCallback(BufferCallback* cb) {
2062 bufferCallback_ = cb;