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