2 * Copyright 2017 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/ExceptionWrapper.h>
20 #include <folly/SocketAddress.h>
21 #include <folly/io/IOBuf.h>
22 #include <folly/Portability.h>
23 #include <folly/portability/Fcntl.h>
24 #include <folly/portability/Sockets.h>
25 #include <folly/portability/SysUio.h>
26 #include <folly/portability/Unistd.h>
31 #include <sys/types.h>
32 #include <boost/preprocessor/control/if.hpp>
35 using std::unique_ptr;
37 namespace fsp = folly::portability::sockets;
41 // static members initializers
42 const AsyncSocket::OptionMap AsyncSocket::emptyOptionMap;
44 const AsyncSocketException socketClosedLocallyEx(
45 AsyncSocketException::END_OF_FILE, "socket closed locally");
46 const AsyncSocketException socketShutdownForWritesEx(
47 AsyncSocketException::END_OF_FILE, "socket shutdown for writes");
49 // TODO: It might help performance to provide a version of BytesWriteRequest that
50 // users could derive from, so we can avoid the extra allocation for each call
51 // to write()/writev(). We could templatize TFramedAsyncChannel just like the
52 // protocols are currently templatized for transports.
54 // We would need the version for external users where they provide the iovec
55 // storage space, and only our internal version would allocate it at the end of
58 /* The default WriteRequest implementation, used for write(), writev() and
61 * A new BytesWriteRequest operation is allocated on the heap for all write
62 * operations that cannot be completed immediately.
64 class AsyncSocket::BytesWriteRequest : public AsyncSocket::WriteRequest {
66 static BytesWriteRequest* newRequest(AsyncSocket* socket,
67 WriteCallback* callback,
70 uint32_t partialWritten,
71 uint32_t bytesWritten,
72 unique_ptr<IOBuf>&& ioBuf,
75 // Since we put a variable size iovec array at the end
76 // of each BytesWriteRequest, we have to manually allocate the memory.
77 void* buf = malloc(sizeof(BytesWriteRequest) +
78 (opCount * sizeof(struct iovec)));
80 throw std::bad_alloc();
83 return new(buf) BytesWriteRequest(socket, callback, ops, opCount,
84 partialWritten, bytesWritten,
85 std::move(ioBuf), flags);
88 void destroy() override {
89 this->~BytesWriteRequest();
93 WriteResult performWrite() override {
94 WriteFlags writeFlags = flags_;
95 if (getNext() != nullptr) {
96 writeFlags = writeFlags | WriteFlags::CORK;
98 auto writeResult = socket_->performWrite(
99 getOps(), getOpCount(), writeFlags, &opsWritten_, &partialBytes_);
100 bytesWritten_ = writeResult.writeReturn > 0 ? writeResult.writeReturn : 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 assert(bytesWritten_ >= 0);
130 totalBytesWritten_ += uint32_t(bytesWritten_);
134 BytesWriteRequest(AsyncSocket* socket,
135 WriteCallback* callback,
136 const struct iovec* ops,
138 uint32_t partialBytes,
139 uint32_t bytesWritten,
140 unique_ptr<IOBuf>&& ioBuf,
142 : AsyncSocket::WriteRequest(socket, callback)
146 , ioBuf_(std::move(ioBuf))
148 , partialBytes_(partialBytes)
149 , bytesWritten_(bytesWritten) {
150 memcpy(writeOps_, ops, sizeof(*ops) * opCount_);
153 // private destructor, to ensure callers use destroy()
154 ~BytesWriteRequest() override = default;
156 const struct iovec* getOps() const {
157 assert(opCount_ > opIndex_);
158 return writeOps_ + opIndex_;
161 uint32_t getOpCount() const {
162 assert(opCount_ > opIndex_);
163 return opCount_ - opIndex_;
166 uint32_t opCount_; ///< number of entries in writeOps_
167 uint32_t opIndex_; ///< current index into writeOps_
168 WriteFlags flags_; ///< set for WriteFlags
169 unique_ptr<IOBuf> ioBuf_; ///< underlying IOBuf, or nullptr if N/A
171 // for consume(), how much we wrote on the last write
172 uint32_t opsWritten_; ///< complete ops written
173 uint32_t partialBytes_; ///< partial bytes of incomplete op written
174 ssize_t bytesWritten_; ///< bytes written altogether
176 struct iovec writeOps_[]; ///< write operation(s) list
179 AsyncSocket::AsyncSocket()
180 : eventBase_(nullptr),
181 writeTimeout_(this, nullptr),
182 ioHandler_(this, nullptr),
183 immediateReadHandler_(this) {
184 VLOG(5) << "new AsyncSocket()";
188 AsyncSocket::AsyncSocket(EventBase* evb)
190 writeTimeout_(this, evb),
191 ioHandler_(this, evb),
192 immediateReadHandler_(this) {
193 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
197 AsyncSocket::AsyncSocket(EventBase* evb,
198 const folly::SocketAddress& address,
199 uint32_t connectTimeout)
201 connect(nullptr, address, connectTimeout);
204 AsyncSocket::AsyncSocket(EventBase* evb,
205 const std::string& ip,
207 uint32_t connectTimeout)
209 connect(nullptr, ip, port, connectTimeout);
212 AsyncSocket::AsyncSocket(EventBase* evb, int fd)
214 writeTimeout_(this, evb),
215 ioHandler_(this, evb, fd),
216 immediateReadHandler_(this) {
217 VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ", fd="
222 state_ = StateEnum::ESTABLISHED;
225 // init() method, since constructor forwarding isn't supported in most
227 void AsyncSocket::init() {
228 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
230 state_ = StateEnum::UNINIT;
231 eventFlags_ = EventHandler::NONE;
234 maxReadsPerEvent_ = 16;
235 connectCallback_ = nullptr;
236 readCallback_ = nullptr;
237 writeReqHead_ = nullptr;
238 writeReqTail_ = nullptr;
239 shutdownSocketSet_ = nullptr;
240 appBytesWritten_ = 0;
241 appBytesReceived_ = 0;
244 AsyncSocket::~AsyncSocket() {
245 VLOG(7) << "actual destruction of AsyncSocket(this=" << this
246 << ", evb=" << eventBase_ << ", fd=" << fd_
247 << ", state=" << state_ << ")";
250 void AsyncSocket::destroy() {
251 VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
252 << ", fd=" << fd_ << ", state=" << state_;
253 // When destroy is called, close the socket immediately
256 // Then call DelayedDestruction::destroy() to take care of
257 // whether or not we need immediate or delayed destruction
258 DelayedDestruction::destroy();
261 int AsyncSocket::detachFd() {
262 VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
263 << ", evb=" << eventBase_ << ", state=" << state_
264 << ", events=" << std::hex << eventFlags_ << ")";
265 // Extract the fd, and set fd_ to -1 first, so closeNow() won't
266 // actually close the descriptor.
267 if (shutdownSocketSet_) {
268 shutdownSocketSet_->remove(fd_);
272 // Call closeNow() to invoke all pending callbacks with an error.
274 // Update the EventHandler to stop using this fd.
275 // This can only be done after closeNow() unregisters the handler.
276 ioHandler_.changeHandlerFD(-1);
280 const folly::SocketAddress& AsyncSocket::anyAddress() {
281 static const folly::SocketAddress anyAddress =
282 folly::SocketAddress("0.0.0.0", 0);
286 void AsyncSocket::setShutdownSocketSet(ShutdownSocketSet* newSS) {
287 if (shutdownSocketSet_ == newSS) {
290 if (shutdownSocketSet_ && fd_ != -1) {
291 shutdownSocketSet_->remove(fd_);
293 shutdownSocketSet_ = newSS;
294 if (shutdownSocketSet_ && fd_ != -1) {
295 shutdownSocketSet_->add(fd_);
299 void AsyncSocket::setCloseOnExec() {
300 int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
302 auto errnoCopy = errno;
303 throw AsyncSocketException(
304 AsyncSocketException::INTERNAL_ERROR,
305 withAddr("failed to set close-on-exec flag"),
310 void AsyncSocket::connect(ConnectCallback* callback,
311 const folly::SocketAddress& address,
313 const OptionMap &options,
314 const folly::SocketAddress& bindAddr) noexcept {
315 DestructorGuard dg(this);
316 assert(eventBase_->isInEventBaseThread());
320 // Make sure we're in the uninitialized state
321 if (state_ != StateEnum::UNINIT) {
322 return invalidState(callback);
325 connectTimeout_ = std::chrono::milliseconds(timeout);
326 connectStartTime_ = std::chrono::steady_clock::now();
327 // Make connect end time at least >= connectStartTime.
328 connectEndTime_ = connectStartTime_;
331 state_ = StateEnum::CONNECTING;
332 connectCallback_ = callback;
334 sockaddr_storage addrStorage;
335 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
339 // Technically the first parameter should actually be a protocol family
340 // constant (PF_xxx) rather than an address family (AF_xxx), but the
341 // distinction is mainly just historical. In pretty much all
342 // implementations the PF_foo and AF_foo constants are identical.
343 fd_ = fsp::socket(address.getFamily(), SOCK_STREAM, 0);
345 auto errnoCopy = errno;
346 throw AsyncSocketException(
347 AsyncSocketException::INTERNAL_ERROR,
348 withAddr("failed to create socket"),
351 if (shutdownSocketSet_) {
352 shutdownSocketSet_->add(fd_);
354 ioHandler_.changeHandlerFD(fd_);
358 // Put the socket in non-blocking mode
359 int flags = fcntl(fd_, F_GETFL, 0);
361 auto errnoCopy = errno;
362 throw AsyncSocketException(
363 AsyncSocketException::INTERNAL_ERROR,
364 withAddr("failed to get socket flags"),
367 int rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
369 auto errnoCopy = errno;
370 throw AsyncSocketException(
371 AsyncSocketException::INTERNAL_ERROR,
372 withAddr("failed to put socket in non-blocking mode"),
376 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
377 // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
378 rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
380 auto errnoCopy = errno;
381 throw AsyncSocketException(
382 AsyncSocketException::INTERNAL_ERROR,
383 "failed to enable F_SETNOSIGPIPE on socket",
388 // By default, turn on TCP_NODELAY
389 // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
390 // setNoDelay() will log an error message if it fails.
391 if (address.getFamily() != AF_UNIX) {
392 (void)setNoDelay(true);
395 VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
396 << ", fd=" << fd_ << ", host=" << address.describe().c_str();
399 if (bindAddr != anyAddress()) {
401 if (setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
402 auto errnoCopy = errno;
404 throw AsyncSocketException(
405 AsyncSocketException::NOT_OPEN,
406 "failed to setsockopt prior to bind on " + bindAddr.describe(),
410 bindAddr.getAddress(&addrStorage);
412 if (bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
413 auto errnoCopy = errno;
415 throw AsyncSocketException(
416 AsyncSocketException::NOT_OPEN,
417 "failed to bind to async socket: " + bindAddr.describe(),
422 // Apply the additional options if any.
423 for (const auto& opt: options) {
424 rv = opt.first.apply(fd_, opt.second);
426 auto errnoCopy = errno;
427 throw AsyncSocketException(
428 AsyncSocketException::INTERNAL_ERROR,
429 withAddr("failed to set socket option"),
434 // Perform the connect()
435 address.getAddress(&addrStorage);
438 state_ = StateEnum::FAST_OPEN;
439 tfoAttempted_ = true;
441 if (socketConnect(saddr, addr_.getActualSize()) < 0) {
446 // If we're still here the connect() succeeded immediately.
447 // Fall through to call the callback outside of this try...catch block
448 } catch (const AsyncSocketException& ex) {
449 return failConnect(__func__, ex);
450 } catch (const std::exception& ex) {
451 // shouldn't happen, but handle it just in case
452 VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
453 << "): unexpected " << typeid(ex).name() << " exception: "
455 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
456 withAddr(string("unexpected exception: ") +
458 return failConnect(__func__, tex);
461 // The connection succeeded immediately
462 // The read callback may not have been set yet, and no writes may be pending
463 // yet, so we don't have to register for any events at the moment.
464 VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
465 assert(readCallback_ == nullptr);
466 assert(writeReqHead_ == nullptr);
467 if (state_ != StateEnum::FAST_OPEN) {
468 state_ = StateEnum::ESTABLISHED;
470 invokeConnectSuccess();
473 int AsyncSocket::socketConnect(const struct sockaddr* saddr, socklen_t len) {
475 if (noTransparentTls_) {
476 // Ignore return value, errors are ok
477 setsockopt(fd_, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0);
480 int rv = fsp::connect(fd_, saddr, len);
482 auto errnoCopy = errno;
483 if (errnoCopy == EINPROGRESS) {
484 scheduleConnectTimeout();
485 registerForConnectEvents();
487 throw AsyncSocketException(
488 AsyncSocketException::NOT_OPEN,
489 "connect failed (immediately)",
496 void AsyncSocket::scheduleConnectTimeout() {
497 // Connection in progress.
498 auto timeout = connectTimeout_.count();
500 // Start a timer in case the connection takes too long.
501 if (!writeTimeout_.scheduleTimeout(uint32_t(timeout))) {
502 throw AsyncSocketException(
503 AsyncSocketException::INTERNAL_ERROR,
504 withAddr("failed to schedule AsyncSocket connect timeout"));
509 void AsyncSocket::registerForConnectEvents() {
510 // Register for write events, so we'll
511 // be notified when the connection finishes/fails.
512 // Note that we don't register for a persistent event here.
513 assert(eventFlags_ == EventHandler::NONE);
514 eventFlags_ = EventHandler::WRITE;
515 if (!ioHandler_.registerHandler(eventFlags_)) {
516 throw AsyncSocketException(
517 AsyncSocketException::INTERNAL_ERROR,
518 withAddr("failed to register AsyncSocket connect handler"));
522 void AsyncSocket::connect(ConnectCallback* callback,
523 const string& ip, uint16_t port,
525 const OptionMap &options) noexcept {
526 DestructorGuard dg(this);
528 connectCallback_ = callback;
529 connect(callback, folly::SocketAddress(ip, port), timeout, options);
530 } catch (const std::exception& ex) {
531 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
533 return failConnect(__func__, tex);
537 void AsyncSocket::cancelConnect() {
538 connectCallback_ = nullptr;
539 if (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN) {
544 void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
545 sendTimeout_ = milliseconds;
546 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
548 // If we are currently pending on write requests, immediately update
549 // writeTimeout_ with the new value.
550 if ((eventFlags_ & EventHandler::WRITE) &&
551 (state_ != StateEnum::CONNECTING && state_ != StateEnum::FAST_OPEN)) {
552 assert(state_ == StateEnum::ESTABLISHED);
553 assert((shutdownFlags_ & SHUT_WRITE) == 0);
554 if (sendTimeout_ > 0) {
555 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
556 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
557 withAddr("failed to reschedule send timeout in setSendTimeout"));
558 return failWrite(__func__, ex);
561 writeTimeout_.cancelTimeout();
566 void AsyncSocket::setReadCB(ReadCallback *callback) {
567 VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
568 << ", callback=" << callback << ", state=" << state_;
570 // Short circuit if callback is the same as the existing readCallback_.
572 // Note that this is needed for proper functioning during some cleanup cases.
573 // During cleanup we allow setReadCallback(nullptr) to be called even if the
574 // read callback is already unset and we have been detached from an event
575 // base. This check prevents us from asserting
576 // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
577 if (callback == readCallback_) {
581 /* We are removing a read callback */
582 if (callback == nullptr &&
583 immediateReadHandler_.isLoopCallbackScheduled()) {
584 immediateReadHandler_.cancelLoopCallback();
587 if (shutdownFlags_ & SHUT_READ) {
588 // Reads have already been shut down on this socket.
590 // Allow setReadCallback(nullptr) to be called in this case, but don't
591 // allow a new callback to be set.
593 // For example, setReadCallback(nullptr) can happen after an error if we
594 // invoke some other error callback before invoking readError(). The other
595 // error callback that is invoked first may go ahead and clear the read
596 // callback before we get a chance to invoke readError().
597 if (callback != nullptr) {
598 return invalidState(callback);
600 assert((eventFlags_ & EventHandler::READ) == 0);
601 readCallback_ = nullptr;
605 DestructorGuard dg(this);
606 assert(eventBase_->isInEventBaseThread());
608 switch ((StateEnum)state_) {
609 case StateEnum::CONNECTING:
610 case StateEnum::FAST_OPEN:
611 // For convenience, we allow the read callback to be set while we are
612 // still connecting. We just store the callback for now. Once the
613 // connection completes we'll register for read events.
614 readCallback_ = callback;
616 case StateEnum::ESTABLISHED:
618 readCallback_ = callback;
619 uint16_t oldFlags = eventFlags_;
621 eventFlags_ |= EventHandler::READ;
623 eventFlags_ &= ~EventHandler::READ;
626 // Update our registration if our flags have changed
627 if (eventFlags_ != oldFlags) {
628 // We intentionally ignore the return value here.
629 // updateEventRegistration() will move us into the error state if it
630 // fails, and we don't need to do anything else here afterwards.
631 (void)updateEventRegistration();
635 checkForImmediateRead();
639 case StateEnum::CLOSED:
640 case StateEnum::ERROR:
641 // We should never reach here. SHUT_READ should always be set
642 // if we are in STATE_CLOSED or STATE_ERROR.
644 return invalidState(callback);
645 case StateEnum::UNINIT:
646 // We do not allow setReadCallback() to be called before we start
648 return invalidState(callback);
651 // We don't put a default case in the switch statement, so that the compiler
652 // will warn us to update the switch statement if a new state is added.
653 return invalidState(callback);
656 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
657 return readCallback_;
660 void AsyncSocket::write(WriteCallback* callback,
661 const void* buf, size_t bytes, WriteFlags flags) {
663 op.iov_base = const_cast<void*>(buf);
665 writeImpl(callback, &op, 1, unique_ptr<IOBuf>(), flags);
668 void AsyncSocket::writev(WriteCallback* callback,
672 writeImpl(callback, vec, count, unique_ptr<IOBuf>(), flags);
675 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
677 constexpr size_t kSmallSizeMax = 64;
678 size_t count = buf->countChainElements();
679 if (count <= kSmallSizeMax) {
680 // suppress "warning: variable length array 'vec' is used [-Wvla]"
682 FOLLY_GCC_DISABLE_WARNING(vla);
683 iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA, count, kSmallSizeMax)];
686 writeChainImpl(callback, vec, count, std::move(buf), flags);
688 iovec* vec = new iovec[count];
689 writeChainImpl(callback, vec, count, std::move(buf), flags);
694 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
695 size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
696 size_t veclen = buf->fillIov(vec, count);
697 writeImpl(callback, vec, veclen, std::move(buf), flags);
700 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
701 size_t count, unique_ptr<IOBuf>&& buf,
703 VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
704 << ", callback=" << callback << ", count=" << count
705 << ", state=" << state_;
706 DestructorGuard dg(this);
707 unique_ptr<IOBuf>ioBuf(std::move(buf));
708 assert(eventBase_->isInEventBaseThread());
710 if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
711 // No new writes may be performed after the write side of the socket has
714 // We could just call callback->writeError() here to fail just this write.
715 // However, fail hard and use invalidState() to fail all outstanding
716 // callbacks and move the socket into the error state. There's most likely
717 // a bug in the caller's code, so we abort everything rather than trying to
718 // proceed as best we can.
719 return invalidState(callback);
722 uint32_t countWritten = 0;
723 uint32_t partialWritten = 0;
724 ssize_t bytesWritten = 0;
725 bool mustRegister = false;
726 if ((state_ == StateEnum::ESTABLISHED || state_ == StateEnum::FAST_OPEN) &&
728 if (writeReqHead_ == nullptr) {
729 // If we are established and there are no other writes pending,
730 // we can attempt to perform the write immediately.
731 assert(writeReqTail_ == nullptr);
732 assert((eventFlags_ & EventHandler::WRITE) == 0);
734 auto writeResult = performWrite(
735 vec, uint32_t(count), flags, &countWritten, &partialWritten);
736 bytesWritten = writeResult.writeReturn;
737 if (bytesWritten < 0) {
738 auto errnoCopy = errno;
739 if (writeResult.exception) {
740 return failWrite(__func__, callback, 0, *writeResult.exception);
742 AsyncSocketException ex(
743 AsyncSocketException::INTERNAL_ERROR,
744 withAddr("writev failed"),
746 return failWrite(__func__, callback, 0, ex);
747 } else if (countWritten == count) {
748 // We successfully wrote everything.
749 // Invoke the callback and return.
751 callback->writeSuccess();
754 } else { // continue writing the next writeReq
755 if (bufferCallback_) {
756 bufferCallback_->onEgressBuffered();
760 // Writes might put the socket back into connecting state
761 // if TFO is enabled, and using TFO fails.
762 // This means that write timeouts would not be active, however
763 // connect timeouts would affect this stage.
767 } else if (!connecting()) {
768 // Invalid state for writing
769 return invalidState(callback);
772 // Create a new WriteRequest to add to the queue
775 req = BytesWriteRequest::newRequest(
779 uint32_t(count - countWritten),
781 uint32_t(bytesWritten),
784 } catch (const std::exception& ex) {
785 // we mainly expect to catch std::bad_alloc here
786 AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
787 withAddr(string("failed to append new WriteRequest: ") + ex.what()));
788 return failWrite(__func__, callback, size_t(bytesWritten), tex);
791 if (writeReqTail_ == nullptr) {
792 assert(writeReqHead_ == nullptr);
793 writeReqHead_ = writeReqTail_ = req;
795 writeReqTail_->append(req);
799 // Register for write events if are established and not currently
800 // waiting on write events
802 assert(state_ == StateEnum::ESTABLISHED);
803 assert((eventFlags_ & EventHandler::WRITE) == 0);
804 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
805 assert(state_ == StateEnum::ERROR);
808 if (sendTimeout_ > 0) {
809 // Schedule a timeout to fire if the write takes too long.
810 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
811 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
812 withAddr("failed to schedule send timeout"));
813 return failWrite(__func__, ex);
819 void AsyncSocket::writeRequest(WriteRequest* req) {
820 if (writeReqTail_ == nullptr) {
821 assert(writeReqHead_ == nullptr);
822 writeReqHead_ = writeReqTail_ = req;
825 writeReqTail_->append(req);
830 void AsyncSocket::close() {
831 VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
832 << ", state=" << state_ << ", shutdownFlags="
833 << std::hex << (int) shutdownFlags_;
835 // close() is only different from closeNow() when there are pending writes
836 // that need to drain before we can close. In all other cases, just call
839 // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
840 // STATE_ERROR if close() is invoked while a previous closeNow() or failure
841 // is still running. (e.g., If there are multiple pending writes, and we
842 // call writeError() on the first one, it may call close(). In this case we
843 // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
844 // writes will still be in the queue.)
846 // We only need to drain pending writes if we are still in STATE_CONNECTING
847 // or STATE_ESTABLISHED
848 if ((writeReqHead_ == nullptr) ||
849 !(state_ == StateEnum::CONNECTING ||
850 state_ == StateEnum::ESTABLISHED)) {
855 // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
856 // destroyed until close() returns.
857 DestructorGuard dg(this);
858 assert(eventBase_->isInEventBaseThread());
860 // Since there are write requests pending, we have to set the
861 // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
862 // connect finishes and we finish writing these requests.
864 // Set SHUT_READ to indicate that reads are shut down, and set the
865 // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
866 // pending writes complete.
867 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
869 // If a read callback is set, invoke readEOF() immediately to inform it that
870 // the socket has been closed and no more data can be read.
872 // Disable reads if they are enabled
873 if (!updateEventRegistration(0, EventHandler::READ)) {
874 // We're now in the error state; callbacks have been cleaned up
875 assert(state_ == StateEnum::ERROR);
876 assert(readCallback_ == nullptr);
878 ReadCallback* callback = readCallback_;
879 readCallback_ = nullptr;
885 void AsyncSocket::closeNow() {
886 VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
887 << ", state=" << state_ << ", shutdownFlags="
888 << std::hex << (int) shutdownFlags_;
889 DestructorGuard dg(this);
890 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
893 case StateEnum::ESTABLISHED:
894 case StateEnum::CONNECTING:
895 case StateEnum::FAST_OPEN: {
896 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
897 state_ = StateEnum::CLOSED;
899 // If the write timeout was set, cancel it.
900 writeTimeout_.cancelTimeout();
902 // If we are registered for I/O events, unregister.
903 if (eventFlags_ != EventHandler::NONE) {
904 eventFlags_ = EventHandler::NONE;
905 if (!updateEventRegistration()) {
906 // We will have been moved into the error state.
907 assert(state_ == StateEnum::ERROR);
912 if (immediateReadHandler_.isLoopCallbackScheduled()) {
913 immediateReadHandler_.cancelLoopCallback();
917 ioHandler_.changeHandlerFD(-1);
921 invokeConnectErr(socketClosedLocallyEx);
923 failAllWrites(socketClosedLocallyEx);
926 ReadCallback* callback = readCallback_;
927 readCallback_ = nullptr;
932 case StateEnum::CLOSED:
933 // Do nothing. It's possible that we are being called recursively
934 // from inside a callback that we invoked inside another call to close()
935 // that is still running.
937 case StateEnum::ERROR:
938 // Do nothing. The error handling code has performed (or is performing)
941 case StateEnum::UNINIT:
942 assert(eventFlags_ == EventHandler::NONE);
943 assert(connectCallback_ == nullptr);
944 assert(readCallback_ == nullptr);
945 assert(writeReqHead_ == nullptr);
946 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
947 state_ = StateEnum::CLOSED;
951 LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
952 << ") called in unknown state " << state_;
955 void AsyncSocket::closeWithReset() {
956 // Enable SO_LINGER, with the linger timeout set to 0.
957 // This will trigger a TCP reset when we close the socket.
959 struct linger optLinger = {1, 0};
960 if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
961 VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
962 << "on " << fd_ << ": errno=" << errno;
966 // Then let closeNow() take care of the rest
970 void AsyncSocket::shutdownWrite() {
971 VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
972 << ", state=" << state_ << ", shutdownFlags="
973 << std::hex << (int) shutdownFlags_;
975 // If there are no pending writes, shutdownWrite() is identical to
976 // shutdownWriteNow().
977 if (writeReqHead_ == nullptr) {
982 assert(eventBase_->isInEventBaseThread());
984 // There are pending writes. Set SHUT_WRITE_PENDING so that the actual
985 // shutdown will be performed once all writes complete.
986 shutdownFlags_ |= SHUT_WRITE_PENDING;
989 void AsyncSocket::shutdownWriteNow() {
990 VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
991 << ", fd=" << fd_ << ", state=" << state_
992 << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
994 if (shutdownFlags_ & SHUT_WRITE) {
995 // Writes are already shutdown; nothing else to do.
999 // If SHUT_READ is already set, just call closeNow() to completely
1000 // close the socket. This can happen if close() was called with writes
1001 // pending, and then shutdownWriteNow() is called before all pending writes
1003 if (shutdownFlags_ & SHUT_READ) {
1008 DestructorGuard dg(this);
1009 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
1011 switch (static_cast<StateEnum>(state_)) {
1012 case StateEnum::ESTABLISHED:
1014 shutdownFlags_ |= SHUT_WRITE;
1016 // If the write timeout was set, cancel it.
1017 writeTimeout_.cancelTimeout();
1019 // If we are registered for write events, unregister.
1020 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1021 // We will have been moved into the error state.
1022 assert(state_ == StateEnum::ERROR);
1026 // Shutdown writes on the file descriptor
1027 shutdown(fd_, SHUT_WR);
1029 // Immediately fail all write requests
1030 failAllWrites(socketShutdownForWritesEx);
1033 case StateEnum::CONNECTING:
1035 // Set the SHUT_WRITE_PENDING flag.
1036 // When the connection completes, it will check this flag,
1037 // shutdown the write half of the socket, and then set SHUT_WRITE.
1038 shutdownFlags_ |= SHUT_WRITE_PENDING;
1040 // Immediately fail all write requests
1041 failAllWrites(socketShutdownForWritesEx);
1044 case StateEnum::UNINIT:
1045 // Callers normally shouldn't call shutdownWriteNow() before the socket
1046 // even starts connecting. Nonetheless, go ahead and set
1047 // SHUT_WRITE_PENDING. Once the socket eventually connects it will
1048 // immediately shut down the write side of the socket.
1049 shutdownFlags_ |= SHUT_WRITE_PENDING;
1051 case StateEnum::FAST_OPEN:
1052 // In fast open state we haven't call connected yet, and if we shutdown
1053 // the writes, we will never try to call connect, so shut everything down
1054 shutdownFlags_ |= SHUT_WRITE;
1055 // Immediately fail all write requests
1056 failAllWrites(socketShutdownForWritesEx);
1058 case StateEnum::CLOSED:
1059 case StateEnum::ERROR:
1060 // We should never get here. SHUT_WRITE should always be set
1061 // in STATE_CLOSED and STATE_ERROR.
1062 VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
1063 << ", fd=" << fd_ << ") in unexpected state " << state_
1064 << " with SHUT_WRITE not set ("
1065 << std::hex << (int) shutdownFlags_ << ")";
1070 LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
1071 << fd_ << ") called in unknown state " << state_;
1074 bool AsyncSocket::readable() const {
1078 struct pollfd fds[1];
1080 fds[0].events = POLLIN;
1082 int rc = poll(fds, 1, 0);
1086 bool AsyncSocket::isPending() const {
1087 return ioHandler_.isPending();
1090 bool AsyncSocket::hangup() const {
1092 // sanity check, no one should ask for hangup if we are not connected.
1096 #ifdef POLLRDHUP // Linux-only
1097 struct pollfd fds[1];
1099 fds[0].events = POLLRDHUP|POLLHUP;
1102 return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1108 bool AsyncSocket::good() const {
1110 (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN ||
1111 state_ == StateEnum::ESTABLISHED) &&
1112 (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1115 bool AsyncSocket::error() const {
1116 return (state_ == StateEnum::ERROR);
1119 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1120 VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1121 << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1122 << ", state=" << state_ << ", events="
1123 << std::hex << eventFlags_ << ")";
1124 assert(eventBase_ == nullptr);
1125 assert(eventBase->isInEventBaseThread());
1127 eventBase_ = eventBase;
1128 ioHandler_.attachEventBase(eventBase);
1129 writeTimeout_.attachEventBase(eventBase);
1131 evbChangeCb_->evbAttached(this);
1135 void AsyncSocket::detachEventBase() {
1136 VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1137 << ", old evb=" << eventBase_ << ", state=" << state_
1138 << ", events=" << std::hex << eventFlags_ << ")";
1139 assert(eventBase_ != nullptr);
1140 assert(eventBase_->isInEventBaseThread());
1142 eventBase_ = nullptr;
1143 ioHandler_.detachEventBase();
1144 writeTimeout_.detachEventBase();
1146 evbChangeCb_->evbDetached(this);
1150 bool AsyncSocket::isDetachable() const {
1151 DCHECK(eventBase_ != nullptr);
1152 DCHECK(eventBase_->isInEventBaseThread());
1154 return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1157 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1158 if (!localAddr_.isInitialized()) {
1159 localAddr_.setFromLocalAddress(fd_);
1161 *address = localAddr_;
1164 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1165 if (!addr_.isInitialized()) {
1166 addr_.setFromPeerAddress(fd_);
1171 bool AsyncSocket::getTFOSucceded() const {
1172 return detail::tfo_succeeded(fd_);
1175 int AsyncSocket::setNoDelay(bool noDelay) {
1177 VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1178 << this << "(state=" << state_ << ")";
1183 int value = noDelay ? 1 : 0;
1184 if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1185 int errnoCopy = errno;
1186 VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1187 << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1188 << strerror(errnoCopy);
1195 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1197 #ifndef TCP_CONGESTION
1198 #define TCP_CONGESTION 13
1202 VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1203 << "socket " << this << "(state=" << state_ << ")";
1213 socklen_t(cname.length() + 1)) != 0) {
1214 int errnoCopy = errno;
1215 VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1216 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1217 << strerror(errnoCopy);
1224 int AsyncSocket::setQuickAck(bool quickack) {
1226 VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1227 << this << "(state=" << state_ << ")";
1232 #ifdef TCP_QUICKACK // Linux-only
1233 int value = quickack ? 1 : 0;
1234 if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1235 int errnoCopy = errno;
1236 VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1237 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1238 << strerror(errnoCopy);
1248 int AsyncSocket::setSendBufSize(size_t bufsize) {
1250 VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1251 << this << "(state=" << state_ << ")";
1255 if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1256 int errnoCopy = errno;
1257 VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1258 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1259 << strerror(errnoCopy);
1266 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1268 VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1269 << this << "(state=" << state_ << ")";
1273 if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1274 int errnoCopy = errno;
1275 VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1276 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1277 << strerror(errnoCopy);
1284 int AsyncSocket::setTCPProfile(int profd) {
1286 VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1287 << this << "(state=" << state_ << ")";
1291 if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1292 int errnoCopy = errno;
1293 VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1294 << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1295 << strerror(errnoCopy);
1302 void AsyncSocket::ioReady(uint16_t events) noexcept {
1303 VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd" << fd_
1304 << ", events=" << std::hex << events << ", state=" << state_;
1305 DestructorGuard dg(this);
1306 assert(events & EventHandler::READ_WRITE);
1307 assert(eventBase_->isInEventBaseThread());
1309 uint16_t relevantEvents = events & EventHandler::READ_WRITE;
1310 if (relevantEvents == EventHandler::READ) {
1312 } else if (relevantEvents == EventHandler::WRITE) {
1314 } else if (relevantEvents == EventHandler::READ_WRITE) {
1315 EventBase* originalEventBase = eventBase_;
1316 // If both read and write events are ready, process writes first.
1319 // Return now if handleWrite() detached us from our EventBase
1320 if (eventBase_ != originalEventBase) {
1324 // Only call handleRead() if a read callback is still installed.
1325 // (It's possible that the read callback was uninstalled during
1327 if (readCallback_) {
1331 VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1332 << std::hex << events << "(this=" << this << ")";
1337 AsyncSocket::ReadResult
1338 AsyncSocket::performRead(void** buf, size_t* buflen, size_t* /* offset */) {
1339 VLOG(5) << "AsyncSocket::performRead() this=" << this << ", buf=" << *buf
1340 << ", buflen=" << *buflen;
1344 recvFlags |= MSG_PEEK;
1347 ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT | recvFlags);
1349 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1350 // No more data to read right now.
1351 return ReadResult(READ_BLOCKING);
1353 return ReadResult(READ_ERROR);
1356 appBytesReceived_ += bytes;
1357 return ReadResult(bytes);
1361 void AsyncSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1362 // no matter what, buffer should be preapared for non-ssl socket
1363 CHECK(readCallback_);
1364 readCallback_->getReadBuffer(buf, buflen);
1367 void AsyncSocket::handleRead() noexcept {
1368 VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1369 << ", state=" << state_;
1370 assert(state_ == StateEnum::ESTABLISHED);
1371 assert((shutdownFlags_ & SHUT_READ) == 0);
1372 assert(readCallback_ != nullptr);
1373 assert(eventFlags_ & EventHandler::READ);
1376 // - a read attempt would block
1377 // - readCallback_ is uninstalled
1378 // - the number of loop iterations exceeds the optional maximum
1379 // - this AsyncSocket is moved to another EventBase
1381 // When we invoke readDataAvailable() it may uninstall the readCallback_,
1382 // which is why need to check for it here.
1384 // The last bullet point is slightly subtle. readDataAvailable() may also
1385 // detach this socket from this EventBase. However, before
1386 // readDataAvailable() returns another thread may pick it up, attach it to
1387 // a different EventBase, and install another readCallback_. We need to
1388 // exit immediately after readDataAvailable() returns if the eventBase_ has
1389 // changed. (The caller must perform some sort of locking to transfer the
1390 // AsyncSocket between threads properly. This will be sufficient to ensure
1391 // that this thread sees the updated eventBase_ variable after
1392 // readDataAvailable() returns.)
1393 uint16_t numReads = 0;
1394 EventBase* originalEventBase = eventBase_;
1395 while (readCallback_ && eventBase_ == originalEventBase) {
1396 // Get the buffer to read into.
1397 void* buf = nullptr;
1398 size_t buflen = 0, offset = 0;
1400 prepareReadBuffer(&buf, &buflen);
1401 VLOG(5) << "prepareReadBuffer() buf=" << buf << ", buflen=" << buflen;
1402 } catch (const AsyncSocketException& ex) {
1403 return failRead(__func__, ex);
1404 } catch (const std::exception& ex) {
1405 AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1406 string("ReadCallback::getReadBuffer() "
1407 "threw exception: ") +
1409 return failRead(__func__, tex);
1411 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1412 "ReadCallback::getReadBuffer() threw "
1413 "non-exception type");
1414 return failRead(__func__, ex);
1416 if (!isBufferMovable_ && (buf == nullptr || buflen == 0)) {
1417 AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1418 "ReadCallback::getReadBuffer() returned "
1420 return failRead(__func__, ex);
1424 auto readResult = performRead(&buf, &buflen, &offset);
1425 auto bytesRead = readResult.readReturn;
1426 VLOG(4) << "this=" << this << ", AsyncSocket::handleRead() got "
1427 << bytesRead << " bytes";
1428 if (bytesRead > 0) {
1429 if (!isBufferMovable_) {
1430 readCallback_->readDataAvailable(bytesRead);
1432 CHECK(kOpenSslModeMoveBufferOwnership);
1433 VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
1434 << "buf=" << buf << ", " << bytesRead << "/" << buflen
1435 << ", offset=" << offset;
1436 auto readBuf = folly::IOBuf::takeOwnership(buf, buflen);
1437 readBuf->trimStart(offset);
1438 readBuf->trimEnd(buflen - offset - bytesRead);
1439 readCallback_->readBufferAvailable(std::move(readBuf));
1442 // Fall through and continue around the loop if the read
1443 // completely filled the available buffer.
1444 // Note that readCallback_ may have been uninstalled or changed inside
1445 // readDataAvailable().
1446 if (size_t(bytesRead) < buflen) {
1449 } else if (bytesRead == READ_BLOCKING) {
1450 // No more data to read right now.
1452 } else if (bytesRead == READ_ERROR) {
1453 readErr_ = READ_ERROR;
1454 if (readResult.exception) {
1455 return failRead(__func__, *readResult.exception);
1457 auto errnoCopy = errno;
1458 AsyncSocketException ex(
1459 AsyncSocketException::INTERNAL_ERROR,
1460 withAddr("recv() failed"),
1462 return failRead(__func__, ex);
1464 assert(bytesRead == READ_EOF);
1465 readErr_ = READ_EOF;
1467 shutdownFlags_ |= SHUT_READ;
1468 if (!updateEventRegistration(0, EventHandler::READ)) {
1469 // we've already been moved into STATE_ERROR
1470 assert(state_ == StateEnum::ERROR);
1471 assert(readCallback_ == nullptr);
1475 ReadCallback* callback = readCallback_;
1476 readCallback_ = nullptr;
1477 callback->readEOF();
1480 if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1481 if (readCallback_ != nullptr) {
1482 // We might still have data in the socket.
1483 // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
1484 scheduleImmediateRead();
1492 * This function attempts to write as much data as possible, until no more data
1495 * - If it sends all available data, it unregisters for write events, and stops
1496 * the writeTimeout_.
1498 * - If not all of the data can be sent immediately, it reschedules
1499 * writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1500 * registered for write events.
1502 void AsyncSocket::handleWrite() noexcept {
1503 VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1504 << ", state=" << state_;
1505 DestructorGuard dg(this);
1507 if (state_ == StateEnum::CONNECTING) {
1513 assert(state_ == StateEnum::ESTABLISHED);
1514 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1515 assert(writeReqHead_ != nullptr);
1517 // Loop until we run out of write requests,
1518 // or until this socket is moved to another EventBase.
1519 // (See the comment in handleRead() explaining how this can happen.)
1520 EventBase* originalEventBase = eventBase_;
1521 while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1522 auto writeResult = writeReqHead_->performWrite();
1523 if (writeResult.writeReturn < 0) {
1524 if (writeResult.exception) {
1525 return failWrite(__func__, *writeResult.exception);
1527 auto errnoCopy = errno;
1528 AsyncSocketException ex(
1529 AsyncSocketException::INTERNAL_ERROR,
1530 withAddr("writev() failed"),
1532 return failWrite(__func__, ex);
1533 } else if (writeReqHead_->isComplete()) {
1534 // We finished this request
1535 WriteRequest* req = writeReqHead_;
1536 writeReqHead_ = req->getNext();
1538 if (writeReqHead_ == nullptr) {
1539 writeReqTail_ = nullptr;
1540 // This is the last write request.
1541 // Unregister for write events and cancel the send timer
1542 // before we invoke the callback. We have to update the state properly
1543 // before calling the callback, since it may want to detach us from
1545 if (eventFlags_ & EventHandler::WRITE) {
1546 if (!updateEventRegistration(0, EventHandler::WRITE)) {
1547 assert(state_ == StateEnum::ERROR);
1550 // Stop the send timeout
1551 writeTimeout_.cancelTimeout();
1553 assert(!writeTimeout_.isScheduled());
1555 // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
1556 // we finish sending the last write request.
1558 // We have to do this before invoking writeSuccess(), since
1559 // writeSuccess() may detach us from our EventBase.
1560 if (shutdownFlags_ & SHUT_WRITE_PENDING) {
1561 assert(connectCallback_ == nullptr);
1562 shutdownFlags_ |= SHUT_WRITE;
1564 if (shutdownFlags_ & SHUT_READ) {
1565 // Reads have already been shutdown. Fully close the socket and
1566 // move to STATE_CLOSED.
1568 // Note: This code currently moves us to STATE_CLOSED even if
1569 // close() hasn't ever been called. This can occur if we have
1570 // received EOF from the peer and shutdownWrite() has been called
1571 // locally. Should we bother staying in STATE_ESTABLISHED in this
1572 // case, until close() is actually called? I can't think of a
1573 // reason why we would need to do so. No other operations besides
1574 // calling close() or destroying the socket can be performed at
1576 assert(readCallback_ == nullptr);
1577 state_ = StateEnum::CLOSED;
1579 ioHandler_.changeHandlerFD(-1);
1583 // Reads are still enabled, so we are only doing a half-shutdown
1584 shutdown(fd_, SHUT_WR);
1589 // Invoke the callback
1590 WriteCallback* callback = req->getCallback();
1593 callback->writeSuccess();
1595 // We'll continue around the loop, trying to write another request
1598 if (bufferCallback_) {
1599 bufferCallback_->onEgressBuffered();
1601 writeReqHead_->consume();
1602 // Stop after a partial write; it's highly likely that a subsequent write
1603 // attempt will just return EAGAIN.
1605 // Ensure that we are registered for write events.
1606 if ((eventFlags_ & EventHandler::WRITE) == 0) {
1607 if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1608 assert(state_ == StateEnum::ERROR);
1613 // Reschedule the send timeout, since we have made some write progress.
1614 if (sendTimeout_ > 0) {
1615 if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1616 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1617 withAddr("failed to reschedule write timeout"));
1618 return failWrite(__func__, ex);
1624 if (!writeReqHead_ && bufferCallback_) {
1625 bufferCallback_->onEgressBufferCleared();
1629 void AsyncSocket::checkForImmediateRead() noexcept {
1630 // We currently don't attempt to perform optimistic reads in AsyncSocket.
1631 // (However, note that some subclasses do override this method.)
1633 // Simply calling handleRead() here would be bad, as this would call
1634 // readCallback_->getReadBuffer(), forcing the callback to allocate a read
1635 // buffer even though no data may be available. This would waste lots of
1636 // memory, since the buffer will sit around unused until the socket actually
1637 // becomes readable.
1639 // Checking if the socket is readable now also seems like it would probably
1640 // be a pessimism. In most cases it probably wouldn't be readable, and we
1641 // would just waste an extra system call. Even if it is readable, waiting to
1642 // find out from libevent on the next event loop doesn't seem that bad.
1645 void AsyncSocket::handleInitialReadWrite() noexcept {
1646 // Our callers should already be holding a DestructorGuard, but grab
1647 // one here just to make sure, in case one of our calling code paths ever
1649 DestructorGuard dg(this);
1650 // If we have a readCallback_, make sure we enable read events. We
1651 // may already be registered for reads if connectSuccess() set
1652 // the read calback.
1653 if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
1654 assert(state_ == StateEnum::ESTABLISHED);
1655 assert((shutdownFlags_ & SHUT_READ) == 0);
1656 if (!updateEventRegistration(EventHandler::READ, 0)) {
1657 assert(state_ == StateEnum::ERROR);
1660 checkForImmediateRead();
1661 } else if (readCallback_ == nullptr) {
1662 // Unregister for read events.
1663 updateEventRegistration(0, EventHandler::READ);
1666 // If we have write requests pending, try to send them immediately.
1667 // Since we just finished accepting, there is a very good chance that we can
1668 // write without blocking.
1670 // However, we only process them if EventHandler::WRITE is not already set,
1671 // which means that we're already blocked on a write attempt. (This can
1672 // happen if connectSuccess() called write() before returning.)
1673 if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
1674 // Call handleWrite() to perform write processing.
1676 } else if (writeReqHead_ == nullptr) {
1677 // Unregister for write event.
1678 updateEventRegistration(0, EventHandler::WRITE);
1682 void AsyncSocket::handleConnect() noexcept {
1683 VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
1684 << ", state=" << state_;
1685 assert(state_ == StateEnum::CONNECTING);
1686 // SHUT_WRITE can never be set while we are still connecting;
1687 // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
1689 assert((shutdownFlags_ & SHUT_WRITE) == 0);
1691 // In case we had a connect timeout, cancel the timeout
1692 writeTimeout_.cancelTimeout();
1693 // We don't use a persistent registration when waiting on a connect event,
1694 // so we have been automatically unregistered now. Update eventFlags_ to
1696 assert(eventFlags_ == EventHandler::WRITE);
1697 eventFlags_ = EventHandler::NONE;
1699 // Call getsockopt() to check if the connect succeeded
1701 socklen_t len = sizeof(error);
1702 int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
1704 auto errnoCopy = errno;
1705 AsyncSocketException ex(
1706 AsyncSocketException::INTERNAL_ERROR,
1707 withAddr("error calling getsockopt() after connect"),
1709 VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1710 << fd_ << " host=" << addr_.describe()
1711 << ") exception:" << ex.what();
1712 return failConnect(__func__, ex);
1716 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
1717 "connect failed", error);
1718 VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
1719 << fd_ << " host=" << addr_.describe()
1720 << ") exception: " << ex.what();
1721 return failConnect(__func__, ex);
1724 // Move into STATE_ESTABLISHED
1725 state_ = StateEnum::ESTABLISHED;
1727 // If SHUT_WRITE_PENDING is set and we don't have any write requests to
1728 // perform, immediately shutdown the write half of the socket.
1729 if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
1730 // SHUT_READ shouldn't be set. If close() is called on the socket while we
1731 // are still connecting we just abort the connect rather than waiting for
1733 assert((shutdownFlags_ & SHUT_READ) == 0);
1734 shutdown(fd_, SHUT_WR);
1735 shutdownFlags_ |= SHUT_WRITE;
1738 VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
1739 << "successfully connected; state=" << state_;
1741 // Remember the EventBase we are attached to, before we start invoking any
1742 // callbacks (since the callbacks may call detachEventBase()).
1743 EventBase* originalEventBase = eventBase_;
1745 invokeConnectSuccess();
1746 // Note that the connect callback may have changed our state.
1747 // (set or unset the read callback, called write(), closed the socket, etc.)
1748 // The following code needs to handle these situations correctly.
1750 // If the socket has been closed, readCallback_ and writeReqHead_ will
1751 // always be nullptr, so that will prevent us from trying to read or write.
1753 // The main thing to check for is if eventBase_ is still originalEventBase.
1754 // If not, we have been detached from this event base, so we shouldn't
1755 // perform any more operations.
1756 if (eventBase_ != originalEventBase) {
1760 handleInitialReadWrite();
1763 void AsyncSocket::timeoutExpired() noexcept {
1764 VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
1765 << "state=" << state_ << ", events=" << std::hex << eventFlags_;
1766 DestructorGuard dg(this);
1767 assert(eventBase_->isInEventBaseThread());
1769 if (state_ == StateEnum::CONNECTING) {
1770 // connect() timed out
1771 // Unregister for I/O events.
1772 if (connectCallback_) {
1773 AsyncSocketException ex(
1774 AsyncSocketException::TIMED_OUT, "connect timed out");
1775 failConnect(__func__, ex);
1777 // we faced a connect error without a connect callback, which could
1778 // happen due to TFO.
1779 AsyncSocketException ex(
1780 AsyncSocketException::TIMED_OUT, "write timed out during connection");
1781 failWrite(__func__, ex);
1784 // a normal write operation timed out
1785 AsyncSocketException ex(AsyncSocketException::TIMED_OUT, "write timed out");
1786 failWrite(__func__, ex);
1790 ssize_t AsyncSocket::tfoSendMsg(int fd, struct msghdr* msg, int msg_flags) {
1791 return detail::tfo_sendmsg(fd, msg, msg_flags);
1794 AsyncSocket::WriteResult
1795 AsyncSocket::sendSocketMessage(int fd, struct msghdr* msg, int msg_flags) {
1796 ssize_t totalWritten = 0;
1797 if (state_ == StateEnum::FAST_OPEN) {
1798 sockaddr_storage addr;
1799 auto len = addr_.getAddress(&addr);
1800 msg->msg_name = &addr;
1801 msg->msg_namelen = len;
1802 totalWritten = tfoSendMsg(fd_, msg, msg_flags);
1803 if (totalWritten >= 0) {
1804 tfoFinished_ = true;
1805 state_ = StateEnum::ESTABLISHED;
1806 // We schedule this asynchrously so that we don't end up
1807 // invoking initial read or write while a write is in progress.
1808 scheduleInitialReadWrite();
1809 } else if (errno == EINPROGRESS) {
1810 VLOG(4) << "TFO falling back to connecting";
1811 // A normal sendmsg doesn't return EINPROGRESS, however
1812 // TFO might fallback to connecting if there is no
1814 state_ = StateEnum::CONNECTING;
1816 scheduleConnectTimeout();
1817 registerForConnectEvents();
1818 } catch (const AsyncSocketException& ex) {
1820 WRITE_ERROR, folly::make_unique<AsyncSocketException>(ex));
1822 // Let's fake it that no bytes were written and return an errno.
1825 } else if (errno == EOPNOTSUPP) {
1826 // Try falling back to connecting.
1827 VLOG(4) << "TFO not supported";
1828 state_ = StateEnum::CONNECTING;
1830 int ret = socketConnect((const sockaddr*)&addr, len);
1832 // connect succeeded immediately
1833 // Treat this like no data was written.
1834 state_ = StateEnum::ESTABLISHED;
1835 scheduleInitialReadWrite();
1837 // If there was no exception during connections,
1838 // we would return that no bytes were written.
1841 } catch (const AsyncSocketException& ex) {
1843 WRITE_ERROR, folly::make_unique<AsyncSocketException>(ex));
1845 } else if (errno == EAGAIN) {
1846 // Normally sendmsg would indicate that the write would block.
1847 // However in the fast open case, it would indicate that sendmsg
1848 // fell back to a connect. This is a return code from connect()
1849 // instead, and is an error condition indicating no fds available.
1852 folly::make_unique<AsyncSocketException>(
1853 AsyncSocketException::UNKNOWN, "No more free local ports"));
1856 totalWritten = ::sendmsg(fd, msg, msg_flags);
1858 return WriteResult(totalWritten);
1861 AsyncSocket::WriteResult AsyncSocket::performWrite(
1865 uint32_t* countWritten,
1866 uint32_t* partialWritten) {
1867 // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
1868 // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
1869 // (since it may terminate the program if the main program doesn't explicitly
1872 msg.msg_name = nullptr;
1873 msg.msg_namelen = 0;
1874 msg.msg_iov = const_cast<iovec *>(vec);
1875 msg.msg_iovlen = std::min<size_t>(count, kIovMax);
1876 msg.msg_control = nullptr;
1877 msg.msg_controllen = 0;
1880 int msg_flags = MSG_DONTWAIT;
1882 #ifdef MSG_NOSIGNAL // Linux-only
1883 msg_flags |= MSG_NOSIGNAL;
1884 if (isSet(flags, WriteFlags::CORK)) {
1885 // MSG_MORE tells the kernel we have more data to send, so wait for us to
1886 // give it the rest of the data rather than immediately sending a partial
1887 // frame, even when TCP_NODELAY is enabled.
1888 msg_flags |= MSG_MORE;
1891 if (isSet(flags, WriteFlags::EOR)) {
1892 // marks that this is the last byte of a record (response)
1893 msg_flags |= MSG_EOR;
1895 auto writeResult = sendSocketMessage(fd_, &msg, msg_flags);
1896 auto totalWritten = writeResult.writeReturn;
1897 if (totalWritten < 0) {
1898 bool tryAgain = (errno == EAGAIN);
1900 // Apple has a bug where doing a second write on a socket which we
1901 // have opened with TFO causes an ENOTCONN to be thrown. However the
1902 // socket is really connected, so treat ENOTCONN as a EAGAIN until
1903 // this bug is fixed.
1904 tryAgain |= (errno == ENOTCONN);
1906 if (!writeResult.exception && tryAgain) {
1907 // TCP buffer is full; we can't write any more data right now.
1909 *partialWritten = 0;
1910 return WriteResult(0);
1914 *partialWritten = 0;
1918 appBytesWritten_ += totalWritten;
1920 uint32_t bytesWritten;
1922 for (bytesWritten = uint32_t(totalWritten), n = 0; n < count; ++n) {
1923 const iovec* v = vec + n;
1924 if (v->iov_len > bytesWritten) {
1925 // Partial write finished in the middle of this iovec
1927 *partialWritten = bytesWritten;
1928 return WriteResult(totalWritten);
1931 bytesWritten -= uint32_t(v->iov_len);
1934 assert(bytesWritten == 0);
1936 *partialWritten = 0;
1937 return WriteResult(totalWritten);
1941 * Re-register the EventHandler after eventFlags_ has changed.
1943 * If an error occurs, fail() is called to move the socket into the error state
1944 * and call all currently installed callbacks. After an error, the
1945 * AsyncSocket is completely unregistered.
1947 * @return Returns true on succcess, or false on error.
1949 bool AsyncSocket::updateEventRegistration() {
1950 VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
1951 << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
1952 << ", events=" << std::hex << eventFlags_;
1953 assert(eventBase_->isInEventBaseThread());
1954 if (eventFlags_ == EventHandler::NONE) {
1955 ioHandler_.unregisterHandler();
1959 // Always register for persistent events, so we don't have to re-register
1960 // after being called back.
1961 if (!ioHandler_.registerHandler(eventFlags_ | EventHandler::PERSIST)) {
1962 eventFlags_ = EventHandler::NONE; // we're not registered after error
1963 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1964 withAddr("failed to update AsyncSocket event registration"));
1965 fail("updateEventRegistration", ex);
1972 bool AsyncSocket::updateEventRegistration(uint16_t enable,
1974 uint16_t oldFlags = eventFlags_;
1975 eventFlags_ |= enable;
1976 eventFlags_ &= ~disable;
1977 if (eventFlags_ == oldFlags) {
1980 return updateEventRegistration();
1984 void AsyncSocket::startFail() {
1985 // startFail() should only be called once
1986 assert(state_ != StateEnum::ERROR);
1987 assert(getDestructorGuardCount() > 0);
1988 state_ = StateEnum::ERROR;
1989 // Ensure that SHUT_READ and SHUT_WRITE are set,
1990 // so all future attempts to read or write will be rejected
1991 shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1993 if (eventFlags_ != EventHandler::NONE) {
1994 eventFlags_ = EventHandler::NONE;
1995 ioHandler_.unregisterHandler();
1997 writeTimeout_.cancelTimeout();
2000 ioHandler_.changeHandlerFD(-1);
2005 void AsyncSocket::invokeAllErrors(const AsyncSocketException& ex) {
2006 invokeConnectErr(ex);
2009 if (readCallback_) {
2010 ReadCallback* callback = readCallback_;
2011 readCallback_ = nullptr;
2012 callback->readErr(ex);
2016 void AsyncSocket::finishFail() {
2017 assert(state_ == StateEnum::ERROR);
2018 assert(getDestructorGuardCount() > 0);
2020 AsyncSocketException ex(
2021 AsyncSocketException::INTERNAL_ERROR,
2022 withAddr("socket closing after error"));
2023 invokeAllErrors(ex);
2026 void AsyncSocket::finishFail(const AsyncSocketException& ex) {
2027 assert(state_ == StateEnum::ERROR);
2028 assert(getDestructorGuardCount() > 0);
2029 invokeAllErrors(ex);
2032 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
2033 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2034 << state_ << " host=" << addr_.describe()
2035 << "): failed in " << fn << "(): "
2041 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
2042 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2043 << state_ << " host=" << addr_.describe()
2044 << "): failed while connecting in " << fn << "(): "
2048 invokeConnectErr(ex);
2052 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
2053 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2054 << state_ << " host=" << addr_.describe()
2055 << "): failed while reading in " << fn << "(): "
2059 if (readCallback_ != nullptr) {
2060 ReadCallback* callback = readCallback_;
2061 readCallback_ = nullptr;
2062 callback->readErr(ex);
2068 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
2069 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2070 << state_ << " host=" << addr_.describe()
2071 << "): failed while writing in " << fn << "(): "
2075 // Only invoke the first write callback, since the error occurred while
2076 // writing this request. Let any other pending write callbacks be invoked in
2078 if (writeReqHead_ != nullptr) {
2079 WriteRequest* req = writeReqHead_;
2080 writeReqHead_ = req->getNext();
2081 WriteCallback* callback = req->getCallback();
2082 uint32_t bytesWritten = req->getTotalBytesWritten();
2085 callback->writeErr(bytesWritten, ex);
2092 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
2093 size_t bytesWritten,
2094 const AsyncSocketException& ex) {
2095 // This version of failWrite() is used when the failure occurs before
2096 // we've added the callback to writeReqHead_.
2097 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2098 << state_ << " host=" << addr_.describe()
2099 <<"): failed while writing in " << fn << "(): "
2103 if (callback != nullptr) {
2104 callback->writeErr(bytesWritten, ex);
2110 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
2111 // Invoke writeError() on all write callbacks.
2112 // This is used when writes are forcibly shutdown with write requests
2113 // pending, or when an error occurs with writes pending.
2114 while (writeReqHead_ != nullptr) {
2115 WriteRequest* req = writeReqHead_;
2116 writeReqHead_ = req->getNext();
2117 WriteCallback* callback = req->getCallback();
2119 callback->writeErr(req->getTotalBytesWritten(), ex);
2125 void AsyncSocket::invalidState(ConnectCallback* callback) {
2126 VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2127 << "): connect() called in invalid state " << state_;
2130 * The invalidState() methods don't use the normal failure mechanisms,
2131 * since we don't know what state we are in. We don't want to call
2132 * startFail()/finishFail() recursively if we are already in the middle of
2136 AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
2137 "connect() called with socket in invalid state");
2138 connectEndTime_ = std::chrono::steady_clock::now();
2139 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2141 callback->connectErr(ex);
2144 // We can't use failConnect() here since connectCallback_
2145 // may already be set to another callback. Invoke this ConnectCallback
2146 // here; any other connectCallback_ will be invoked in finishFail()
2149 callback->connectErr(ex);
2155 void AsyncSocket::invokeConnectErr(const AsyncSocketException& ex) {
2156 connectEndTime_ = std::chrono::steady_clock::now();
2157 if (connectCallback_) {
2158 ConnectCallback* callback = connectCallback_;
2159 connectCallback_ = nullptr;
2160 callback->connectErr(ex);
2164 void AsyncSocket::invokeConnectSuccess() {
2165 connectEndTime_ = std::chrono::steady_clock::now();
2166 if (connectCallback_) {
2167 ConnectCallback* callback = connectCallback_;
2168 connectCallback_ = nullptr;
2169 callback->connectSuccess();
2173 void AsyncSocket::invalidState(ReadCallback* callback) {
2174 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2175 << "): setReadCallback(" << callback
2176 << ") called in invalid state " << state_;
2178 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2179 "setReadCallback() called with socket in "
2181 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2183 callback->readErr(ex);
2188 callback->readErr(ex);
2194 void AsyncSocket::invalidState(WriteCallback* callback) {
2195 VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2196 << "): write() called in invalid state " << state_;
2198 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2199 withAddr("write() called with socket in invalid state"));
2200 if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2202 callback->writeErr(0, ex);
2207 callback->writeErr(0, ex);
2213 void AsyncSocket::doClose() {
2214 if (fd_ == -1) return;
2215 if (shutdownSocketSet_) {
2216 shutdownSocketSet_->close(fd_);
2223 std::ostream& operator << (std::ostream& os,
2224 const AsyncSocket::StateEnum& state) {
2225 os << static_cast<int>(state);
2229 std::string AsyncSocket::withAddr(const std::string& s) {
2230 // Don't use addr_ directly because it may not be initialized
2231 // e.g. if constructed from fd
2232 folly::SocketAddress peer, local;
2234 getPeerAddress(&peer);
2235 getLocalAddress(&local);
2236 } catch (const std::exception&) {
2241 return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";
2244 void AsyncSocket::setBufferCallback(BufferCallback* cb) {
2245 bufferCallback_ = cb;