Expose the zerocopy buf ID, change the AsyncSocket fd constructor to accept the id...
[folly.git] / folly / io / async / AsyncSocket.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <folly/io/async/AsyncSocket.h>
18
19 #include <folly/ExceptionWrapper.h>
20 #include <folly/Format.h>
21 #include <folly/Portability.h>
22 #include <folly/SocketAddress.h>
23 #include <folly/io/Cursor.h>
24 #include <folly/io/IOBuf.h>
25 #include <folly/io/IOBufQueue.h>
26 #include <folly/portability/Fcntl.h>
27 #include <folly/portability/Sockets.h>
28 #include <folly/portability/SysUio.h>
29 #include <folly/portability/Unistd.h>
30
31 #include <boost/preprocessor/control/if.hpp>
32 #include <errno.h>
33 #include <limits.h>
34 #include <sys/types.h>
35 #include <thread>
36
37 using std::string;
38 using std::unique_ptr;
39
40 namespace fsp = folly::portability::sockets;
41
42 namespace folly {
43
44 static constexpr bool msgErrQueueSupported =
45 #ifdef FOLLY_HAVE_MSG_ERRQUEUE
46     true;
47 #else
48     false;
49 #endif // FOLLY_HAVE_MSG_ERRQUEUE
50
51 // static members initializers
52 const AsyncSocket::OptionMap AsyncSocket::emptyOptionMap;
53
54 const AsyncSocketException socketClosedLocallyEx(
55     AsyncSocketException::END_OF_FILE, "socket closed locally");
56 const AsyncSocketException socketShutdownForWritesEx(
57     AsyncSocketException::END_OF_FILE, "socket shutdown for writes");
58
59 // TODO: It might help performance to provide a version of BytesWriteRequest that
60 // users could derive from, so we can avoid the extra allocation for each call
61 // to write()/writev().  We could templatize TFramedAsyncChannel just like the
62 // protocols are currently templatized for transports.
63 //
64 // We would need the version for external users where they provide the iovec
65 // storage space, and only our internal version would allocate it at the end of
66 // the WriteRequest.
67
68 /* The default WriteRequest implementation, used for write(), writev() and
69  * writeChain()
70  *
71  * A new BytesWriteRequest operation is allocated on the heap for all write
72  * operations that cannot be completed immediately.
73  */
74 class AsyncSocket::BytesWriteRequest : public AsyncSocket::WriteRequest {
75  public:
76   static BytesWriteRequest* newRequest(AsyncSocket* socket,
77                                        WriteCallback* callback,
78                                        const iovec* ops,
79                                        uint32_t opCount,
80                                        uint32_t partialWritten,
81                                        uint32_t bytesWritten,
82                                        unique_ptr<IOBuf>&& ioBuf,
83                                        WriteFlags flags) {
84     assert(opCount > 0);
85     // Since we put a variable size iovec array at the end
86     // of each BytesWriteRequest, we have to manually allocate the memory.
87     void* buf = malloc(sizeof(BytesWriteRequest) +
88                        (opCount * sizeof(struct iovec)));
89     if (buf == nullptr) {
90       throw std::bad_alloc();
91     }
92
93     return new(buf) BytesWriteRequest(socket, callback, ops, opCount,
94                                       partialWritten, bytesWritten,
95                                       std::move(ioBuf), flags);
96   }
97
98   void destroy() override {
99     this->~BytesWriteRequest();
100     free(this);
101   }
102
103   WriteResult performWrite() override {
104     WriteFlags writeFlags = flags_;
105     if (getNext() != nullptr) {
106       writeFlags |= WriteFlags::CORK;
107     }
108
109     socket_->adjustZeroCopyFlags(getOps(), getOpCount(), writeFlags);
110
111     auto writeResult = socket_->performWrite(
112         getOps(), getOpCount(), writeFlags, &opsWritten_, &partialBytes_);
113     bytesWritten_ = writeResult.writeReturn > 0 ? writeResult.writeReturn : 0;
114     if (bytesWritten_) {
115       if (socket_->isZeroCopyRequest(writeFlags)) {
116         if (isComplete()) {
117           socket_->addZeroCopyBuf(std::move(ioBuf_));
118         } else {
119           socket_->addZeroCopyBuf(ioBuf_.get());
120         }
121       } else {
122         // this happens if at least one of the prev requests were sent
123         // with zero copy but not the last one
124         if (isComplete() && socket_->getZeroCopy() &&
125             socket_->containsZeroCopyBuf(ioBuf_.get())) {
126           socket_->setZeroCopyBuf(std::move(ioBuf_));
127         }
128       }
129     }
130     return writeResult;
131   }
132
133   bool isComplete() override {
134     return opsWritten_ == getOpCount();
135   }
136
137   void consume() override {
138     // Advance opIndex_ forward by opsWritten_
139     opIndex_ += opsWritten_;
140     assert(opIndex_ < opCount_);
141
142     if (!socket_->isZeroCopyRequest(flags_)) {
143       // If we've finished writing any IOBufs, release them
144       if (ioBuf_) {
145         for (uint32_t i = opsWritten_; i != 0; --i) {
146           assert(ioBuf_);
147           ioBuf_ = ioBuf_->pop();
148         }
149       }
150     }
151
152     // Move partialBytes_ forward into the current iovec buffer
153     struct iovec* currentOp = writeOps_ + opIndex_;
154     assert((partialBytes_ < currentOp->iov_len) || (currentOp->iov_len == 0));
155     currentOp->iov_base =
156       reinterpret_cast<uint8_t*>(currentOp->iov_base) + partialBytes_;
157     currentOp->iov_len -= partialBytes_;
158
159     // Increment the totalBytesWritten_ count by bytesWritten_;
160     assert(bytesWritten_ >= 0);
161     totalBytesWritten_ += uint32_t(bytesWritten_);
162   }
163
164  private:
165   BytesWriteRequest(AsyncSocket* socket,
166                     WriteCallback* callback,
167                     const struct iovec* ops,
168                     uint32_t opCount,
169                     uint32_t partialBytes,
170                     uint32_t bytesWritten,
171                     unique_ptr<IOBuf>&& ioBuf,
172                     WriteFlags flags)
173     : AsyncSocket::WriteRequest(socket, callback)
174     , opCount_(opCount)
175     , opIndex_(0)
176     , flags_(flags)
177     , ioBuf_(std::move(ioBuf))
178     , opsWritten_(0)
179     , partialBytes_(partialBytes)
180     , bytesWritten_(bytesWritten) {
181     memcpy(writeOps_, ops, sizeof(*ops) * opCount_);
182   }
183
184   // private destructor, to ensure callers use destroy()
185   ~BytesWriteRequest() override = default;
186
187   const struct iovec* getOps() const {
188     assert(opCount_ > opIndex_);
189     return writeOps_ + opIndex_;
190   }
191
192   uint32_t getOpCount() const {
193     assert(opCount_ > opIndex_);
194     return opCount_ - opIndex_;
195   }
196
197   uint32_t opCount_;            ///< number of entries in writeOps_
198   uint32_t opIndex_;            ///< current index into writeOps_
199   WriteFlags flags_;            ///< set for WriteFlags
200   unique_ptr<IOBuf> ioBuf_;     ///< underlying IOBuf, or nullptr if N/A
201
202   // for consume(), how much we wrote on the last write
203   uint32_t opsWritten_;         ///< complete ops written
204   uint32_t partialBytes_;       ///< partial bytes of incomplete op written
205   ssize_t bytesWritten_;        ///< bytes written altogether
206
207   struct iovec writeOps_[];     ///< write operation(s) list
208 };
209
210 int AsyncSocket::SendMsgParamsCallback::getDefaultFlags(
211     folly::WriteFlags flags,
212     bool zeroCopyEnabled) noexcept {
213   int msg_flags = MSG_DONTWAIT;
214
215 #ifdef MSG_NOSIGNAL // Linux-only
216   msg_flags |= MSG_NOSIGNAL;
217 #ifdef MSG_MORE
218   if (isSet(flags, WriteFlags::CORK)) {
219     // MSG_MORE tells the kernel we have more data to send, so wait for us to
220     // give it the rest of the data rather than immediately sending a partial
221     // frame, even when TCP_NODELAY is enabled.
222     msg_flags |= MSG_MORE;
223   }
224 #endif // MSG_MORE
225 #endif // MSG_NOSIGNAL
226   if (isSet(flags, WriteFlags::EOR)) {
227     // marks that this is the last byte of a record (response)
228     msg_flags |= MSG_EOR;
229   }
230
231   if (zeroCopyEnabled && isSet(flags, WriteFlags::WRITE_MSG_ZEROCOPY)) {
232     msg_flags |= MSG_ZEROCOPY;
233   }
234
235   return msg_flags;
236 }
237
238 namespace {
239 static AsyncSocket::SendMsgParamsCallback defaultSendMsgParamsCallback;
240 } // namespace
241
242 AsyncSocket::AsyncSocket()
243     : eventBase_(nullptr),
244       writeTimeout_(this, nullptr),
245       ioHandler_(this, nullptr),
246       immediateReadHandler_(this) {
247   VLOG(5) << "new AsyncSocket()";
248   init();
249 }
250
251 AsyncSocket::AsyncSocket(EventBase* evb)
252     : eventBase_(evb),
253       writeTimeout_(this, evb),
254       ioHandler_(this, evb),
255       immediateReadHandler_(this) {
256   VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ")";
257   init();
258 }
259
260 AsyncSocket::AsyncSocket(EventBase* evb,
261                            const folly::SocketAddress& address,
262                            uint32_t connectTimeout)
263   : AsyncSocket(evb) {
264   connect(nullptr, address, connectTimeout);
265 }
266
267 AsyncSocket::AsyncSocket(EventBase* evb,
268                            const std::string& ip,
269                            uint16_t port,
270                            uint32_t connectTimeout)
271   : AsyncSocket(evb) {
272   connect(nullptr, ip, port, connectTimeout);
273 }
274
275 AsyncSocket::AsyncSocket(EventBase* evb, int fd, uint32_t zeroCopyBufId)
276     : zeroCopyBufId_(zeroCopyBufId),
277       eventBase_(evb),
278       writeTimeout_(this, evb),
279       ioHandler_(this, evb, fd),
280       immediateReadHandler_(this) {
281   VLOG(5) << "new AsyncSocket(" << this << ", evb=" << evb << ", fd=" << fd
282           << ", zeroCopyBufId=" << zeroCopyBufId << ")";
283   init();
284   fd_ = fd;
285   setCloseOnExec();
286   state_ = StateEnum::ESTABLISHED;
287 }
288
289 AsyncSocket::AsyncSocket(AsyncSocket::UniquePtr oldAsyncSocket)
290     : AsyncSocket(
291           oldAsyncSocket->getEventBase(),
292           oldAsyncSocket->detachFd(),
293           oldAsyncSocket->getZeroCopyBufId()) {
294   preReceivedData_ = std::move(oldAsyncSocket->preReceivedData_);
295 }
296
297 // init() method, since constructor forwarding isn't supported in most
298 // compilers yet.
299 void AsyncSocket::init() {
300   if (eventBase_) {
301     eventBase_->dcheckIsInEventBaseThread();
302   }
303   shutdownFlags_ = 0;
304   state_ = StateEnum::UNINIT;
305   eventFlags_ = EventHandler::NONE;
306   fd_ = -1;
307   sendTimeout_ = 0;
308   maxReadsPerEvent_ = 16;
309   connectCallback_ = nullptr;
310   errMessageCallback_ = nullptr;
311   readCallback_ = nullptr;
312   writeReqHead_ = nullptr;
313   writeReqTail_ = nullptr;
314   wShutdownSocketSet_.reset();
315   appBytesWritten_ = 0;
316   appBytesReceived_ = 0;
317   sendMsgParamCallback_ = &defaultSendMsgParamsCallback;
318 }
319
320 AsyncSocket::~AsyncSocket() {
321   VLOG(7) << "actual destruction of AsyncSocket(this=" << this
322           << ", evb=" << eventBase_ << ", fd=" << fd_
323           << ", state=" << state_ << ")";
324 }
325
326 void AsyncSocket::destroy() {
327   VLOG(5) << "AsyncSocket::destroy(this=" << this << ", evb=" << eventBase_
328           << ", fd=" << fd_ << ", state=" << state_;
329   // When destroy is called, close the socket immediately
330   closeNow();
331
332   // Then call DelayedDestruction::destroy() to take care of
333   // whether or not we need immediate or delayed destruction
334   DelayedDestruction::destroy();
335 }
336
337 int AsyncSocket::detachFd() {
338   VLOG(6) << "AsyncSocket::detachFd(this=" << this << ", fd=" << fd_
339           << ", evb=" << eventBase_ << ", state=" << state_
340           << ", events=" << std::hex << eventFlags_ << ")";
341   // Extract the fd, and set fd_ to -1 first, so closeNow() won't
342   // actually close the descriptor.
343   if (const auto socketSet = wShutdownSocketSet_.lock()) {
344     socketSet->remove(fd_);
345   }
346   int fd = fd_;
347   fd_ = -1;
348   // Call closeNow() to invoke all pending callbacks with an error.
349   closeNow();
350   // Update the EventHandler to stop using this fd.
351   // This can only be done after closeNow() unregisters the handler.
352   ioHandler_.changeHandlerFD(-1);
353   return fd;
354 }
355
356 const folly::SocketAddress& AsyncSocket::anyAddress() {
357   static const folly::SocketAddress anyAddress =
358     folly::SocketAddress("0.0.0.0", 0);
359   return anyAddress;
360 }
361
362 void AsyncSocket::setShutdownSocketSet(
363     const std::weak_ptr<ShutdownSocketSet>& wNewSS) {
364   const auto newSS = wNewSS.lock();
365   const auto shutdownSocketSet = wShutdownSocketSet_.lock();
366
367   if (newSS == shutdownSocketSet) {
368     return;
369   }
370
371   if (shutdownSocketSet && fd_ != -1) {
372     shutdownSocketSet->remove(fd_);
373   }
374
375   if (newSS && fd_ != -1) {
376     newSS->add(fd_);
377   }
378
379   wShutdownSocketSet_ = wNewSS;
380 }
381
382 void AsyncSocket::setCloseOnExec() {
383   int rv = fcntl(fd_, F_SETFD, FD_CLOEXEC);
384   if (rv != 0) {
385     auto errnoCopy = errno;
386     throw AsyncSocketException(
387         AsyncSocketException::INTERNAL_ERROR,
388         withAddr("failed to set close-on-exec flag"),
389         errnoCopy);
390   }
391 }
392
393 void AsyncSocket::connect(ConnectCallback* callback,
394                            const folly::SocketAddress& address,
395                            int timeout,
396                            const OptionMap &options,
397                            const folly::SocketAddress& bindAddr) noexcept {
398   DestructorGuard dg(this);
399   eventBase_->dcheckIsInEventBaseThread();
400
401   addr_ = address;
402
403   // Make sure we're in the uninitialized state
404   if (state_ != StateEnum::UNINIT) {
405     return invalidState(callback);
406   }
407
408   connectTimeout_ = std::chrono::milliseconds(timeout);
409   connectStartTime_ = std::chrono::steady_clock::now();
410   // Make connect end time at least >= connectStartTime.
411   connectEndTime_ = connectStartTime_;
412
413   assert(fd_ == -1);
414   state_ = StateEnum::CONNECTING;
415   connectCallback_ = callback;
416
417   sockaddr_storage addrStorage;
418   sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
419
420   try {
421     // Create the socket
422     // Technically the first parameter should actually be a protocol family
423     // constant (PF_xxx) rather than an address family (AF_xxx), but the
424     // distinction is mainly just historical.  In pretty much all
425     // implementations the PF_foo and AF_foo constants are identical.
426     fd_ = fsp::socket(address.getFamily(), SOCK_STREAM, 0);
427     if (fd_ < 0) {
428       auto errnoCopy = errno;
429       throw AsyncSocketException(
430           AsyncSocketException::INTERNAL_ERROR,
431           withAddr("failed to create socket"),
432           errnoCopy);
433     }
434     if (const auto shutdownSocketSet = wShutdownSocketSet_.lock()) {
435       shutdownSocketSet->add(fd_);
436     }
437     ioHandler_.changeHandlerFD(fd_);
438
439     setCloseOnExec();
440
441     // Put the socket in non-blocking mode
442     int flags = fcntl(fd_, F_GETFL, 0);
443     if (flags == -1) {
444       auto errnoCopy = errno;
445       throw AsyncSocketException(
446           AsyncSocketException::INTERNAL_ERROR,
447           withAddr("failed to get socket flags"),
448           errnoCopy);
449     }
450     int rv = fcntl(fd_, F_SETFL, flags | O_NONBLOCK);
451     if (rv == -1) {
452       auto errnoCopy = errno;
453       throw AsyncSocketException(
454           AsyncSocketException::INTERNAL_ERROR,
455           withAddr("failed to put socket in non-blocking mode"),
456           errnoCopy);
457     }
458
459 #if !defined(MSG_NOSIGNAL) && defined(F_SETNOSIGPIPE)
460     // iOS and OS X don't support MSG_NOSIGNAL; set F_SETNOSIGPIPE instead
461     rv = fcntl(fd_, F_SETNOSIGPIPE, 1);
462     if (rv == -1) {
463       auto errnoCopy = errno;
464       throw AsyncSocketException(
465           AsyncSocketException::INTERNAL_ERROR,
466           "failed to enable F_SETNOSIGPIPE on socket",
467           errnoCopy);
468     }
469 #endif
470
471     // By default, turn on TCP_NODELAY
472     // If setNoDelay() fails, we continue anyway; this isn't a fatal error.
473     // setNoDelay() will log an error message if it fails.
474     // Also set the cached zeroCopyVal_ since it cannot be set earlier if the fd
475     // is not created
476     if (address.getFamily() != AF_UNIX) {
477       (void)setNoDelay(true);
478       setZeroCopy(zeroCopyVal_);
479     }
480
481     VLOG(5) << "AsyncSocket::connect(this=" << this << ", evb=" << eventBase_
482             << ", fd=" << fd_ << ", host=" << address.describe().c_str();
483
484     // bind the socket
485     if (bindAddr != anyAddress()) {
486       int one = 1;
487       if (setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
488         auto errnoCopy = errno;
489         doClose();
490         throw AsyncSocketException(
491             AsyncSocketException::NOT_OPEN,
492             "failed to setsockopt prior to bind on " + bindAddr.describe(),
493             errnoCopy);
494       }
495
496       bindAddr.getAddress(&addrStorage);
497
498       if (bind(fd_, saddr, bindAddr.getActualSize()) != 0) {
499         auto errnoCopy = errno;
500         doClose();
501         throw AsyncSocketException(
502             AsyncSocketException::NOT_OPEN,
503             "failed to bind to async socket: " + bindAddr.describe(),
504             errnoCopy);
505       }
506     }
507
508     // Apply the additional options if any.
509     for (const auto& opt: options) {
510       rv = opt.first.apply(fd_, opt.second);
511       if (rv != 0) {
512         auto errnoCopy = errno;
513         throw AsyncSocketException(
514             AsyncSocketException::INTERNAL_ERROR,
515             withAddr("failed to set socket option"),
516             errnoCopy);
517       }
518     }
519
520     // Perform the connect()
521     address.getAddress(&addrStorage);
522
523     if (tfoEnabled_) {
524       state_ = StateEnum::FAST_OPEN;
525       tfoAttempted_ = true;
526     } else {
527       if (socketConnect(saddr, addr_.getActualSize()) < 0) {
528         return;
529       }
530     }
531
532     // If we're still here the connect() succeeded immediately.
533     // Fall through to call the callback outside of this try...catch block
534   } catch (const AsyncSocketException& ex) {
535     return failConnect(__func__, ex);
536   } catch (const std::exception& ex) {
537     // shouldn't happen, but handle it just in case
538     VLOG(4) << "AsyncSocket::connect(this=" << this << ", fd=" << fd_
539                << "): unexpected " << typeid(ex).name() << " exception: "
540                << ex.what();
541     AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
542                             withAddr(string("unexpected exception: ") +
543                                      ex.what()));
544     return failConnect(__func__, tex);
545   }
546
547   // The connection succeeded immediately
548   // The read callback may not have been set yet, and no writes may be pending
549   // yet, so we don't have to register for any events at the moment.
550   VLOG(8) << "AsyncSocket::connect succeeded immediately; this=" << this;
551   assert(errMessageCallback_ == nullptr);
552   assert(readCallback_ == nullptr);
553   assert(writeReqHead_ == nullptr);
554   if (state_ != StateEnum::FAST_OPEN) {
555     state_ = StateEnum::ESTABLISHED;
556   }
557   invokeConnectSuccess();
558 }
559
560 int AsyncSocket::socketConnect(const struct sockaddr* saddr, socklen_t len) {
561 #if __linux__
562   if (noTransparentTls_) {
563     // Ignore return value, errors are ok
564     setsockopt(fd_, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0);
565   }
566   if (noTSocks_) {
567     VLOG(4) << "Disabling TSOCKS for fd " << fd_;
568     // Ignore return value, errors are ok
569     setsockopt(fd_, SOL_SOCKET, SO_NO_TSOCKS, nullptr, 0);
570   }
571 #endif
572   int rv = fsp::connect(fd_, saddr, len);
573   if (rv < 0) {
574     auto errnoCopy = errno;
575     if (errnoCopy == EINPROGRESS) {
576       scheduleConnectTimeout();
577       registerForConnectEvents();
578     } else {
579       throw AsyncSocketException(
580           AsyncSocketException::NOT_OPEN,
581           "connect failed (immediately)",
582           errnoCopy);
583     }
584   }
585   return rv;
586 }
587
588 void AsyncSocket::scheduleConnectTimeout() {
589   // Connection in progress.
590   auto timeout = connectTimeout_.count();
591   if (timeout > 0) {
592     // Start a timer in case the connection takes too long.
593     if (!writeTimeout_.scheduleTimeout(uint32_t(timeout))) {
594       throw AsyncSocketException(
595           AsyncSocketException::INTERNAL_ERROR,
596           withAddr("failed to schedule AsyncSocket connect timeout"));
597     }
598   }
599 }
600
601 void AsyncSocket::registerForConnectEvents() {
602   // Register for write events, so we'll
603   // be notified when the connection finishes/fails.
604   // Note that we don't register for a persistent event here.
605   assert(eventFlags_ == EventHandler::NONE);
606   eventFlags_ = EventHandler::WRITE;
607   if (!ioHandler_.registerHandler(eventFlags_)) {
608     throw AsyncSocketException(
609         AsyncSocketException::INTERNAL_ERROR,
610         withAddr("failed to register AsyncSocket connect handler"));
611   }
612 }
613
614 void AsyncSocket::connect(ConnectCallback* callback,
615                            const string& ip, uint16_t port,
616                            int timeout,
617                            const OptionMap &options) noexcept {
618   DestructorGuard dg(this);
619   try {
620     connectCallback_ = callback;
621     connect(callback, folly::SocketAddress(ip, port), timeout, options);
622   } catch (const std::exception& ex) {
623     AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
624                             ex.what());
625     return failConnect(__func__, tex);
626   }
627 }
628
629 void AsyncSocket::cancelConnect() {
630   connectCallback_ = nullptr;
631   if (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN) {
632     closeNow();
633   }
634 }
635
636 void AsyncSocket::setSendTimeout(uint32_t milliseconds) {
637   sendTimeout_ = milliseconds;
638   if (eventBase_) {
639     eventBase_->dcheckIsInEventBaseThread();
640   }
641
642   // If we are currently pending on write requests, immediately update
643   // writeTimeout_ with the new value.
644   if ((eventFlags_ & EventHandler::WRITE) &&
645       (state_ != StateEnum::CONNECTING && state_ != StateEnum::FAST_OPEN)) {
646     assert(state_ == StateEnum::ESTABLISHED);
647     assert((shutdownFlags_ & SHUT_WRITE) == 0);
648     if (sendTimeout_ > 0) {
649       if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
650         AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
651             withAddr("failed to reschedule send timeout in setSendTimeout"));
652         return failWrite(__func__, ex);
653       }
654     } else {
655       writeTimeout_.cancelTimeout();
656     }
657   }
658 }
659
660 void AsyncSocket::setErrMessageCB(ErrMessageCallback* callback) {
661   VLOG(6) << "AsyncSocket::setErrMessageCB() this=" << this
662           << ", fd=" << fd_ << ", callback=" << callback
663           << ", state=" << state_;
664
665   // Short circuit if callback is the same as the existing errMessageCallback_.
666   if (callback == errMessageCallback_) {
667     return;
668   }
669
670   if (!msgErrQueueSupported) {
671       // Per-socket error message queue is not supported on this platform.
672       return invalidState(callback);
673   }
674
675   DestructorGuard dg(this);
676   eventBase_->dcheckIsInEventBaseThread();
677
678   if (callback == nullptr) {
679     // We should be able to reset the callback regardless of the
680     // socket state. It's important to have a reliable callback
681     // cancellation mechanism.
682     errMessageCallback_ = callback;
683     return;
684   }
685
686   switch ((StateEnum)state_) {
687     case StateEnum::CONNECTING:
688     case StateEnum::FAST_OPEN:
689     case StateEnum::ESTABLISHED: {
690       errMessageCallback_ = callback;
691       return;
692     }
693     case StateEnum::CLOSED:
694     case StateEnum::ERROR:
695       // We should never reach here.  SHUT_READ should always be set
696       // if we are in STATE_CLOSED or STATE_ERROR.
697       assert(false);
698       return invalidState(callback);
699     case StateEnum::UNINIT:
700       // We do not allow setReadCallback() to be called before we start
701       // connecting.
702       return invalidState(callback);
703   }
704
705   // We don't put a default case in the switch statement, so that the compiler
706   // will warn us to update the switch statement if a new state is added.
707   return invalidState(callback);
708 }
709
710 AsyncSocket::ErrMessageCallback* AsyncSocket::getErrMessageCallback() const {
711   return errMessageCallback_;
712 }
713
714 void AsyncSocket::setSendMsgParamCB(SendMsgParamsCallback* callback) {
715   sendMsgParamCallback_ = callback;
716 }
717
718 AsyncSocket::SendMsgParamsCallback* AsyncSocket::getSendMsgParamsCB() const {
719   return sendMsgParamCallback_;
720 }
721
722 void AsyncSocket::setReadCB(ReadCallback *callback) {
723   VLOG(6) << "AsyncSocket::setReadCallback() this=" << this << ", fd=" << fd_
724           << ", callback=" << callback << ", state=" << state_;
725
726   // Short circuit if callback is the same as the existing readCallback_.
727   //
728   // Note that this is needed for proper functioning during some cleanup cases.
729   // During cleanup we allow setReadCallback(nullptr) to be called even if the
730   // read callback is already unset and we have been detached from an event
731   // base.  This check prevents us from asserting
732   // eventBase_->isInEventBaseThread() when eventBase_ is nullptr.
733   if (callback == readCallback_) {
734     return;
735   }
736
737   /* We are removing a read callback */
738   if (callback == nullptr &&
739       immediateReadHandler_.isLoopCallbackScheduled()) {
740     immediateReadHandler_.cancelLoopCallback();
741   }
742
743   if (shutdownFlags_ & SHUT_READ) {
744     // Reads have already been shut down on this socket.
745     //
746     // Allow setReadCallback(nullptr) to be called in this case, but don't
747     // allow a new callback to be set.
748     //
749     // For example, setReadCallback(nullptr) can happen after an error if we
750     // invoke some other error callback before invoking readError().  The other
751     // error callback that is invoked first may go ahead and clear the read
752     // callback before we get a chance to invoke readError().
753     if (callback != nullptr) {
754       return invalidState(callback);
755     }
756     assert((eventFlags_ & EventHandler::READ) == 0);
757     readCallback_ = nullptr;
758     return;
759   }
760
761   DestructorGuard dg(this);
762   eventBase_->dcheckIsInEventBaseThread();
763
764   switch ((StateEnum)state_) {
765     case StateEnum::CONNECTING:
766     case StateEnum::FAST_OPEN:
767       // For convenience, we allow the read callback to be set while we are
768       // still connecting.  We just store the callback for now.  Once the
769       // connection completes we'll register for read events.
770       readCallback_ = callback;
771       return;
772     case StateEnum::ESTABLISHED:
773     {
774       readCallback_ = callback;
775       uint16_t oldFlags = eventFlags_;
776       if (readCallback_) {
777         eventFlags_ |= EventHandler::READ;
778       } else {
779         eventFlags_ &= ~EventHandler::READ;
780       }
781
782       // Update our registration if our flags have changed
783       if (eventFlags_ != oldFlags) {
784         // We intentionally ignore the return value here.
785         // updateEventRegistration() will move us into the error state if it
786         // fails, and we don't need to do anything else here afterwards.
787         (void)updateEventRegistration();
788       }
789
790       if (readCallback_) {
791         checkForImmediateRead();
792       }
793       return;
794     }
795     case StateEnum::CLOSED:
796     case StateEnum::ERROR:
797       // We should never reach here.  SHUT_READ should always be set
798       // if we are in STATE_CLOSED or STATE_ERROR.
799       assert(false);
800       return invalidState(callback);
801     case StateEnum::UNINIT:
802       // We do not allow setReadCallback() to be called before we start
803       // connecting.
804       return invalidState(callback);
805   }
806
807   // We don't put a default case in the switch statement, so that the compiler
808   // will warn us to update the switch statement if a new state is added.
809   return invalidState(callback);
810 }
811
812 AsyncSocket::ReadCallback* AsyncSocket::getReadCallback() const {
813   return readCallback_;
814 }
815
816 bool AsyncSocket::setZeroCopy(bool enable) {
817   if (msgErrQueueSupported) {
818     zeroCopyVal_ = enable;
819
820     if (fd_ < 0) {
821       return false;
822     }
823
824     int val = enable ? 1 : 0;
825     int ret = setsockopt(fd_, SOL_SOCKET, SO_ZEROCOPY, &val, sizeof(val));
826
827     // if enable == false, set zeroCopyEnabled_ = false regardless
828     // if SO_ZEROCOPY is set or not
829     if (!enable) {
830       zeroCopyEnabled_ = enable;
831       return true;
832     }
833
834     /* if the setsockopt failed, try to see if the socket inherited the flag
835      * since we cannot set SO_ZEROCOPY on a socket s = accept
836      */
837     if (ret) {
838       val = 0;
839       socklen_t optlen = sizeof(val);
840       ret = getsockopt(fd_, SOL_SOCKET, SO_ZEROCOPY, &val, &optlen);
841
842       if (!ret) {
843         enable = val ? true : false;
844       }
845     }
846
847     if (!ret) {
848       zeroCopyEnabled_ = enable;
849
850       return true;
851     }
852   }
853
854   return false;
855 }
856
857 void AsyncSocket::setZeroCopyWriteChainThreshold(size_t threshold) {
858   zeroCopyWriteChainThreshold_ = threshold;
859 }
860
861 bool AsyncSocket::isZeroCopyRequest(WriteFlags flags) {
862   return (zeroCopyEnabled_ && isSet(flags, WriteFlags::WRITE_MSG_ZEROCOPY));
863 }
864
865 void AsyncSocket::adjustZeroCopyFlags(
866     folly::IOBuf* buf,
867     folly::WriteFlags& flags) {
868   if (zeroCopyEnabled_ && zeroCopyWriteChainThreshold_ && buf &&
869       buf->isManaged()) {
870     if (buf->computeChainDataLength() >= zeroCopyWriteChainThreshold_) {
871       flags |= folly::WriteFlags::WRITE_MSG_ZEROCOPY;
872     } else {
873       flags = unSet(flags, folly::WriteFlags::WRITE_MSG_ZEROCOPY);
874     }
875   }
876 }
877
878 void AsyncSocket::adjustZeroCopyFlags(
879     const iovec* vec,
880     uint32_t count,
881     folly::WriteFlags& flags) {
882   if (zeroCopyEnabled_ && zeroCopyWriteChainThreshold_) {
883     count = std::min<uint32_t>(count, kIovMax);
884     size_t sum = 0;
885     for (uint32_t i = 0; i < count; ++i) {
886       const iovec* v = vec + i;
887       sum += v->iov_len;
888     }
889
890     if (sum >= zeroCopyWriteChainThreshold_) {
891       flags |= folly::WriteFlags::WRITE_MSG_ZEROCOPY;
892     } else {
893       flags = unSet(flags, folly::WriteFlags::WRITE_MSG_ZEROCOPY);
894     }
895   }
896 }
897
898 void AsyncSocket::addZeroCopyBuf(std::unique_ptr<folly::IOBuf>&& buf) {
899   uint32_t id = getNextZeroCopyBufId();
900   folly::IOBuf* ptr = buf.get();
901
902   idZeroCopyBufPtrMap_[id] = ptr;
903   auto& p = idZeroCopyBufInfoMap_[ptr];
904   p.count_++;
905   CHECK(p.buf_.get() == nullptr);
906   p.buf_ = std::move(buf);
907 }
908
909 void AsyncSocket::addZeroCopyBuf(folly::IOBuf* ptr) {
910   uint32_t id = getNextZeroCopyBufId();
911   idZeroCopyBufPtrMap_[id] = ptr;
912
913   idZeroCopyBufInfoMap_[ptr].count_++;
914 }
915
916 void AsyncSocket::releaseZeroCopyBuf(uint32_t id) {
917   auto iter = idZeroCopyBufPtrMap_.find(id);
918   CHECK(iter != idZeroCopyBufPtrMap_.end());
919   auto ptr = iter->second;
920   auto iter1 = idZeroCopyBufInfoMap_.find(ptr);
921   CHECK(iter1 != idZeroCopyBufInfoMap_.end());
922   if (0 == --iter1->second.count_) {
923     idZeroCopyBufInfoMap_.erase(iter1);
924   }
925 }
926
927 void AsyncSocket::setZeroCopyBuf(std::unique_ptr<folly::IOBuf>&& buf) {
928   folly::IOBuf* ptr = buf.get();
929   auto& p = idZeroCopyBufInfoMap_[ptr];
930   CHECK(p.buf_.get() == nullptr);
931
932   p.buf_ = std::move(buf);
933 }
934
935 bool AsyncSocket::containsZeroCopyBuf(folly::IOBuf* ptr) {
936   return (idZeroCopyBufInfoMap_.find(ptr) != idZeroCopyBufInfoMap_.end());
937 }
938
939 bool AsyncSocket::isZeroCopyMsg(const cmsghdr& cmsg) const {
940 #ifdef FOLLY_HAVE_MSG_ERRQUEUE
941   if (zeroCopyEnabled_ &&
942       ((cmsg.cmsg_level == SOL_IP && cmsg.cmsg_type == IP_RECVERR) ||
943        (cmsg.cmsg_level == SOL_IPV6 && cmsg.cmsg_type == IPV6_RECVERR))) {
944     const struct sock_extended_err* serr =
945         reinterpret_cast<const struct sock_extended_err*>(CMSG_DATA(&cmsg));
946     return (
947         (serr->ee_errno == 0) && (serr->ee_origin == SO_EE_ORIGIN_ZEROCOPY));
948   }
949 #endif
950   return false;
951 }
952
953 void AsyncSocket::processZeroCopyMsg(const cmsghdr& cmsg) {
954 #ifdef FOLLY_HAVE_MSG_ERRQUEUE
955   const struct sock_extended_err* serr =
956       reinterpret_cast<const struct sock_extended_err*>(CMSG_DATA(&cmsg));
957   uint32_t hi = serr->ee_data;
958   uint32_t lo = serr->ee_info;
959   // disable zero copy if the buffer was actually copied
960   if ((serr->ee_code & SO_EE_CODE_ZEROCOPY_COPIED) && zeroCopyEnabled_) {
961     VLOG(2) << "AsyncSocket::processZeroCopyMsg(): setting "
962             << "zeroCopyEnabled_ = false due to SO_EE_CODE_ZEROCOPY_COPIED "
963             << "on " << fd_;
964     zeroCopyEnabled_ = false;
965   }
966
967   for (uint32_t i = lo; i <= hi; i++) {
968     releaseZeroCopyBuf(i);
969   }
970 #endif
971 }
972
973 void AsyncSocket::write(WriteCallback* callback,
974                          const void* buf, size_t bytes, WriteFlags flags) {
975   iovec op;
976   op.iov_base = const_cast<void*>(buf);
977   op.iov_len = bytes;
978   writeImpl(callback, &op, 1, unique_ptr<IOBuf>(), flags);
979 }
980
981 void AsyncSocket::writev(WriteCallback* callback,
982                           const iovec* vec,
983                           size_t count,
984                           WriteFlags flags) {
985   writeImpl(callback, vec, count, unique_ptr<IOBuf>(), flags);
986 }
987
988 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
989                               WriteFlags flags) {
990   adjustZeroCopyFlags(buf.get(), flags);
991
992   constexpr size_t kSmallSizeMax = 64;
993   size_t count = buf->countChainElements();
994   if (count <= kSmallSizeMax) {
995     // suppress "warning: variable length array 'vec' is used [-Wvla]"
996     FOLLY_PUSH_WARNING
997     FOLLY_GCC_DISABLE_WARNING("-Wvla")
998     iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA, count, kSmallSizeMax)];
999     FOLLY_POP_WARNING
1000
1001     writeChainImpl(callback, vec, count, std::move(buf), flags);
1002   } else {
1003     iovec* vec = new iovec[count];
1004     writeChainImpl(callback, vec, count, std::move(buf), flags);
1005     delete[] vec;
1006   }
1007 }
1008
1009 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
1010     size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
1011   size_t veclen = buf->fillIov(vec, count);
1012   writeImpl(callback, vec, veclen, std::move(buf), flags);
1013 }
1014
1015 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
1016                              size_t count, unique_ptr<IOBuf>&& buf,
1017                              WriteFlags flags) {
1018   VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
1019           << ", callback=" << callback << ", count=" << count
1020           << ", state=" << state_;
1021   DestructorGuard dg(this);
1022   unique_ptr<IOBuf>ioBuf(std::move(buf));
1023   eventBase_->dcheckIsInEventBaseThread();
1024
1025   if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
1026     // No new writes may be performed after the write side of the socket has
1027     // been shutdown.
1028     //
1029     // We could just call callback->writeError() here to fail just this write.
1030     // However, fail hard and use invalidState() to fail all outstanding
1031     // callbacks and move the socket into the error state.  There's most likely
1032     // a bug in the caller's code, so we abort everything rather than trying to
1033     // proceed as best we can.
1034     return invalidState(callback);
1035   }
1036
1037   uint32_t countWritten = 0;
1038   uint32_t partialWritten = 0;
1039   ssize_t bytesWritten = 0;
1040   bool mustRegister = false;
1041   if ((state_ == StateEnum::ESTABLISHED || state_ == StateEnum::FAST_OPEN) &&
1042       !connecting()) {
1043     if (writeReqHead_ == nullptr) {
1044       // If we are established and there are no other writes pending,
1045       // we can attempt to perform the write immediately.
1046       assert(writeReqTail_ == nullptr);
1047       assert((eventFlags_ & EventHandler::WRITE) == 0);
1048
1049       auto writeResult = performWrite(
1050           vec, uint32_t(count), flags, &countWritten, &partialWritten);
1051       bytesWritten = writeResult.writeReturn;
1052       if (bytesWritten < 0) {
1053         auto errnoCopy = errno;
1054         if (writeResult.exception) {
1055           return failWrite(__func__, callback, 0, *writeResult.exception);
1056         }
1057         AsyncSocketException ex(
1058             AsyncSocketException::INTERNAL_ERROR,
1059             withAddr("writev failed"),
1060             errnoCopy);
1061         return failWrite(__func__, callback, 0, ex);
1062       } else if (countWritten == count) {
1063         // done, add the whole buffer
1064         if (isZeroCopyRequest(flags)) {
1065           addZeroCopyBuf(std::move(ioBuf));
1066         }
1067         // We successfully wrote everything.
1068         // Invoke the callback and return.
1069         if (callback) {
1070           callback->writeSuccess();
1071         }
1072         return;
1073       } else { // continue writing the next writeReq
1074         // add just the ptr
1075         if (isZeroCopyRequest(flags)) {
1076           addZeroCopyBuf(ioBuf.get());
1077         }
1078         if (bufferCallback_) {
1079           bufferCallback_->onEgressBuffered();
1080         }
1081       }
1082       if (!connecting()) {
1083         // Writes might put the socket back into connecting state
1084         // if TFO is enabled, and using TFO fails.
1085         // This means that write timeouts would not be active, however
1086         // connect timeouts would affect this stage.
1087         mustRegister = true;
1088       }
1089     }
1090   } else if (!connecting()) {
1091     // Invalid state for writing
1092     return invalidState(callback);
1093   }
1094
1095   // Create a new WriteRequest to add to the queue
1096   WriteRequest* req;
1097   try {
1098     req = BytesWriteRequest::newRequest(
1099         this,
1100         callback,
1101         vec + countWritten,
1102         uint32_t(count - countWritten),
1103         partialWritten,
1104         uint32_t(bytesWritten),
1105         std::move(ioBuf),
1106         flags);
1107   } catch (const std::exception& ex) {
1108     // we mainly expect to catch std::bad_alloc here
1109     AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
1110         withAddr(string("failed to append new WriteRequest: ") + ex.what()));
1111     return failWrite(__func__, callback, size_t(bytesWritten), tex);
1112   }
1113   req->consume();
1114   if (writeReqTail_ == nullptr) {
1115     assert(writeReqHead_ == nullptr);
1116     writeReqHead_ = writeReqTail_ = req;
1117   } else {
1118     writeReqTail_->append(req);
1119     writeReqTail_ = req;
1120   }
1121
1122   // Register for write events if are established and not currently
1123   // waiting on write events
1124   if (mustRegister) {
1125     assert(state_ == StateEnum::ESTABLISHED);
1126     assert((eventFlags_ & EventHandler::WRITE) == 0);
1127     if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1128       assert(state_ == StateEnum::ERROR);
1129       return;
1130     }
1131     if (sendTimeout_ > 0) {
1132       // Schedule a timeout to fire if the write takes too long.
1133       if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1134         AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1135                                withAddr("failed to schedule send timeout"));
1136         return failWrite(__func__, ex);
1137       }
1138     }
1139   }
1140 }
1141
1142 void AsyncSocket::writeRequest(WriteRequest* req) {
1143   if (writeReqTail_ == nullptr) {
1144     assert(writeReqHead_ == nullptr);
1145     writeReqHead_ = writeReqTail_ = req;
1146     req->start();
1147   } else {
1148     writeReqTail_->append(req);
1149     writeReqTail_ = req;
1150   }
1151 }
1152
1153 void AsyncSocket::close() {
1154   VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
1155           << ", state=" << state_ << ", shutdownFlags="
1156           << std::hex << (int) shutdownFlags_;
1157
1158   // close() is only different from closeNow() when there are pending writes
1159   // that need to drain before we can close.  In all other cases, just call
1160   // closeNow().
1161   //
1162   // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
1163   // STATE_ERROR if close() is invoked while a previous closeNow() or failure
1164   // is still running.  (e.g., If there are multiple pending writes, and we
1165   // call writeError() on the first one, it may call close().  In this case we
1166   // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
1167   // writes will still be in the queue.)
1168   //
1169   // We only need to drain pending writes if we are still in STATE_CONNECTING
1170   // or STATE_ESTABLISHED
1171   if ((writeReqHead_ == nullptr) ||
1172       !(state_ == StateEnum::CONNECTING ||
1173       state_ == StateEnum::ESTABLISHED)) {
1174     closeNow();
1175     return;
1176   }
1177
1178   // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
1179   // destroyed until close() returns.
1180   DestructorGuard dg(this);
1181   eventBase_->dcheckIsInEventBaseThread();
1182
1183   // Since there are write requests pending, we have to set the
1184   // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
1185   // connect finishes and we finish writing these requests.
1186   //
1187   // Set SHUT_READ to indicate that reads are shut down, and set the
1188   // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
1189   // pending writes complete.
1190   shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
1191
1192   // If a read callback is set, invoke readEOF() immediately to inform it that
1193   // the socket has been closed and no more data can be read.
1194   if (readCallback_) {
1195     // Disable reads if they are enabled
1196     if (!updateEventRegistration(0, EventHandler::READ)) {
1197       // We're now in the error state; callbacks have been cleaned up
1198       assert(state_ == StateEnum::ERROR);
1199       assert(readCallback_ == nullptr);
1200     } else {
1201       ReadCallback* callback = readCallback_;
1202       readCallback_ = nullptr;
1203       callback->readEOF();
1204     }
1205   }
1206 }
1207
1208 void AsyncSocket::closeNow() {
1209   VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
1210           << ", state=" << state_ << ", shutdownFlags="
1211           << std::hex << (int) shutdownFlags_;
1212   DestructorGuard dg(this);
1213   if (eventBase_) {
1214     eventBase_->dcheckIsInEventBaseThread();
1215   }
1216
1217   switch (state_) {
1218     case StateEnum::ESTABLISHED:
1219     case StateEnum::CONNECTING:
1220     case StateEnum::FAST_OPEN: {
1221       shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1222       state_ = StateEnum::CLOSED;
1223
1224       // If the write timeout was set, cancel it.
1225       writeTimeout_.cancelTimeout();
1226
1227       // If we are registered for I/O events, unregister.
1228       if (eventFlags_ != EventHandler::NONE) {
1229         eventFlags_ = EventHandler::NONE;
1230         if (!updateEventRegistration()) {
1231           // We will have been moved into the error state.
1232           assert(state_ == StateEnum::ERROR);
1233           return;
1234         }
1235       }
1236
1237       if (immediateReadHandler_.isLoopCallbackScheduled()) {
1238         immediateReadHandler_.cancelLoopCallback();
1239       }
1240
1241       if (fd_ >= 0) {
1242         ioHandler_.changeHandlerFD(-1);
1243         doClose();
1244       }
1245
1246       invokeConnectErr(socketClosedLocallyEx);
1247
1248       failAllWrites(socketClosedLocallyEx);
1249
1250       if (readCallback_) {
1251         ReadCallback* callback = readCallback_;
1252         readCallback_ = nullptr;
1253         callback->readEOF();
1254       }
1255       return;
1256     }
1257     case StateEnum::CLOSED:
1258       // Do nothing.  It's possible that we are being called recursively
1259       // from inside a callback that we invoked inside another call to close()
1260       // that is still running.
1261       return;
1262     case StateEnum::ERROR:
1263       // Do nothing.  The error handling code has performed (or is performing)
1264       // cleanup.
1265       return;
1266     case StateEnum::UNINIT:
1267       assert(eventFlags_ == EventHandler::NONE);
1268       assert(connectCallback_ == nullptr);
1269       assert(readCallback_ == nullptr);
1270       assert(writeReqHead_ == nullptr);
1271       shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1272       state_ = StateEnum::CLOSED;
1273       return;
1274   }
1275
1276   LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
1277               << ") called in unknown state " << state_;
1278 }
1279
1280 void AsyncSocket::closeWithReset() {
1281   // Enable SO_LINGER, with the linger timeout set to 0.
1282   // This will trigger a TCP reset when we close the socket.
1283   if (fd_ >= 0) {
1284     struct linger optLinger = {1, 0};
1285     if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
1286       VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
1287               << "on " << fd_ << ": errno=" << errno;
1288     }
1289   }
1290
1291   // Then let closeNow() take care of the rest
1292   closeNow();
1293 }
1294
1295 void AsyncSocket::shutdownWrite() {
1296   VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
1297           << ", state=" << state_ << ", shutdownFlags="
1298           << std::hex << (int) shutdownFlags_;
1299
1300   // If there are no pending writes, shutdownWrite() is identical to
1301   // shutdownWriteNow().
1302   if (writeReqHead_ == nullptr) {
1303     shutdownWriteNow();
1304     return;
1305   }
1306
1307   eventBase_->dcheckIsInEventBaseThread();
1308
1309   // There are pending writes.  Set SHUT_WRITE_PENDING so that the actual
1310   // shutdown will be performed once all writes complete.
1311   shutdownFlags_ |= SHUT_WRITE_PENDING;
1312 }
1313
1314 void AsyncSocket::shutdownWriteNow() {
1315   VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
1316           << ", fd=" << fd_ << ", state=" << state_
1317           << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
1318
1319   if (shutdownFlags_ & SHUT_WRITE) {
1320     // Writes are already shutdown; nothing else to do.
1321     return;
1322   }
1323
1324   // If SHUT_READ is already set, just call closeNow() to completely
1325   // close the socket.  This can happen if close() was called with writes
1326   // pending, and then shutdownWriteNow() is called before all pending writes
1327   // complete.
1328   if (shutdownFlags_ & SHUT_READ) {
1329     closeNow();
1330     return;
1331   }
1332
1333   DestructorGuard dg(this);
1334   if (eventBase_) {
1335     eventBase_->dcheckIsInEventBaseThread();
1336   }
1337
1338   switch (static_cast<StateEnum>(state_)) {
1339     case StateEnum::ESTABLISHED:
1340     {
1341       shutdownFlags_ |= SHUT_WRITE;
1342
1343       // If the write timeout was set, cancel it.
1344       writeTimeout_.cancelTimeout();
1345
1346       // If we are registered for write events, unregister.
1347       if (!updateEventRegistration(0, EventHandler::WRITE)) {
1348         // We will have been moved into the error state.
1349         assert(state_ == StateEnum::ERROR);
1350         return;
1351       }
1352
1353       // Shutdown writes on the file descriptor
1354       shutdown(fd_, SHUT_WR);
1355
1356       // Immediately fail all write requests
1357       failAllWrites(socketShutdownForWritesEx);
1358       return;
1359     }
1360     case StateEnum::CONNECTING:
1361     {
1362       // Set the SHUT_WRITE_PENDING flag.
1363       // When the connection completes, it will check this flag,
1364       // shutdown the write half of the socket, and then set SHUT_WRITE.
1365       shutdownFlags_ |= SHUT_WRITE_PENDING;
1366
1367       // Immediately fail all write requests
1368       failAllWrites(socketShutdownForWritesEx);
1369       return;
1370     }
1371     case StateEnum::UNINIT:
1372       // Callers normally shouldn't call shutdownWriteNow() before the socket
1373       // even starts connecting.  Nonetheless, go ahead and set
1374       // SHUT_WRITE_PENDING.  Once the socket eventually connects it will
1375       // immediately shut down the write side of the socket.
1376       shutdownFlags_ |= SHUT_WRITE_PENDING;
1377       return;
1378     case StateEnum::FAST_OPEN:
1379       // In fast open state we haven't call connected yet, and if we shutdown
1380       // the writes, we will never try to call connect, so shut everything down
1381       shutdownFlags_ |= SHUT_WRITE;
1382       // Immediately fail all write requests
1383       failAllWrites(socketShutdownForWritesEx);
1384       return;
1385     case StateEnum::CLOSED:
1386     case StateEnum::ERROR:
1387       // We should never get here.  SHUT_WRITE should always be set
1388       // in STATE_CLOSED and STATE_ERROR.
1389       VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
1390                  << ", fd=" << fd_ << ") in unexpected state " << state_
1391                  << " with SHUT_WRITE not set ("
1392                  << std::hex << (int) shutdownFlags_ << ")";
1393       assert(false);
1394       return;
1395   }
1396
1397   LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
1398               << fd_ << ") called in unknown state " << state_;
1399 }
1400
1401 bool AsyncSocket::readable() const {
1402   if (fd_ == -1) {
1403     return false;
1404   }
1405   struct pollfd fds[1];
1406   fds[0].fd = fd_;
1407   fds[0].events = POLLIN;
1408   fds[0].revents = 0;
1409   int rc = poll(fds, 1, 0);
1410   return rc == 1;
1411 }
1412
1413 bool AsyncSocket::writable() const {
1414   if (fd_ == -1) {
1415     return false;
1416   }
1417   struct pollfd fds[1];
1418   fds[0].fd = fd_;
1419   fds[0].events = POLLOUT;
1420   fds[0].revents = 0;
1421   int rc = poll(fds, 1, 0);
1422   return rc == 1;
1423 }
1424
1425 bool AsyncSocket::isPending() const {
1426   return ioHandler_.isPending();
1427 }
1428
1429 bool AsyncSocket::hangup() const {
1430   if (fd_ == -1) {
1431     // sanity check, no one should ask for hangup if we are not connected.
1432     assert(false);
1433     return false;
1434   }
1435 #ifdef POLLRDHUP // Linux-only
1436   struct pollfd fds[1];
1437   fds[0].fd = fd_;
1438   fds[0].events = POLLRDHUP|POLLHUP;
1439   fds[0].revents = 0;
1440   poll(fds, 1, 0);
1441   return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1442 #else
1443   return false;
1444 #endif
1445 }
1446
1447 bool AsyncSocket::good() const {
1448   return (
1449       (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN ||
1450        state_ == StateEnum::ESTABLISHED) &&
1451       (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1452 }
1453
1454 bool AsyncSocket::error() const {
1455   return (state_ == StateEnum::ERROR);
1456 }
1457
1458 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1459   VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1460           << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1461           << ", state=" << state_ << ", events="
1462           << std::hex << eventFlags_ << ")";
1463   assert(eventBase_ == nullptr);
1464   eventBase->dcheckIsInEventBaseThread();
1465
1466   eventBase_ = eventBase;
1467   ioHandler_.attachEventBase(eventBase);
1468   writeTimeout_.attachEventBase(eventBase);
1469   if (evbChangeCb_) {
1470     evbChangeCb_->evbAttached(this);
1471   }
1472 }
1473
1474 void AsyncSocket::detachEventBase() {
1475   VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1476           << ", old evb=" << eventBase_ << ", state=" << state_
1477           << ", events=" << std::hex << eventFlags_ << ")";
1478   assert(eventBase_ != nullptr);
1479   eventBase_->dcheckIsInEventBaseThread();
1480
1481   eventBase_ = nullptr;
1482   ioHandler_.detachEventBase();
1483   writeTimeout_.detachEventBase();
1484   if (evbChangeCb_) {
1485     evbChangeCb_->evbDetached(this);
1486   }
1487 }
1488
1489 bool AsyncSocket::isDetachable() const {
1490   DCHECK(eventBase_ != nullptr);
1491   eventBase_->dcheckIsInEventBaseThread();
1492
1493   return !ioHandler_.isHandlerRegistered() && !writeTimeout_.isScheduled();
1494 }
1495
1496 void AsyncSocket::cacheAddresses() {
1497   if (fd_ >= 0) {
1498     try {
1499       cacheLocalAddress();
1500       cachePeerAddress();
1501     } catch (const std::system_error& e) {
1502       if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
1503         VLOG(1) << "Error caching addresses: " << e.code().value() << ", "
1504                 << e.code().message();
1505       }
1506     }
1507   }
1508 }
1509
1510 void AsyncSocket::cacheLocalAddress() const {
1511   if (!localAddr_.isInitialized()) {
1512     localAddr_.setFromLocalAddress(fd_);
1513   }
1514 }
1515
1516 void AsyncSocket::cachePeerAddress() const {
1517   if (!addr_.isInitialized()) {
1518     addr_.setFromPeerAddress(fd_);
1519   }
1520 }
1521
1522 bool AsyncSocket::isZeroCopyWriteInProgress() const noexcept {
1523   eventBase_->dcheckIsInEventBaseThread();
1524   return (!idZeroCopyBufPtrMap_.empty());
1525 }
1526
1527 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1528   cacheLocalAddress();
1529   *address = localAddr_;
1530 }
1531
1532 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1533   cachePeerAddress();
1534   *address = addr_;
1535 }
1536
1537 bool AsyncSocket::getTFOSucceded() const {
1538   return detail::tfo_succeeded(fd_);
1539 }
1540
1541 int AsyncSocket::setNoDelay(bool noDelay) {
1542   if (fd_ < 0) {
1543     VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1544                << this << "(state=" << state_ << ")";
1545     return EINVAL;
1546
1547   }
1548
1549   int value = noDelay ? 1 : 0;
1550   if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1551     int errnoCopy = errno;
1552     VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1553             << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1554             << strerror(errnoCopy);
1555     return errnoCopy;
1556   }
1557
1558   return 0;
1559 }
1560
1561 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1562
1563   #ifndef TCP_CONGESTION
1564   #define TCP_CONGESTION  13
1565   #endif
1566
1567   if (fd_ < 0) {
1568     VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1569                << "socket " << this << "(state=" << state_ << ")";
1570     return EINVAL;
1571
1572   }
1573
1574   if (setsockopt(
1575           fd_,
1576           IPPROTO_TCP,
1577           TCP_CONGESTION,
1578           cname.c_str(),
1579           socklen_t(cname.length() + 1)) != 0) {
1580     int errnoCopy = errno;
1581     VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1582             << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1583             << strerror(errnoCopy);
1584     return errnoCopy;
1585   }
1586
1587   return 0;
1588 }
1589
1590 int AsyncSocket::setQuickAck(bool quickack) {
1591   (void)quickack;
1592   if (fd_ < 0) {
1593     VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1594                << this << "(state=" << state_ << ")";
1595     return EINVAL;
1596
1597   }
1598
1599 #ifdef TCP_QUICKACK // Linux-only
1600   int value = quickack ? 1 : 0;
1601   if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1602     int errnoCopy = errno;
1603     VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1604             << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1605             << strerror(errnoCopy);
1606     return errnoCopy;
1607   }
1608
1609   return 0;
1610 #else
1611   return ENOSYS;
1612 #endif
1613 }
1614
1615 int AsyncSocket::setSendBufSize(size_t bufsize) {
1616   if (fd_ < 0) {
1617     VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1618                << this << "(state=" << state_ << ")";
1619     return EINVAL;
1620   }
1621
1622   if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1623     int errnoCopy = errno;
1624     VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1625             << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1626             << strerror(errnoCopy);
1627     return errnoCopy;
1628   }
1629
1630   return 0;
1631 }
1632
1633 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1634   if (fd_ < 0) {
1635     VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1636                << this << "(state=" << state_ << ")";
1637     return EINVAL;
1638   }
1639
1640   if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1641     int errnoCopy = errno;
1642     VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1643             << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1644             << strerror(errnoCopy);
1645     return errnoCopy;
1646   }
1647
1648   return 0;
1649 }
1650
1651 int AsyncSocket::setTCPProfile(int profd) {
1652   if (fd_ < 0) {
1653     VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1654                << this << "(state=" << state_ << ")";
1655     return EINVAL;
1656   }
1657
1658   if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1659     int errnoCopy = errno;
1660     VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1661             << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1662             << strerror(errnoCopy);
1663     return errnoCopy;
1664   }
1665
1666   return 0;
1667 }
1668
1669 void AsyncSocket::ioReady(uint16_t events) noexcept {
1670   VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd=" << fd_
1671           << ", events=" << std::hex << events << ", state=" << state_;
1672   DestructorGuard dg(this);
1673   assert(events & EventHandler::READ_WRITE);
1674   eventBase_->dcheckIsInEventBaseThread();
1675
1676   uint16_t relevantEvents = uint16_t(events & EventHandler::READ_WRITE);
1677   EventBase* originalEventBase = eventBase_;
1678   // If we got there it means that either EventHandler::READ or
1679   // EventHandler::WRITE is set. Any of these flags can
1680   // indicate that there are messages available in the socket
1681   // error message queue.
1682   handleErrMessages();
1683
1684   // Return now if handleErrMessages() detached us from our EventBase
1685   if (eventBase_ != originalEventBase) {
1686     return;
1687   }
1688
1689   if (relevantEvents == EventHandler::READ) {
1690     handleRead();
1691   } else if (relevantEvents == EventHandler::WRITE) {
1692     handleWrite();
1693   } else if (relevantEvents == EventHandler::READ_WRITE) {
1694     // If both read and write events are ready, process writes first.
1695     handleWrite();
1696
1697     // Return now if handleWrite() detached us from our EventBase
1698     if (eventBase_ != originalEventBase) {
1699       return;
1700     }
1701
1702     // Only call handleRead() if a read callback is still installed.
1703     // (It's possible that the read callback was uninstalled during
1704     // handleWrite().)
1705     if (readCallback_) {
1706       handleRead();
1707     }
1708   } else {
1709     VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1710                << std::hex << events << "(this=" << this << ")";
1711     abort();
1712   }
1713 }
1714
1715 AsyncSocket::ReadResult
1716 AsyncSocket::performRead(void** buf, size_t* buflen, size_t* /* offset */) {
1717   VLOG(5) << "AsyncSocket::performRead() this=" << this << ", buf=" << *buf
1718           << ", buflen=" << *buflen;
1719
1720   if (preReceivedData_ && !preReceivedData_->empty()) {
1721     VLOG(5) << "AsyncSocket::performRead() this=" << this
1722             << ", reading pre-received data";
1723
1724     io::Cursor cursor(preReceivedData_.get());
1725     auto len = cursor.pullAtMost(*buf, *buflen);
1726
1727     IOBufQueue queue;
1728     queue.append(std::move(preReceivedData_));
1729     queue.trimStart(len);
1730     preReceivedData_ = queue.move();
1731
1732     appBytesReceived_ += len;
1733     return ReadResult(len);
1734   }
1735
1736   ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT);
1737   if (bytes < 0) {
1738     if (errno == EAGAIN || errno == EWOULDBLOCK) {
1739       // No more data to read right now.
1740       return ReadResult(READ_BLOCKING);
1741     } else {
1742       return ReadResult(READ_ERROR);
1743     }
1744   } else {
1745     appBytesReceived_ += bytes;
1746     return ReadResult(bytes);
1747   }
1748 }
1749
1750 void AsyncSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1751   // no matter what, buffer should be preapared for non-ssl socket
1752   CHECK(readCallback_);
1753   readCallback_->getReadBuffer(buf, buflen);
1754 }
1755
1756 void AsyncSocket::handleErrMessages() noexcept {
1757   // This method has non-empty implementation only for platforms
1758   // supporting per-socket error queues.
1759   VLOG(5) << "AsyncSocket::handleErrMessages() this=" << this << ", fd=" << fd_
1760           << ", state=" << state_;
1761   if (errMessageCallback_ == nullptr &&
1762       (!zeroCopyEnabled_ || idZeroCopyBufPtrMap_.empty())) {
1763     VLOG(7) << "AsyncSocket::handleErrMessages(): "
1764             << "no callback installed - exiting.";
1765     return;
1766   }
1767
1768 #ifdef FOLLY_HAVE_MSG_ERRQUEUE
1769   uint8_t ctrl[1024];
1770   unsigned char data;
1771   struct msghdr msg;
1772   iovec entry;
1773
1774   entry.iov_base = &data;
1775   entry.iov_len = sizeof(data);
1776   msg.msg_iov = &entry;
1777   msg.msg_iovlen = 1;
1778   msg.msg_name = nullptr;
1779   msg.msg_namelen = 0;
1780   msg.msg_control = ctrl;
1781   msg.msg_controllen = sizeof(ctrl);
1782   msg.msg_flags = 0;
1783
1784   int ret;
1785   while (true) {
1786     ret = recvmsg(fd_, &msg, MSG_ERRQUEUE);
1787     VLOG(5) << "AsyncSocket::handleErrMessages(): recvmsg returned " << ret;
1788
1789     if (ret < 0) {
1790       if (errno != EAGAIN) {
1791         auto errnoCopy = errno;
1792         LOG(ERROR) << "::recvmsg exited with code " << ret
1793                    << ", errno: " << errnoCopy;
1794         AsyncSocketException ex(
1795           AsyncSocketException::INTERNAL_ERROR,
1796           withAddr("recvmsg() failed"),
1797           errnoCopy);
1798         failErrMessageRead(__func__, ex);
1799       }
1800       return;
1801     }
1802
1803     for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
1804          cmsg != nullptr && cmsg->cmsg_len != 0;
1805          cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1806       if (isZeroCopyMsg(*cmsg)) {
1807         processZeroCopyMsg(*cmsg);
1808       } else {
1809         if (errMessageCallback_) {
1810           errMessageCallback_->errMessage(*cmsg);
1811         }
1812       }
1813     }
1814   }
1815 #endif // FOLLY_HAVE_MSG_ERRQUEUE
1816 }
1817
1818 void AsyncSocket::handleRead() noexcept {
1819   VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1820           << ", state=" << state_;
1821   assert(state_ == StateEnum::ESTABLISHED);
1822   assert((shutdownFlags_ & SHUT_READ) == 0);
1823   assert(readCallback_ != nullptr);
1824   assert(eventFlags_ & EventHandler::READ);
1825
1826   // Loop until:
1827   // - a read attempt would block
1828   // - readCallback_ is uninstalled
1829   // - the number of loop iterations exceeds the optional maximum
1830   // - this AsyncSocket is moved to another EventBase
1831   //
1832   // When we invoke readDataAvailable() it may uninstall the readCallback_,
1833   // which is why need to check for it here.
1834   //
1835   // The last bullet point is slightly subtle.  readDataAvailable() may also
1836   // detach this socket from this EventBase.  However, before
1837   // readDataAvailable() returns another thread may pick it up, attach it to
1838   // a different EventBase, and install another readCallback_.  We need to
1839   // exit immediately after readDataAvailable() returns if the eventBase_ has
1840   // changed.  (The caller must perform some sort of locking to transfer the
1841   // AsyncSocket between threads properly.  This will be sufficient to ensure
1842   // that this thread sees the updated eventBase_ variable after
1843   // readDataAvailable() returns.)
1844   uint16_t numReads = 0;
1845   EventBase* originalEventBase = eventBase_;
1846   while (readCallback_ && eventBase_ == originalEventBase) {
1847     // Get the buffer to read into.
1848     void* buf = nullptr;
1849     size_t buflen = 0, offset = 0;
1850     try {
1851       prepareReadBuffer(&buf, &buflen);
1852       VLOG(5) << "prepareReadBuffer() buf=" << buf << ", buflen=" << buflen;
1853     } catch (const AsyncSocketException& ex) {
1854       return failRead(__func__, ex);
1855     } catch (const std::exception& ex) {
1856       AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1857                               string("ReadCallback::getReadBuffer() "
1858                                      "threw exception: ") +
1859                               ex.what());
1860       return failRead(__func__, tex);
1861     } catch (...) {
1862       AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1863                              "ReadCallback::getReadBuffer() threw "
1864                              "non-exception type");
1865       return failRead(__func__, ex);
1866     }
1867     if (!isBufferMovable_ && (buf == nullptr || buflen == 0)) {
1868       AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1869                              "ReadCallback::getReadBuffer() returned "
1870                              "empty buffer");
1871       return failRead(__func__, ex);
1872     }
1873
1874     // Perform the read
1875     auto readResult = performRead(&buf, &buflen, &offset);
1876     auto bytesRead = readResult.readReturn;
1877     VLOG(4) << "this=" << this << ", AsyncSocket::handleRead() got "
1878             << bytesRead << " bytes";
1879     if (bytesRead > 0) {
1880       if (!isBufferMovable_) {
1881         readCallback_->readDataAvailable(size_t(bytesRead));
1882       } else {
1883         CHECK(kOpenSslModeMoveBufferOwnership);
1884         VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
1885                 << "buf=" << buf << ", " << bytesRead << "/" << buflen
1886                 << ", offset=" << offset;
1887         auto readBuf = folly::IOBuf::takeOwnership(buf, buflen);
1888         readBuf->trimStart(offset);
1889         readBuf->trimEnd(buflen - offset - bytesRead);
1890         readCallback_->readBufferAvailable(std::move(readBuf));
1891       }
1892
1893       // Fall through and continue around the loop if the read
1894       // completely filled the available buffer.
1895       // Note that readCallback_ may have been uninstalled or changed inside
1896       // readDataAvailable().
1897       if (size_t(bytesRead) < buflen) {
1898         return;
1899       }
1900     } else if (bytesRead == READ_BLOCKING) {
1901         // No more data to read right now.
1902         return;
1903     } else if (bytesRead == READ_ERROR) {
1904       readErr_ = READ_ERROR;
1905       if (readResult.exception) {
1906         return failRead(__func__, *readResult.exception);
1907       }
1908       auto errnoCopy = errno;
1909       AsyncSocketException ex(
1910           AsyncSocketException::INTERNAL_ERROR,
1911           withAddr("recv() failed"),
1912           errnoCopy);
1913       return failRead(__func__, ex);
1914     } else {
1915       assert(bytesRead == READ_EOF);
1916       readErr_ = READ_EOF;
1917       // EOF
1918       shutdownFlags_ |= SHUT_READ;
1919       if (!updateEventRegistration(0, EventHandler::READ)) {
1920         // we've already been moved into STATE_ERROR
1921         assert(state_ == StateEnum::ERROR);
1922         assert(readCallback_ == nullptr);
1923         return;
1924       }
1925
1926       ReadCallback* callback = readCallback_;
1927       readCallback_ = nullptr;
1928       callback->readEOF();
1929       return;
1930     }
1931     if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1932       if (readCallback_ != nullptr) {
1933         // We might still have data in the socket.
1934         // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
1935         scheduleImmediateRead();
1936       }
1937       return;
1938     }
1939   }
1940 }
1941
1942 /**
1943  * This function attempts to write as much data as possible, until no more data
1944  * can be written.
1945  *
1946  * - If it sends all available data, it unregisters for write events, and stops
1947  *   the writeTimeout_.
1948  *
1949  * - If not all of the data can be sent immediately, it reschedules
1950  *   writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1951  *   registered for write events.
1952  */
1953 void AsyncSocket::handleWrite() noexcept {
1954   VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1955           << ", state=" << state_;
1956   DestructorGuard dg(this);
1957
1958   if (state_ == StateEnum::CONNECTING) {
1959     handleConnect();
1960     return;
1961   }
1962
1963   // Normal write
1964   assert(state_ == StateEnum::ESTABLISHED);
1965   assert((shutdownFlags_ & SHUT_WRITE) == 0);
1966   assert(writeReqHead_ != nullptr);
1967
1968   // Loop until we run out of write requests,
1969   // or until this socket is moved to another EventBase.
1970   // (See the comment in handleRead() explaining how this can happen.)
1971   EventBase* originalEventBase = eventBase_;
1972   while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1973     auto writeResult = writeReqHead_->performWrite();
1974     if (writeResult.writeReturn < 0) {
1975       if (writeResult.exception) {
1976         return failWrite(__func__, *writeResult.exception);
1977       }
1978       auto errnoCopy = errno;
1979       AsyncSocketException ex(
1980           AsyncSocketException::INTERNAL_ERROR,
1981           withAddr("writev() failed"),
1982           errnoCopy);
1983       return failWrite(__func__, ex);
1984     } else if (writeReqHead_->isComplete()) {
1985       // We finished this request
1986       WriteRequest* req = writeReqHead_;
1987       writeReqHead_ = req->getNext();
1988
1989       if (writeReqHead_ == nullptr) {
1990         writeReqTail_ = nullptr;
1991         // This is the last write request.
1992         // Unregister for write events and cancel the send timer
1993         // before we invoke the callback.  We have to update the state properly
1994         // before calling the callback, since it may want to detach us from
1995         // the EventBase.
1996         if (eventFlags_ & EventHandler::WRITE) {
1997           if (!updateEventRegistration(0, EventHandler::WRITE)) {
1998             assert(state_ == StateEnum::ERROR);
1999             return;
2000           }
2001           // Stop the send timeout
2002           writeTimeout_.cancelTimeout();
2003         }
2004         assert(!writeTimeout_.isScheduled());
2005
2006         // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
2007         // we finish sending the last write request.
2008         //
2009         // We have to do this before invoking writeSuccess(), since
2010         // writeSuccess() may detach us from our EventBase.
2011         if (shutdownFlags_ & SHUT_WRITE_PENDING) {
2012           assert(connectCallback_ == nullptr);
2013           shutdownFlags_ |= SHUT_WRITE;
2014
2015           if (shutdownFlags_ & SHUT_READ) {
2016             // Reads have already been shutdown.  Fully close the socket and
2017             // move to STATE_CLOSED.
2018             //
2019             // Note: This code currently moves us to STATE_CLOSED even if
2020             // close() hasn't ever been called.  This can occur if we have
2021             // received EOF from the peer and shutdownWrite() has been called
2022             // locally.  Should we bother staying in STATE_ESTABLISHED in this
2023             // case, until close() is actually called?  I can't think of a
2024             // reason why we would need to do so.  No other operations besides
2025             // calling close() or destroying the socket can be performed at
2026             // this point.
2027             assert(readCallback_ == nullptr);
2028             state_ = StateEnum::CLOSED;
2029             if (fd_ >= 0) {
2030               ioHandler_.changeHandlerFD(-1);
2031               doClose();
2032             }
2033           } else {
2034             // Reads are still enabled, so we are only doing a half-shutdown
2035             shutdown(fd_, SHUT_WR);
2036           }
2037         }
2038       }
2039
2040       // Invoke the callback
2041       WriteCallback* callback = req->getCallback();
2042       req->destroy();
2043       if (callback) {
2044         callback->writeSuccess();
2045       }
2046       // We'll continue around the loop, trying to write another request
2047     } else {
2048       // Partial write.
2049       if (bufferCallback_) {
2050         bufferCallback_->onEgressBuffered();
2051       }
2052       writeReqHead_->consume();
2053       // Stop after a partial write; it's highly likely that a subsequent write
2054       // attempt will just return EAGAIN.
2055       //
2056       // Ensure that we are registered for write events.
2057       if ((eventFlags_ & EventHandler::WRITE) == 0) {
2058         if (!updateEventRegistration(EventHandler::WRITE, 0)) {
2059           assert(state_ == StateEnum::ERROR);
2060           return;
2061         }
2062       }
2063
2064       // Reschedule the send timeout, since we have made some write progress.
2065       if (sendTimeout_ > 0) {
2066         if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
2067           AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
2068               withAddr("failed to reschedule write timeout"));
2069           return failWrite(__func__, ex);
2070         }
2071       }
2072       return;
2073     }
2074   }
2075   if (!writeReqHead_ && bufferCallback_) {
2076     bufferCallback_->onEgressBufferCleared();
2077   }
2078 }
2079
2080 void AsyncSocket::checkForImmediateRead() noexcept {
2081   // We currently don't attempt to perform optimistic reads in AsyncSocket.
2082   // (However, note that some subclasses do override this method.)
2083   //
2084   // Simply calling handleRead() here would be bad, as this would call
2085   // readCallback_->getReadBuffer(), forcing the callback to allocate a read
2086   // buffer even though no data may be available.  This would waste lots of
2087   // memory, since the buffer will sit around unused until the socket actually
2088   // becomes readable.
2089   //
2090   // Checking if the socket is readable now also seems like it would probably
2091   // be a pessimism.  In most cases it probably wouldn't be readable, and we
2092   // would just waste an extra system call.  Even if it is readable, waiting to
2093   // find out from libevent on the next event loop doesn't seem that bad.
2094   //
2095   // The exception to this is if we have pre-received data. In that case there
2096   // is definitely data available immediately.
2097   if (preReceivedData_ && !preReceivedData_->empty()) {
2098     handleRead();
2099   }
2100 }
2101
2102 void AsyncSocket::handleInitialReadWrite() noexcept {
2103   // Our callers should already be holding a DestructorGuard, but grab
2104   // one here just to make sure, in case one of our calling code paths ever
2105   // changes.
2106   DestructorGuard dg(this);
2107   // If we have a readCallback_, make sure we enable read events.  We
2108   // may already be registered for reads if connectSuccess() set
2109   // the read calback.
2110   if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
2111     assert(state_ == StateEnum::ESTABLISHED);
2112     assert((shutdownFlags_ & SHUT_READ) == 0);
2113     if (!updateEventRegistration(EventHandler::READ, 0)) {
2114       assert(state_ == StateEnum::ERROR);
2115       return;
2116     }
2117     checkForImmediateRead();
2118   } else if (readCallback_ == nullptr) {
2119     // Unregister for read events.
2120     updateEventRegistration(0, EventHandler::READ);
2121   }
2122
2123   // If we have write requests pending, try to send them immediately.
2124   // Since we just finished accepting, there is a very good chance that we can
2125   // write without blocking.
2126   //
2127   // However, we only process them if EventHandler::WRITE is not already set,
2128   // which means that we're already blocked on a write attempt.  (This can
2129   // happen if connectSuccess() called write() before returning.)
2130   if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
2131     // Call handleWrite() to perform write processing.
2132     handleWrite();
2133   } else if (writeReqHead_ == nullptr) {
2134     // Unregister for write event.
2135     updateEventRegistration(0, EventHandler::WRITE);
2136   }
2137 }
2138
2139 void AsyncSocket::handleConnect() noexcept {
2140   VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
2141           << ", state=" << state_;
2142   assert(state_ == StateEnum::CONNECTING);
2143   // SHUT_WRITE can never be set while we are still connecting;
2144   // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
2145   // finishes
2146   assert((shutdownFlags_ & SHUT_WRITE) == 0);
2147
2148   // In case we had a connect timeout, cancel the timeout
2149   writeTimeout_.cancelTimeout();
2150   // We don't use a persistent registration when waiting on a connect event,
2151   // so we have been automatically unregistered now.  Update eventFlags_ to
2152   // reflect reality.
2153   assert(eventFlags_ == EventHandler::WRITE);
2154   eventFlags_ = EventHandler::NONE;
2155
2156   // Call getsockopt() to check if the connect succeeded
2157   int error;
2158   socklen_t len = sizeof(error);
2159   int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
2160   if (rv != 0) {
2161     auto errnoCopy = errno;
2162     AsyncSocketException ex(
2163         AsyncSocketException::INTERNAL_ERROR,
2164         withAddr("error calling getsockopt() after connect"),
2165         errnoCopy);
2166     VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
2167                << fd_ << " host=" << addr_.describe()
2168                << ") exception:" << ex.what();
2169     return failConnect(__func__, ex);
2170   }
2171
2172   if (error != 0) {
2173     AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2174                            "connect failed", error);
2175     VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
2176             << fd_ << " host=" << addr_.describe()
2177             << ") exception: " << ex.what();
2178     return failConnect(__func__, ex);
2179   }
2180
2181   // Move into STATE_ESTABLISHED
2182   state_ = StateEnum::ESTABLISHED;
2183
2184   // If SHUT_WRITE_PENDING is set and we don't have any write requests to
2185   // perform, immediately shutdown the write half of the socket.
2186   if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
2187     // SHUT_READ shouldn't be set.  If close() is called on the socket while we
2188     // are still connecting we just abort the connect rather than waiting for
2189     // it to complete.
2190     assert((shutdownFlags_ & SHUT_READ) == 0);
2191     shutdown(fd_, SHUT_WR);
2192     shutdownFlags_ |= SHUT_WRITE;
2193   }
2194
2195   VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
2196           << "successfully connected; state=" << state_;
2197
2198   // Remember the EventBase we are attached to, before we start invoking any
2199   // callbacks (since the callbacks may call detachEventBase()).
2200   EventBase* originalEventBase = eventBase_;
2201
2202   invokeConnectSuccess();
2203   // Note that the connect callback may have changed our state.
2204   // (set or unset the read callback, called write(), closed the socket, etc.)
2205   // The following code needs to handle these situations correctly.
2206   //
2207   // If the socket has been closed, readCallback_ and writeReqHead_ will
2208   // always be nullptr, so that will prevent us from trying to read or write.
2209   //
2210   // The main thing to check for is if eventBase_ is still originalEventBase.
2211   // If not, we have been detached from this event base, so we shouldn't
2212   // perform any more operations.
2213   if (eventBase_ != originalEventBase) {
2214     return;
2215   }
2216
2217   handleInitialReadWrite();
2218 }
2219
2220 void AsyncSocket::timeoutExpired() noexcept {
2221   VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
2222           << "state=" << state_ << ", events=" << std::hex << eventFlags_;
2223   DestructorGuard dg(this);
2224   eventBase_->dcheckIsInEventBaseThread();
2225
2226   if (state_ == StateEnum::CONNECTING) {
2227     // connect() timed out
2228     // Unregister for I/O events.
2229     if (connectCallback_) {
2230       AsyncSocketException ex(
2231           AsyncSocketException::TIMED_OUT,
2232           folly::sformat(
2233               "connect timed out after {}ms", connectTimeout_.count()));
2234       failConnect(__func__, ex);
2235     } else {
2236       // we faced a connect error without a connect callback, which could
2237       // happen due to TFO.
2238       AsyncSocketException ex(
2239           AsyncSocketException::TIMED_OUT, "write timed out during connection");
2240       failWrite(__func__, ex);
2241     }
2242   } else {
2243     // a normal write operation timed out
2244     AsyncSocketException ex(
2245         AsyncSocketException::TIMED_OUT,
2246         folly::sformat("write timed out after {}ms", sendTimeout_));
2247     failWrite(__func__, ex);
2248   }
2249 }
2250
2251 ssize_t AsyncSocket::tfoSendMsg(int fd, struct msghdr* msg, int msg_flags) {
2252   return detail::tfo_sendmsg(fd, msg, msg_flags);
2253 }
2254
2255 AsyncSocket::WriteResult
2256 AsyncSocket::sendSocketMessage(int fd, struct msghdr* msg, int msg_flags) {
2257   ssize_t totalWritten = 0;
2258   if (state_ == StateEnum::FAST_OPEN) {
2259     sockaddr_storage addr;
2260     auto len = addr_.getAddress(&addr);
2261     msg->msg_name = &addr;
2262     msg->msg_namelen = len;
2263     totalWritten = tfoSendMsg(fd_, msg, msg_flags);
2264     if (totalWritten >= 0) {
2265       tfoFinished_ = true;
2266       state_ = StateEnum::ESTABLISHED;
2267       // We schedule this asynchrously so that we don't end up
2268       // invoking initial read or write while a write is in progress.
2269       scheduleInitialReadWrite();
2270     } else if (errno == EINPROGRESS) {
2271       VLOG(4) << "TFO falling back to connecting";
2272       // A normal sendmsg doesn't return EINPROGRESS, however
2273       // TFO might fallback to connecting if there is no
2274       // cookie.
2275       state_ = StateEnum::CONNECTING;
2276       try {
2277         scheduleConnectTimeout();
2278         registerForConnectEvents();
2279       } catch (const AsyncSocketException& ex) {
2280         return WriteResult(
2281             WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
2282       }
2283       // Let's fake it that no bytes were written and return an errno.
2284       errno = EAGAIN;
2285       totalWritten = -1;
2286     } else if (errno == EOPNOTSUPP) {
2287       // Try falling back to connecting.
2288       VLOG(4) << "TFO not supported";
2289       state_ = StateEnum::CONNECTING;
2290       try {
2291         int ret = socketConnect((const sockaddr*)&addr, len);
2292         if (ret == 0) {
2293           // connect succeeded immediately
2294           // Treat this like no data was written.
2295           state_ = StateEnum::ESTABLISHED;
2296           scheduleInitialReadWrite();
2297         }
2298         // If there was no exception during connections,
2299         // we would return that no bytes were written.
2300         errno = EAGAIN;
2301         totalWritten = -1;
2302       } catch (const AsyncSocketException& ex) {
2303         return WriteResult(
2304             WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
2305       }
2306     } else if (errno == EAGAIN) {
2307       // Normally sendmsg would indicate that the write would block.
2308       // However in the fast open case, it would indicate that sendmsg
2309       // fell back to a connect. This is a return code from connect()
2310       // instead, and is an error condition indicating no fds available.
2311       return WriteResult(
2312           WRITE_ERROR,
2313           std::make_unique<AsyncSocketException>(
2314               AsyncSocketException::UNKNOWN, "No more free local ports"));
2315     }
2316   } else {
2317     totalWritten = ::sendmsg(fd, msg, msg_flags);
2318   }
2319   return WriteResult(totalWritten);
2320 }
2321
2322 AsyncSocket::WriteResult AsyncSocket::performWrite(
2323     const iovec* vec,
2324     uint32_t count,
2325     WriteFlags flags,
2326     uint32_t* countWritten,
2327     uint32_t* partialWritten) {
2328   // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
2329   // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
2330   // (since it may terminate the program if the main program doesn't explicitly
2331   // ignore it).
2332   struct msghdr msg;
2333   msg.msg_name = nullptr;
2334   msg.msg_namelen = 0;
2335   msg.msg_iov = const_cast<iovec *>(vec);
2336   msg.msg_iovlen = std::min<size_t>(count, kIovMax);
2337   msg.msg_flags = 0;
2338   msg.msg_controllen = sendMsgParamCallback_->getAncillaryDataSize(flags);
2339   CHECK_GE(AsyncSocket::SendMsgParamsCallback::maxAncillaryDataSize,
2340            msg.msg_controllen);
2341
2342   if (msg.msg_controllen != 0) {
2343     msg.msg_control = reinterpret_cast<char*>(alloca(msg.msg_controllen));
2344     sendMsgParamCallback_->getAncillaryData(flags, msg.msg_control);
2345   } else {
2346     msg.msg_control = nullptr;
2347   }
2348   int msg_flags = sendMsgParamCallback_->getFlags(flags, zeroCopyEnabled_);
2349
2350   auto writeResult = sendSocketMessage(fd_, &msg, msg_flags);
2351   auto totalWritten = writeResult.writeReturn;
2352   if (totalWritten < 0) {
2353     bool tryAgain = (errno == EAGAIN);
2354 #ifdef __APPLE__
2355     // Apple has a bug where doing a second write on a socket which we
2356     // have opened with TFO causes an ENOTCONN to be thrown. However the
2357     // socket is really connected, so treat ENOTCONN as a EAGAIN until
2358     // this bug is fixed.
2359     tryAgain |= (errno == ENOTCONN);
2360 #endif
2361     if (!writeResult.exception && tryAgain) {
2362       // TCP buffer is full; we can't write any more data right now.
2363       *countWritten = 0;
2364       *partialWritten = 0;
2365       return WriteResult(0);
2366     }
2367     // error
2368     *countWritten = 0;
2369     *partialWritten = 0;
2370     return writeResult;
2371   }
2372
2373   appBytesWritten_ += totalWritten;
2374
2375   uint32_t bytesWritten;
2376   uint32_t n;
2377   for (bytesWritten = uint32_t(totalWritten), n = 0; n < count; ++n) {
2378     const iovec* v = vec + n;
2379     if (v->iov_len > bytesWritten) {
2380       // Partial write finished in the middle of this iovec
2381       *countWritten = n;
2382       *partialWritten = bytesWritten;
2383       return WriteResult(totalWritten);
2384     }
2385
2386     bytesWritten -= uint32_t(v->iov_len);
2387   }
2388
2389   assert(bytesWritten == 0);
2390   *countWritten = n;
2391   *partialWritten = 0;
2392   return WriteResult(totalWritten);
2393 }
2394
2395 /**
2396  * Re-register the EventHandler after eventFlags_ has changed.
2397  *
2398  * If an error occurs, fail() is called to move the socket into the error state
2399  * and call all currently installed callbacks.  After an error, the
2400  * AsyncSocket is completely unregistered.
2401  *
2402  * @return Returns true on success, or false on error.
2403  */
2404 bool AsyncSocket::updateEventRegistration() {
2405   VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
2406           << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
2407           << ", events=" << std::hex << eventFlags_;
2408   eventBase_->dcheckIsInEventBaseThread();
2409   if (eventFlags_ == EventHandler::NONE) {
2410     ioHandler_.unregisterHandler();
2411     return true;
2412   }
2413
2414   // Always register for persistent events, so we don't have to re-register
2415   // after being called back.
2416   if (!ioHandler_.registerHandler(
2417           uint16_t(eventFlags_ | EventHandler::PERSIST))) {
2418     eventFlags_ = EventHandler::NONE; // we're not registered after error
2419     AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
2420         withAddr("failed to update AsyncSocket event registration"));
2421     fail("updateEventRegistration", ex);
2422     return false;
2423   }
2424
2425   return true;
2426 }
2427
2428 bool AsyncSocket::updateEventRegistration(uint16_t enable,
2429                                            uint16_t disable) {
2430   uint16_t oldFlags = eventFlags_;
2431   eventFlags_ |= enable;
2432   eventFlags_ &= ~disable;
2433   if (eventFlags_ == oldFlags) {
2434     return true;
2435   } else {
2436     return updateEventRegistration();
2437   }
2438 }
2439
2440 void AsyncSocket::startFail() {
2441   // startFail() should only be called once
2442   assert(state_ != StateEnum::ERROR);
2443   assert(getDestructorGuardCount() > 0);
2444   state_ = StateEnum::ERROR;
2445   // Ensure that SHUT_READ and SHUT_WRITE are set,
2446   // so all future attempts to read or write will be rejected
2447   shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
2448
2449   if (eventFlags_ != EventHandler::NONE) {
2450     eventFlags_ = EventHandler::NONE;
2451     ioHandler_.unregisterHandler();
2452   }
2453   writeTimeout_.cancelTimeout();
2454
2455   if (fd_ >= 0) {
2456     ioHandler_.changeHandlerFD(-1);
2457     doClose();
2458   }
2459 }
2460
2461 void AsyncSocket::invokeAllErrors(const AsyncSocketException& ex) {
2462   invokeConnectErr(ex);
2463   failAllWrites(ex);
2464
2465   if (readCallback_) {
2466     ReadCallback* callback = readCallback_;
2467     readCallback_ = nullptr;
2468     callback->readErr(ex);
2469   }
2470 }
2471
2472 void AsyncSocket::finishFail() {
2473   assert(state_ == StateEnum::ERROR);
2474   assert(getDestructorGuardCount() > 0);
2475
2476   AsyncSocketException ex(
2477       AsyncSocketException::INTERNAL_ERROR,
2478       withAddr("socket closing after error"));
2479   invokeAllErrors(ex);
2480 }
2481
2482 void AsyncSocket::finishFail(const AsyncSocketException& ex) {
2483   assert(state_ == StateEnum::ERROR);
2484   assert(getDestructorGuardCount() > 0);
2485   invokeAllErrors(ex);
2486 }
2487
2488 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
2489   VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2490              << state_ << " host=" << addr_.describe()
2491              << "): failed in " << fn << "(): "
2492              << ex.what();
2493   startFail();
2494   finishFail();
2495 }
2496
2497 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
2498   VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2499                << state_ << " host=" << addr_.describe()
2500                << "): failed while connecting in " << fn << "(): "
2501                << ex.what();
2502   startFail();
2503
2504   invokeConnectErr(ex);
2505   finishFail(ex);
2506 }
2507
2508 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
2509   VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2510                << state_ << " host=" << addr_.describe()
2511                << "): failed while reading in " << fn << "(): "
2512                << ex.what();
2513   startFail();
2514
2515   if (readCallback_ != nullptr) {
2516     ReadCallback* callback = readCallback_;
2517     readCallback_ = nullptr;
2518     callback->readErr(ex);
2519   }
2520
2521   finishFail();
2522 }
2523
2524 void AsyncSocket::failErrMessageRead(const char* fn,
2525                                      const AsyncSocketException& ex) {
2526   VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2527                << state_ << " host=" << addr_.describe()
2528                << "): failed while reading message in " << fn << "(): "
2529                << ex.what();
2530   startFail();
2531
2532   if (errMessageCallback_ != nullptr) {
2533     ErrMessageCallback* callback = errMessageCallback_;
2534     errMessageCallback_ = nullptr;
2535     callback->errMessageError(ex);
2536   }
2537
2538   finishFail();
2539 }
2540
2541 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
2542   VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2543                << state_ << " host=" << addr_.describe()
2544                << "): failed while writing in " << fn << "(): "
2545                << ex.what();
2546   startFail();
2547
2548   // Only invoke the first write callback, since the error occurred while
2549   // writing this request.  Let any other pending write callbacks be invoked in
2550   // finishFail().
2551   if (writeReqHead_ != nullptr) {
2552     WriteRequest* req = writeReqHead_;
2553     writeReqHead_ = req->getNext();
2554     WriteCallback* callback = req->getCallback();
2555     uint32_t bytesWritten = req->getTotalBytesWritten();
2556     req->destroy();
2557     if (callback) {
2558       callback->writeErr(bytesWritten, ex);
2559     }
2560   }
2561
2562   finishFail();
2563 }
2564
2565 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
2566                              size_t bytesWritten,
2567                              const AsyncSocketException& ex) {
2568   // This version of failWrite() is used when the failure occurs before
2569   // we've added the callback to writeReqHead_.
2570   VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2571              << state_ << " host=" << addr_.describe()
2572              <<"): failed while writing in " << fn << "(): "
2573              << ex.what();
2574   startFail();
2575
2576   if (callback != nullptr) {
2577     callback->writeErr(bytesWritten, ex);
2578   }
2579
2580   finishFail();
2581 }
2582
2583 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
2584   // Invoke writeError() on all write callbacks.
2585   // This is used when writes are forcibly shutdown with write requests
2586   // pending, or when an error occurs with writes pending.
2587   while (writeReqHead_ != nullptr) {
2588     WriteRequest* req = writeReqHead_;
2589     writeReqHead_ = req->getNext();
2590     WriteCallback* callback = req->getCallback();
2591     if (callback) {
2592       callback->writeErr(req->getTotalBytesWritten(), ex);
2593     }
2594     req->destroy();
2595   }
2596 }
2597
2598 void AsyncSocket::invalidState(ConnectCallback* callback) {
2599   VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2600           << "): connect() called in invalid state " << state_;
2601
2602   /*
2603    * The invalidState() methods don't use the normal failure mechanisms,
2604    * since we don't know what state we are in.  We don't want to call
2605    * startFail()/finishFail() recursively if we are already in the middle of
2606    * cleaning up.
2607    */
2608
2609   AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
2610                          "connect() called with socket in invalid state");
2611   connectEndTime_ = std::chrono::steady_clock::now();
2612   if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2613     if (callback) {
2614       callback->connectErr(ex);
2615     }
2616   } else {
2617     // We can't use failConnect() here since connectCallback_
2618     // may already be set to another callback.  Invoke this ConnectCallback
2619     // here; any other connectCallback_ will be invoked in finishFail()
2620     startFail();
2621     if (callback) {
2622       callback->connectErr(ex);
2623     }
2624     finishFail();
2625   }
2626 }
2627
2628 void AsyncSocket::invalidState(ErrMessageCallback* callback) {
2629   VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2630           << "): setErrMessageCB(" << callback
2631           << ") called in invalid state " << state_;
2632
2633   AsyncSocketException ex(
2634       AsyncSocketException::NOT_OPEN,
2635       msgErrQueueSupported
2636       ? "setErrMessageCB() called with socket in invalid state"
2637       : "This platform does not support socket error message notifications");
2638   if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2639     if (callback) {
2640       callback->errMessageError(ex);
2641     }
2642   } else {
2643     startFail();
2644     if (callback) {
2645       callback->errMessageError(ex);
2646     }
2647     finishFail();
2648   }
2649 }
2650
2651 void AsyncSocket::invokeConnectErr(const AsyncSocketException& ex) {
2652   connectEndTime_ = std::chrono::steady_clock::now();
2653   if (connectCallback_) {
2654     ConnectCallback* callback = connectCallback_;
2655     connectCallback_ = nullptr;
2656     callback->connectErr(ex);
2657   }
2658 }
2659
2660 void AsyncSocket::invokeConnectSuccess() {
2661   connectEndTime_ = std::chrono::steady_clock::now();
2662   if (connectCallback_) {
2663     ConnectCallback* callback = connectCallback_;
2664     connectCallback_ = nullptr;
2665     callback->connectSuccess();
2666   }
2667 }
2668
2669 void AsyncSocket::invalidState(ReadCallback* callback) {
2670   VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2671              << "): setReadCallback(" << callback
2672              << ") called in invalid state " << state_;
2673
2674   AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2675                          "setReadCallback() called with socket in "
2676                          "invalid state");
2677   if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2678     if (callback) {
2679       callback->readErr(ex);
2680     }
2681   } else {
2682     startFail();
2683     if (callback) {
2684       callback->readErr(ex);
2685     }
2686     finishFail();
2687   }
2688 }
2689
2690 void AsyncSocket::invalidState(WriteCallback* callback) {
2691   VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2692              << "): write() called in invalid state " << state_;
2693
2694   AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2695                          withAddr("write() called with socket in invalid state"));
2696   if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2697     if (callback) {
2698       callback->writeErr(0, ex);
2699     }
2700   } else {
2701     startFail();
2702     if (callback) {
2703       callback->writeErr(0, ex);
2704     }
2705     finishFail();
2706   }
2707 }
2708
2709 void AsyncSocket::doClose() {
2710   if (fd_ == -1) {
2711     return;
2712   }
2713   if (const auto shutdownSocketSet = wShutdownSocketSet_.lock()) {
2714     shutdownSocketSet->close(fd_);
2715   } else {
2716     ::close(fd_);
2717   }
2718   fd_ = -1;
2719 }
2720
2721 std::ostream& operator << (std::ostream& os,
2722                            const AsyncSocket::StateEnum& state) {
2723   os << static_cast<int>(state);
2724   return os;
2725 }
2726
2727 std::string AsyncSocket::withAddr(const std::string& s) {
2728   // Don't use addr_ directly because it may not be initialized
2729   // e.g. if constructed from fd
2730   folly::SocketAddress peer, local;
2731   try {
2732     getPeerAddress(&peer);
2733     getLocalAddress(&local);
2734   } catch (const std::exception&) {
2735     // ignore
2736   } catch (...) {
2737     // ignore
2738   }
2739   return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";
2740 }
2741
2742 void AsyncSocket::setBufferCallback(BufferCallback* cb) {
2743   bufferCallback_ = cb;
2744 }
2745
2746 } // namespace folly