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