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