883ee1d76e4469df1b3f129926ec885bc1818f79
[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   idZeroCopyBufPtrMap_.erase(iter);
912 }
913
914 void AsyncSocket::setZeroCopyBuf(std::unique_ptr<folly::IOBuf>&& buf) {
915   folly::IOBuf* ptr = buf.get();
916   auto& p = idZeroCopyBufInfoMap_[ptr];
917   CHECK(p.buf_.get() == nullptr);
918
919   p.buf_ = std::move(buf);
920 }
921
922 bool AsyncSocket::containsZeroCopyBuf(folly::IOBuf* ptr) {
923   return (idZeroCopyBufInfoMap_.find(ptr) != idZeroCopyBufInfoMap_.end());
924 }
925
926 bool AsyncSocket::isZeroCopyMsg(const cmsghdr& cmsg) const {
927 #ifdef FOLLY_HAVE_MSG_ERRQUEUE
928   if (zeroCopyEnabled_ &&
929       ((cmsg.cmsg_level == SOL_IP && cmsg.cmsg_type == IP_RECVERR) ||
930        (cmsg.cmsg_level == SOL_IPV6 && cmsg.cmsg_type == IPV6_RECVERR))) {
931     const struct sock_extended_err* serr =
932         reinterpret_cast<const struct sock_extended_err*>(CMSG_DATA(&cmsg));
933     return (
934         (serr->ee_errno == 0) && (serr->ee_origin == SO_EE_ORIGIN_ZEROCOPY));
935   }
936 #endif
937   return false;
938 }
939
940 void AsyncSocket::processZeroCopyMsg(const cmsghdr& cmsg) {
941 #ifdef FOLLY_HAVE_MSG_ERRQUEUE
942   const struct sock_extended_err* serr =
943       reinterpret_cast<const struct sock_extended_err*>(CMSG_DATA(&cmsg));
944   uint32_t hi = serr->ee_data;
945   uint32_t lo = serr->ee_info;
946   // disable zero copy if the buffer was actually copied
947   if ((serr->ee_code & SO_EE_CODE_ZEROCOPY_COPIED) && zeroCopyEnabled_) {
948     VLOG(2) << "AsyncSocket::processZeroCopyMsg(): setting "
949             << "zeroCopyEnabled_ = false due to SO_EE_CODE_ZEROCOPY_COPIED "
950             << "on " << fd_;
951     zeroCopyEnabled_ = false;
952   }
953
954   for (uint32_t i = lo; i <= hi; i++) {
955     releaseZeroCopyBuf(i);
956   }
957 #endif
958 }
959
960 void AsyncSocket::write(WriteCallback* callback,
961                          const void* buf, size_t bytes, WriteFlags flags) {
962   iovec op;
963   op.iov_base = const_cast<void*>(buf);
964   op.iov_len = bytes;
965   writeImpl(callback, &op, 1, unique_ptr<IOBuf>(), flags);
966 }
967
968 void AsyncSocket::writev(WriteCallback* callback,
969                           const iovec* vec,
970                           size_t count,
971                           WriteFlags flags) {
972   writeImpl(callback, vec, count, unique_ptr<IOBuf>(), flags);
973 }
974
975 void AsyncSocket::writeChain(WriteCallback* callback, unique_ptr<IOBuf>&& buf,
976                               WriteFlags flags) {
977   adjustZeroCopyFlags(flags);
978
979   constexpr size_t kSmallSizeMax = 64;
980   size_t count = buf->countChainElements();
981   if (count <= kSmallSizeMax) {
982     // suppress "warning: variable length array 'vec' is used [-Wvla]"
983     FOLLY_PUSH_WARNING
984     FOLLY_GCC_DISABLE_WARNING("-Wvla")
985     iovec vec[BOOST_PP_IF(FOLLY_HAVE_VLA, count, kSmallSizeMax)];
986     FOLLY_POP_WARNING
987
988     writeChainImpl(callback, vec, count, std::move(buf), flags);
989   } else {
990     iovec* vec = new iovec[count];
991     writeChainImpl(callback, vec, count, std::move(buf), flags);
992     delete[] vec;
993   }
994 }
995
996 void AsyncSocket::writeChainImpl(WriteCallback* callback, iovec* vec,
997     size_t count, unique_ptr<IOBuf>&& buf, WriteFlags flags) {
998   size_t veclen = buf->fillIov(vec, count);
999   writeImpl(callback, vec, veclen, std::move(buf), flags);
1000 }
1001
1002 void AsyncSocket::writeImpl(WriteCallback* callback, const iovec* vec,
1003                              size_t count, unique_ptr<IOBuf>&& buf,
1004                              WriteFlags flags) {
1005   VLOG(6) << "AsyncSocket::writev() this=" << this << ", fd=" << fd_
1006           << ", callback=" << callback << ", count=" << count
1007           << ", state=" << state_;
1008   DestructorGuard dg(this);
1009   unique_ptr<IOBuf>ioBuf(std::move(buf));
1010   eventBase_->dcheckIsInEventBaseThread();
1011
1012   if (shutdownFlags_ & (SHUT_WRITE | SHUT_WRITE_PENDING)) {
1013     // No new writes may be performed after the write side of the socket has
1014     // been shutdown.
1015     //
1016     // We could just call callback->writeError() here to fail just this write.
1017     // However, fail hard and use invalidState() to fail all outstanding
1018     // callbacks and move the socket into the error state.  There's most likely
1019     // a bug in the caller's code, so we abort everything rather than trying to
1020     // proceed as best we can.
1021     return invalidState(callback);
1022   }
1023
1024   uint32_t countWritten = 0;
1025   uint32_t partialWritten = 0;
1026   ssize_t bytesWritten = 0;
1027   bool mustRegister = false;
1028   if ((state_ == StateEnum::ESTABLISHED || state_ == StateEnum::FAST_OPEN) &&
1029       !connecting()) {
1030     if (writeReqHead_ == nullptr) {
1031       // If we are established and there are no other writes pending,
1032       // we can attempt to perform the write immediately.
1033       assert(writeReqTail_ == nullptr);
1034       assert((eventFlags_ & EventHandler::WRITE) == 0);
1035
1036       auto writeResult = performWrite(
1037           vec, uint32_t(count), flags, &countWritten, &partialWritten);
1038       bytesWritten = writeResult.writeReturn;
1039       if (bytesWritten < 0) {
1040         auto errnoCopy = errno;
1041         if (writeResult.exception) {
1042           return failWrite(__func__, callback, 0, *writeResult.exception);
1043         }
1044         AsyncSocketException ex(
1045             AsyncSocketException::INTERNAL_ERROR,
1046             withAddr("writev failed"),
1047             errnoCopy);
1048         return failWrite(__func__, callback, 0, ex);
1049       } else if (countWritten == count) {
1050         // done, add the whole buffer
1051         if (countWritten && isZeroCopyRequest(flags)) {
1052           addZeroCopyBuf(std::move(ioBuf));
1053         }
1054         // We successfully wrote everything.
1055         // Invoke the callback and return.
1056         if (callback) {
1057           callback->writeSuccess();
1058         }
1059         return;
1060       } else { // continue writing the next writeReq
1061         // add just the ptr
1062         if (bytesWritten && isZeroCopyRequest(flags)) {
1063           addZeroCopyBuf(ioBuf.get());
1064         }
1065         if (bufferCallback_) {
1066           bufferCallback_->onEgressBuffered();
1067         }
1068       }
1069       if (!connecting()) {
1070         // Writes might put the socket back into connecting state
1071         // if TFO is enabled, and using TFO fails.
1072         // This means that write timeouts would not be active, however
1073         // connect timeouts would affect this stage.
1074         mustRegister = true;
1075       }
1076     }
1077   } else if (!connecting()) {
1078     // Invalid state for writing
1079     return invalidState(callback);
1080   }
1081
1082   // Create a new WriteRequest to add to the queue
1083   WriteRequest* req;
1084   try {
1085     req = BytesWriteRequest::newRequest(
1086         this,
1087         callback,
1088         vec + countWritten,
1089         uint32_t(count - countWritten),
1090         partialWritten,
1091         uint32_t(bytesWritten),
1092         std::move(ioBuf),
1093         flags);
1094   } catch (const std::exception& ex) {
1095     // we mainly expect to catch std::bad_alloc here
1096     AsyncSocketException tex(AsyncSocketException::INTERNAL_ERROR,
1097         withAddr(string("failed to append new WriteRequest: ") + ex.what()));
1098     return failWrite(__func__, callback, size_t(bytesWritten), tex);
1099   }
1100   req->consume();
1101   if (writeReqTail_ == nullptr) {
1102     assert(writeReqHead_ == nullptr);
1103     writeReqHead_ = writeReqTail_ = req;
1104   } else {
1105     writeReqTail_->append(req);
1106     writeReqTail_ = req;
1107   }
1108
1109   // Register for write events if are established and not currently
1110   // waiting on write events
1111   if (mustRegister) {
1112     assert(state_ == StateEnum::ESTABLISHED);
1113     assert((eventFlags_ & EventHandler::WRITE) == 0);
1114     if (!updateEventRegistration(EventHandler::WRITE, 0)) {
1115       assert(state_ == StateEnum::ERROR);
1116       return;
1117     }
1118     if (sendTimeout_ > 0) {
1119       // Schedule a timeout to fire if the write takes too long.
1120       if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
1121         AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
1122                                withAddr("failed to schedule send timeout"));
1123         return failWrite(__func__, ex);
1124       }
1125     }
1126   }
1127 }
1128
1129 void AsyncSocket::writeRequest(WriteRequest* req) {
1130   if (writeReqTail_ == nullptr) {
1131     assert(writeReqHead_ == nullptr);
1132     writeReqHead_ = writeReqTail_ = req;
1133     req->start();
1134   } else {
1135     writeReqTail_->append(req);
1136     writeReqTail_ = req;
1137   }
1138 }
1139
1140 void AsyncSocket::close() {
1141   VLOG(5) << "AsyncSocket::close(): this=" << this << ", fd_=" << fd_
1142           << ", state=" << state_ << ", shutdownFlags="
1143           << std::hex << (int) shutdownFlags_;
1144
1145   // close() is only different from closeNow() when there are pending writes
1146   // that need to drain before we can close.  In all other cases, just call
1147   // closeNow().
1148   //
1149   // Note that writeReqHead_ can be non-nullptr even in STATE_CLOSED or
1150   // STATE_ERROR if close() is invoked while a previous closeNow() or failure
1151   // is still running.  (e.g., If there are multiple pending writes, and we
1152   // call writeError() on the first one, it may call close().  In this case we
1153   // will already be in STATE_CLOSED or STATE_ERROR, but the remaining pending
1154   // writes will still be in the queue.)
1155   //
1156   // We only need to drain pending writes if we are still in STATE_CONNECTING
1157   // or STATE_ESTABLISHED
1158   if ((writeReqHead_ == nullptr) ||
1159       !(state_ == StateEnum::CONNECTING ||
1160       state_ == StateEnum::ESTABLISHED)) {
1161     closeNow();
1162     return;
1163   }
1164
1165   // Declare a DestructorGuard to ensure that the AsyncSocket cannot be
1166   // destroyed until close() returns.
1167   DestructorGuard dg(this);
1168   eventBase_->dcheckIsInEventBaseThread();
1169
1170   // Since there are write requests pending, we have to set the
1171   // SHUT_WRITE_PENDING flag, and wait to perform the real close until the
1172   // connect finishes and we finish writing these requests.
1173   //
1174   // Set SHUT_READ to indicate that reads are shut down, and set the
1175   // SHUT_WRITE_PENDING flag to mark that we want to shutdown once the
1176   // pending writes complete.
1177   shutdownFlags_ |= (SHUT_READ | SHUT_WRITE_PENDING);
1178
1179   // If a read callback is set, invoke readEOF() immediately to inform it that
1180   // the socket has been closed and no more data can be read.
1181   if (readCallback_) {
1182     // Disable reads if they are enabled
1183     if (!updateEventRegistration(0, EventHandler::READ)) {
1184       // We're now in the error state; callbacks have been cleaned up
1185       assert(state_ == StateEnum::ERROR);
1186       assert(readCallback_ == nullptr);
1187     } else {
1188       ReadCallback* callback = readCallback_;
1189       readCallback_ = nullptr;
1190       callback->readEOF();
1191     }
1192   }
1193 }
1194
1195 void AsyncSocket::closeNow() {
1196   VLOG(5) << "AsyncSocket::closeNow(): this=" << this << ", fd_=" << fd_
1197           << ", state=" << state_ << ", shutdownFlags="
1198           << std::hex << (int) shutdownFlags_;
1199   DestructorGuard dg(this);
1200   if (eventBase_) {
1201     eventBase_->dcheckIsInEventBaseThread();
1202   }
1203
1204   switch (state_) {
1205     case StateEnum::ESTABLISHED:
1206     case StateEnum::CONNECTING:
1207     case StateEnum::FAST_OPEN: {
1208       shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1209       state_ = StateEnum::CLOSED;
1210
1211       // If the write timeout was set, cancel it.
1212       writeTimeout_.cancelTimeout();
1213
1214       // If we are registered for I/O events, unregister.
1215       if (eventFlags_ != EventHandler::NONE) {
1216         eventFlags_ = EventHandler::NONE;
1217         if (!updateEventRegistration()) {
1218           // We will have been moved into the error state.
1219           assert(state_ == StateEnum::ERROR);
1220           return;
1221         }
1222       }
1223
1224       if (immediateReadHandler_.isLoopCallbackScheduled()) {
1225         immediateReadHandler_.cancelLoopCallback();
1226       }
1227
1228       if (fd_ >= 0) {
1229         ioHandler_.changeHandlerFD(-1);
1230         doClose();
1231       }
1232
1233       invokeConnectErr(socketClosedLocallyEx);
1234
1235       failAllWrites(socketClosedLocallyEx);
1236
1237       if (readCallback_) {
1238         ReadCallback* callback = readCallback_;
1239         readCallback_ = nullptr;
1240         callback->readEOF();
1241       }
1242       return;
1243     }
1244     case StateEnum::CLOSED:
1245       // Do nothing.  It's possible that we are being called recursively
1246       // from inside a callback that we invoked inside another call to close()
1247       // that is still running.
1248       return;
1249     case StateEnum::ERROR:
1250       // Do nothing.  The error handling code has performed (or is performing)
1251       // cleanup.
1252       return;
1253     case StateEnum::UNINIT:
1254       assert(eventFlags_ == EventHandler::NONE);
1255       assert(connectCallback_ == nullptr);
1256       assert(readCallback_ == nullptr);
1257       assert(writeReqHead_ == nullptr);
1258       shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
1259       state_ = StateEnum::CLOSED;
1260       return;
1261   }
1262
1263   LOG(DFATAL) << "AsyncSocket::closeNow() (this=" << this << ", fd=" << fd_
1264               << ") called in unknown state " << state_;
1265 }
1266
1267 void AsyncSocket::closeWithReset() {
1268   // Enable SO_LINGER, with the linger timeout set to 0.
1269   // This will trigger a TCP reset when we close the socket.
1270   if (fd_ >= 0) {
1271     struct linger optLinger = {1, 0};
1272     if (setSockOpt(SOL_SOCKET, SO_LINGER, &optLinger) != 0) {
1273       VLOG(2) << "AsyncSocket::closeWithReset(): error setting SO_LINGER "
1274               << "on " << fd_ << ": errno=" << errno;
1275     }
1276   }
1277
1278   // Then let closeNow() take care of the rest
1279   closeNow();
1280 }
1281
1282 void AsyncSocket::shutdownWrite() {
1283   VLOG(5) << "AsyncSocket::shutdownWrite(): this=" << this << ", fd=" << fd_
1284           << ", state=" << state_ << ", shutdownFlags="
1285           << std::hex << (int) shutdownFlags_;
1286
1287   // If there are no pending writes, shutdownWrite() is identical to
1288   // shutdownWriteNow().
1289   if (writeReqHead_ == nullptr) {
1290     shutdownWriteNow();
1291     return;
1292   }
1293
1294   eventBase_->dcheckIsInEventBaseThread();
1295
1296   // There are pending writes.  Set SHUT_WRITE_PENDING so that the actual
1297   // shutdown will be performed once all writes complete.
1298   shutdownFlags_ |= SHUT_WRITE_PENDING;
1299 }
1300
1301 void AsyncSocket::shutdownWriteNow() {
1302   VLOG(5) << "AsyncSocket::shutdownWriteNow(): this=" << this
1303           << ", fd=" << fd_ << ", state=" << state_
1304           << ", shutdownFlags=" << std::hex << (int) shutdownFlags_;
1305
1306   if (shutdownFlags_ & SHUT_WRITE) {
1307     // Writes are already shutdown; nothing else to do.
1308     return;
1309   }
1310
1311   // If SHUT_READ is already set, just call closeNow() to completely
1312   // close the socket.  This can happen if close() was called with writes
1313   // pending, and then shutdownWriteNow() is called before all pending writes
1314   // complete.
1315   if (shutdownFlags_ & SHUT_READ) {
1316     closeNow();
1317     return;
1318   }
1319
1320   DestructorGuard dg(this);
1321   if (eventBase_) {
1322     eventBase_->dcheckIsInEventBaseThread();
1323   }
1324
1325   switch (static_cast<StateEnum>(state_)) {
1326     case StateEnum::ESTABLISHED:
1327     {
1328       shutdownFlags_ |= SHUT_WRITE;
1329
1330       // If the write timeout was set, cancel it.
1331       writeTimeout_.cancelTimeout();
1332
1333       // If we are registered for write events, unregister.
1334       if (!updateEventRegistration(0, EventHandler::WRITE)) {
1335         // We will have been moved into the error state.
1336         assert(state_ == StateEnum::ERROR);
1337         return;
1338       }
1339
1340       // Shutdown writes on the file descriptor
1341       shutdown(fd_, SHUT_WR);
1342
1343       // Immediately fail all write requests
1344       failAllWrites(socketShutdownForWritesEx);
1345       return;
1346     }
1347     case StateEnum::CONNECTING:
1348     {
1349       // Set the SHUT_WRITE_PENDING flag.
1350       // When the connection completes, it will check this flag,
1351       // shutdown the write half of the socket, and then set SHUT_WRITE.
1352       shutdownFlags_ |= SHUT_WRITE_PENDING;
1353
1354       // Immediately fail all write requests
1355       failAllWrites(socketShutdownForWritesEx);
1356       return;
1357     }
1358     case StateEnum::UNINIT:
1359       // Callers normally shouldn't call shutdownWriteNow() before the socket
1360       // even starts connecting.  Nonetheless, go ahead and set
1361       // SHUT_WRITE_PENDING.  Once the socket eventually connects it will
1362       // immediately shut down the write side of the socket.
1363       shutdownFlags_ |= SHUT_WRITE_PENDING;
1364       return;
1365     case StateEnum::FAST_OPEN:
1366       // In fast open state we haven't call connected yet, and if we shutdown
1367       // the writes, we will never try to call connect, so shut everything down
1368       shutdownFlags_ |= SHUT_WRITE;
1369       // Immediately fail all write requests
1370       failAllWrites(socketShutdownForWritesEx);
1371       return;
1372     case StateEnum::CLOSED:
1373     case StateEnum::ERROR:
1374       // We should never get here.  SHUT_WRITE should always be set
1375       // in STATE_CLOSED and STATE_ERROR.
1376       VLOG(4) << "AsyncSocket::shutdownWriteNow() (this=" << this
1377                  << ", fd=" << fd_ << ") in unexpected state " << state_
1378                  << " with SHUT_WRITE not set ("
1379                  << std::hex << (int) shutdownFlags_ << ")";
1380       assert(false);
1381       return;
1382   }
1383
1384   LOG(DFATAL) << "AsyncSocket::shutdownWriteNow() (this=" << this << ", fd="
1385               << fd_ << ") called in unknown state " << state_;
1386 }
1387
1388 bool AsyncSocket::readable() const {
1389   if (fd_ == -1) {
1390     return false;
1391   }
1392   struct pollfd fds[1];
1393   fds[0].fd = fd_;
1394   fds[0].events = POLLIN;
1395   fds[0].revents = 0;
1396   int rc = poll(fds, 1, 0);
1397   return rc == 1;
1398 }
1399
1400 bool AsyncSocket::writable() const {
1401   if (fd_ == -1) {
1402     return false;
1403   }
1404   struct pollfd fds[1];
1405   fds[0].fd = fd_;
1406   fds[0].events = POLLOUT;
1407   fds[0].revents = 0;
1408   int rc = poll(fds, 1, 0);
1409   return rc == 1;
1410 }
1411
1412 bool AsyncSocket::isPending() const {
1413   return ioHandler_.isPending();
1414 }
1415
1416 bool AsyncSocket::hangup() const {
1417   if (fd_ == -1) {
1418     // sanity check, no one should ask for hangup if we are not connected.
1419     assert(false);
1420     return false;
1421   }
1422 #ifdef POLLRDHUP // Linux-only
1423   struct pollfd fds[1];
1424   fds[0].fd = fd_;
1425   fds[0].events = POLLRDHUP|POLLHUP;
1426   fds[0].revents = 0;
1427   poll(fds, 1, 0);
1428   return (fds[0].revents & (POLLRDHUP|POLLHUP)) != 0;
1429 #else
1430   return false;
1431 #endif
1432 }
1433
1434 bool AsyncSocket::good() const {
1435   return (
1436       (state_ == StateEnum::CONNECTING || state_ == StateEnum::FAST_OPEN ||
1437        state_ == StateEnum::ESTABLISHED) &&
1438       (shutdownFlags_ == 0) && (eventBase_ != nullptr));
1439 }
1440
1441 bool AsyncSocket::error() const {
1442   return (state_ == StateEnum::ERROR);
1443 }
1444
1445 void AsyncSocket::attachEventBase(EventBase* eventBase) {
1446   VLOG(5) << "AsyncSocket::attachEventBase(this=" << this << ", fd=" << fd_
1447           << ", old evb=" << eventBase_ << ", new evb=" << eventBase
1448           << ", state=" << state_ << ", events="
1449           << std::hex << eventFlags_ << ")";
1450   assert(eventBase_ == nullptr);
1451   eventBase->dcheckIsInEventBaseThread();
1452
1453   eventBase_ = eventBase;
1454   ioHandler_.attachEventBase(eventBase);
1455
1456   updateEventRegistration();
1457
1458   writeTimeout_.attachEventBase(eventBase);
1459   if (evbChangeCb_) {
1460     evbChangeCb_->evbAttached(this);
1461   }
1462 }
1463
1464 void AsyncSocket::detachEventBase() {
1465   VLOG(5) << "AsyncSocket::detachEventBase(this=" << this << ", fd=" << fd_
1466           << ", old evb=" << eventBase_ << ", state=" << state_
1467           << ", events=" << std::hex << eventFlags_ << ")";
1468   assert(eventBase_ != nullptr);
1469   eventBase_->dcheckIsInEventBaseThread();
1470
1471   eventBase_ = nullptr;
1472
1473   ioHandler_.unregisterHandler();
1474
1475   ioHandler_.detachEventBase();
1476   writeTimeout_.detachEventBase();
1477   if (evbChangeCb_) {
1478     evbChangeCb_->evbDetached(this);
1479   }
1480 }
1481
1482 bool AsyncSocket::isDetachable() const {
1483   DCHECK(eventBase_ != nullptr);
1484   eventBase_->dcheckIsInEventBaseThread();
1485
1486   return !writeTimeout_.isScheduled();
1487 }
1488
1489 void AsyncSocket::cacheAddresses() {
1490   if (fd_ >= 0) {
1491     try {
1492       cacheLocalAddress();
1493       cachePeerAddress();
1494     } catch (const std::system_error& e) {
1495       if (e.code() != std::error_code(ENOTCONN, std::system_category())) {
1496         VLOG(1) << "Error caching addresses: " << e.code().value() << ", "
1497                 << e.code().message();
1498       }
1499     }
1500   }
1501 }
1502
1503 void AsyncSocket::cacheLocalAddress() const {
1504   if (!localAddr_.isInitialized()) {
1505     localAddr_.setFromLocalAddress(fd_);
1506   }
1507 }
1508
1509 void AsyncSocket::cachePeerAddress() const {
1510   if (!addr_.isInitialized()) {
1511     addr_.setFromPeerAddress(fd_);
1512   }
1513 }
1514
1515 bool AsyncSocket::isZeroCopyWriteInProgress() const noexcept {
1516   eventBase_->dcheckIsInEventBaseThread();
1517   return (!idZeroCopyBufPtrMap_.empty());
1518 }
1519
1520 void AsyncSocket::getLocalAddress(folly::SocketAddress* address) const {
1521   cacheLocalAddress();
1522   *address = localAddr_;
1523 }
1524
1525 void AsyncSocket::getPeerAddress(folly::SocketAddress* address) const {
1526   cachePeerAddress();
1527   *address = addr_;
1528 }
1529
1530 bool AsyncSocket::getTFOSucceded() const {
1531   return detail::tfo_succeeded(fd_);
1532 }
1533
1534 int AsyncSocket::setNoDelay(bool noDelay) {
1535   if (fd_ < 0) {
1536     VLOG(4) << "AsyncSocket::setNoDelay() called on non-open socket "
1537                << this << "(state=" << state_ << ")";
1538     return EINVAL;
1539
1540   }
1541
1542   int value = noDelay ? 1 : 0;
1543   if (setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value)) != 0) {
1544     int errnoCopy = errno;
1545     VLOG(2) << "failed to update TCP_NODELAY option on AsyncSocket "
1546             << this << " (fd=" << fd_ << ", state=" << state_ << "): "
1547             << strerror(errnoCopy);
1548     return errnoCopy;
1549   }
1550
1551   return 0;
1552 }
1553
1554 int AsyncSocket::setCongestionFlavor(const std::string &cname) {
1555
1556   #ifndef TCP_CONGESTION
1557   #define TCP_CONGESTION  13
1558   #endif
1559
1560   if (fd_ < 0) {
1561     VLOG(4) << "AsyncSocket::setCongestionFlavor() called on non-open "
1562                << "socket " << this << "(state=" << state_ << ")";
1563     return EINVAL;
1564
1565   }
1566
1567   if (setsockopt(
1568           fd_,
1569           IPPROTO_TCP,
1570           TCP_CONGESTION,
1571           cname.c_str(),
1572           socklen_t(cname.length() + 1)) != 0) {
1573     int errnoCopy = errno;
1574     VLOG(2) << "failed to update TCP_CONGESTION option on AsyncSocket "
1575             << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1576             << strerror(errnoCopy);
1577     return errnoCopy;
1578   }
1579
1580   return 0;
1581 }
1582
1583 int AsyncSocket::setQuickAck(bool quickack) {
1584   (void)quickack;
1585   if (fd_ < 0) {
1586     VLOG(4) << "AsyncSocket::setQuickAck() called on non-open socket "
1587                << this << "(state=" << state_ << ")";
1588     return EINVAL;
1589
1590   }
1591
1592 #ifdef TCP_QUICKACK // Linux-only
1593   int value = quickack ? 1 : 0;
1594   if (setsockopt(fd_, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) != 0) {
1595     int errnoCopy = errno;
1596     VLOG(2) << "failed to update TCP_QUICKACK option on AsyncSocket"
1597             << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1598             << strerror(errnoCopy);
1599     return errnoCopy;
1600   }
1601
1602   return 0;
1603 #else
1604   return ENOSYS;
1605 #endif
1606 }
1607
1608 int AsyncSocket::setSendBufSize(size_t bufsize) {
1609   if (fd_ < 0) {
1610     VLOG(4) << "AsyncSocket::setSendBufSize() called on non-open socket "
1611                << this << "(state=" << state_ << ")";
1612     return EINVAL;
1613   }
1614
1615   if (setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) !=0) {
1616     int errnoCopy = errno;
1617     VLOG(2) << "failed to update SO_SNDBUF option on AsyncSocket"
1618             << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1619             << strerror(errnoCopy);
1620     return errnoCopy;
1621   }
1622
1623   return 0;
1624 }
1625
1626 int AsyncSocket::setRecvBufSize(size_t bufsize) {
1627   if (fd_ < 0) {
1628     VLOG(4) << "AsyncSocket::setRecvBufSize() called on non-open socket "
1629                << this << "(state=" << state_ << ")";
1630     return EINVAL;
1631   }
1632
1633   if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) !=0) {
1634     int errnoCopy = errno;
1635     VLOG(2) << "failed to update SO_RCVBUF option on AsyncSocket"
1636             << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1637             << strerror(errnoCopy);
1638     return errnoCopy;
1639   }
1640
1641   return 0;
1642 }
1643
1644 int AsyncSocket::setTCPProfile(int profd) {
1645   if (fd_ < 0) {
1646     VLOG(4) << "AsyncSocket::setTCPProfile() called on non-open socket "
1647                << this << "(state=" << state_ << ")";
1648     return EINVAL;
1649   }
1650
1651   if (setsockopt(fd_, SOL_SOCKET, SO_SET_NAMESPACE, &profd, sizeof(int)) !=0) {
1652     int errnoCopy = errno;
1653     VLOG(2) << "failed to set socket namespace option on AsyncSocket"
1654             << this << "(fd=" << fd_ << ", state=" << state_ << "): "
1655             << strerror(errnoCopy);
1656     return errnoCopy;
1657   }
1658
1659   return 0;
1660 }
1661
1662 void AsyncSocket::ioReady(uint16_t events) noexcept {
1663   VLOG(7) << "AsyncSocket::ioRead() this=" << this << ", fd=" << fd_
1664           << ", events=" << std::hex << events << ", state=" << state_;
1665   DestructorGuard dg(this);
1666   assert(events & EventHandler::READ_WRITE);
1667   eventBase_->dcheckIsInEventBaseThread();
1668
1669   uint16_t relevantEvents = uint16_t(events & EventHandler::READ_WRITE);
1670   EventBase* originalEventBase = eventBase_;
1671   // If we got there it means that either EventHandler::READ or
1672   // EventHandler::WRITE is set. Any of these flags can
1673   // indicate that there are messages available in the socket
1674   // error message queue.
1675   handleErrMessages();
1676
1677   // Return now if handleErrMessages() detached us from our EventBase
1678   if (eventBase_ != originalEventBase) {
1679     return;
1680   }
1681
1682   if (relevantEvents == EventHandler::READ) {
1683     handleRead();
1684   } else if (relevantEvents == EventHandler::WRITE) {
1685     handleWrite();
1686   } else if (relevantEvents == EventHandler::READ_WRITE) {
1687     // If both read and write events are ready, process writes first.
1688     handleWrite();
1689
1690     // Return now if handleWrite() detached us from our EventBase
1691     if (eventBase_ != originalEventBase) {
1692       return;
1693     }
1694
1695     // Only call handleRead() if a read callback is still installed.
1696     // (It's possible that the read callback was uninstalled during
1697     // handleWrite().)
1698     if (readCallback_) {
1699       handleRead();
1700     }
1701   } else {
1702     VLOG(4) << "AsyncSocket::ioRead() called with unexpected events "
1703                << std::hex << events << "(this=" << this << ")";
1704     abort();
1705   }
1706 }
1707
1708 AsyncSocket::ReadResult
1709 AsyncSocket::performRead(void** buf, size_t* buflen, size_t* /* offset */) {
1710   VLOG(5) << "AsyncSocket::performRead() this=" << this << ", buf=" << *buf
1711           << ", buflen=" << *buflen;
1712
1713   if (preReceivedData_ && !preReceivedData_->empty()) {
1714     VLOG(5) << "AsyncSocket::performRead() this=" << this
1715             << ", reading pre-received data";
1716
1717     io::Cursor cursor(preReceivedData_.get());
1718     auto len = cursor.pullAtMost(*buf, *buflen);
1719
1720     IOBufQueue queue;
1721     queue.append(std::move(preReceivedData_));
1722     queue.trimStart(len);
1723     preReceivedData_ = queue.move();
1724
1725     appBytesReceived_ += len;
1726     return ReadResult(len);
1727   }
1728
1729   ssize_t bytes = recv(fd_, *buf, *buflen, MSG_DONTWAIT);
1730   if (bytes < 0) {
1731     if (errno == EAGAIN || errno == EWOULDBLOCK) {
1732       // No more data to read right now.
1733       return ReadResult(READ_BLOCKING);
1734     } else {
1735       return ReadResult(READ_ERROR);
1736     }
1737   } else {
1738     appBytesReceived_ += bytes;
1739     return ReadResult(bytes);
1740   }
1741 }
1742
1743 void AsyncSocket::prepareReadBuffer(void** buf, size_t* buflen) {
1744   // no matter what, buffer should be preapared for non-ssl socket
1745   CHECK(readCallback_);
1746   readCallback_->getReadBuffer(buf, buflen);
1747 }
1748
1749 void AsyncSocket::handleErrMessages() noexcept {
1750   // This method has non-empty implementation only for platforms
1751   // supporting per-socket error queues.
1752   VLOG(5) << "AsyncSocket::handleErrMessages() this=" << this << ", fd=" << fd_
1753           << ", state=" << state_;
1754   if (errMessageCallback_ == nullptr && idZeroCopyBufPtrMap_.empty()) {
1755     VLOG(7) << "AsyncSocket::handleErrMessages(): "
1756             << "no callback installed - exiting.";
1757     return;
1758   }
1759
1760 #ifdef FOLLY_HAVE_MSG_ERRQUEUE
1761   uint8_t ctrl[1024];
1762   unsigned char data;
1763   struct msghdr msg;
1764   iovec entry;
1765
1766   entry.iov_base = &data;
1767   entry.iov_len = sizeof(data);
1768   msg.msg_iov = &entry;
1769   msg.msg_iovlen = 1;
1770   msg.msg_name = nullptr;
1771   msg.msg_namelen = 0;
1772   msg.msg_control = ctrl;
1773   msg.msg_controllen = sizeof(ctrl);
1774   msg.msg_flags = 0;
1775
1776   int ret;
1777   while (true) {
1778     ret = recvmsg(fd_, &msg, MSG_ERRQUEUE);
1779     VLOG(5) << "AsyncSocket::handleErrMessages(): recvmsg returned " << ret;
1780
1781     if (ret < 0) {
1782       if (errno != EAGAIN) {
1783         auto errnoCopy = errno;
1784         LOG(ERROR) << "::recvmsg exited with code " << ret
1785                    << ", errno: " << errnoCopy;
1786         AsyncSocketException ex(
1787           AsyncSocketException::INTERNAL_ERROR,
1788           withAddr("recvmsg() failed"),
1789           errnoCopy);
1790         failErrMessageRead(__func__, ex);
1791       }
1792       return;
1793     }
1794
1795     for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
1796          cmsg != nullptr && cmsg->cmsg_len != 0;
1797          cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1798       if (isZeroCopyMsg(*cmsg)) {
1799         processZeroCopyMsg(*cmsg);
1800       } else {
1801         if (errMessageCallback_) {
1802           errMessageCallback_->errMessage(*cmsg);
1803         }
1804       }
1805     }
1806   }
1807 #endif // FOLLY_HAVE_MSG_ERRQUEUE
1808 }
1809
1810 bool AsyncSocket::processZeroCopyWriteInProgress() noexcept {
1811   eventBase_->dcheckIsInEventBaseThread();
1812   if (idZeroCopyBufPtrMap_.empty()) {
1813     return true;
1814   }
1815
1816   handleErrMessages();
1817
1818   return idZeroCopyBufPtrMap_.empty();
1819 }
1820
1821 void AsyncSocket::handleRead() noexcept {
1822   VLOG(5) << "AsyncSocket::handleRead() this=" << this << ", fd=" << fd_
1823           << ", state=" << state_;
1824   assert(state_ == StateEnum::ESTABLISHED);
1825   assert((shutdownFlags_ & SHUT_READ) == 0);
1826   assert(readCallback_ != nullptr);
1827   assert(eventFlags_ & EventHandler::READ);
1828
1829   // Loop until:
1830   // - a read attempt would block
1831   // - readCallback_ is uninstalled
1832   // - the number of loop iterations exceeds the optional maximum
1833   // - this AsyncSocket is moved to another EventBase
1834   //
1835   // When we invoke readDataAvailable() it may uninstall the readCallback_,
1836   // which is why need to check for it here.
1837   //
1838   // The last bullet point is slightly subtle.  readDataAvailable() may also
1839   // detach this socket from this EventBase.  However, before
1840   // readDataAvailable() returns another thread may pick it up, attach it to
1841   // a different EventBase, and install another readCallback_.  We need to
1842   // exit immediately after readDataAvailable() returns if the eventBase_ has
1843   // changed.  (The caller must perform some sort of locking to transfer the
1844   // AsyncSocket between threads properly.  This will be sufficient to ensure
1845   // that this thread sees the updated eventBase_ variable after
1846   // readDataAvailable() returns.)
1847   uint16_t numReads = 0;
1848   EventBase* originalEventBase = eventBase_;
1849   while (readCallback_ && eventBase_ == originalEventBase) {
1850     // Get the buffer to read into.
1851     void* buf = nullptr;
1852     size_t buflen = 0, offset = 0;
1853     try {
1854       prepareReadBuffer(&buf, &buflen);
1855       VLOG(5) << "prepareReadBuffer() buf=" << buf << ", buflen=" << buflen;
1856     } catch (const AsyncSocketException& ex) {
1857       return failRead(__func__, ex);
1858     } catch (const std::exception& ex) {
1859       AsyncSocketException tex(AsyncSocketException::BAD_ARGS,
1860                               string("ReadCallback::getReadBuffer() "
1861                                      "threw exception: ") +
1862                               ex.what());
1863       return failRead(__func__, tex);
1864     } catch (...) {
1865       AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1866                              "ReadCallback::getReadBuffer() threw "
1867                              "non-exception type");
1868       return failRead(__func__, ex);
1869     }
1870     if (!isBufferMovable_ && (buf == nullptr || buflen == 0)) {
1871       AsyncSocketException ex(AsyncSocketException::BAD_ARGS,
1872                              "ReadCallback::getReadBuffer() returned "
1873                              "empty buffer");
1874       return failRead(__func__, ex);
1875     }
1876
1877     // Perform the read
1878     auto readResult = performRead(&buf, &buflen, &offset);
1879     auto bytesRead = readResult.readReturn;
1880     VLOG(4) << "this=" << this << ", AsyncSocket::handleRead() got "
1881             << bytesRead << " bytes";
1882     if (bytesRead > 0) {
1883       if (!isBufferMovable_) {
1884         readCallback_->readDataAvailable(size_t(bytesRead));
1885       } else {
1886         CHECK(kOpenSslModeMoveBufferOwnership);
1887         VLOG(5) << "this=" << this << ", AsyncSocket::handleRead() got "
1888                 << "buf=" << buf << ", " << bytesRead << "/" << buflen
1889                 << ", offset=" << offset;
1890         auto readBuf = folly::IOBuf::takeOwnership(buf, buflen);
1891         readBuf->trimStart(offset);
1892         readBuf->trimEnd(buflen - offset - bytesRead);
1893         readCallback_->readBufferAvailable(std::move(readBuf));
1894       }
1895
1896       // Fall through and continue around the loop if the read
1897       // completely filled the available buffer.
1898       // Note that readCallback_ may have been uninstalled or changed inside
1899       // readDataAvailable().
1900       if (size_t(bytesRead) < buflen) {
1901         return;
1902       }
1903     } else if (bytesRead == READ_BLOCKING) {
1904         // No more data to read right now.
1905         return;
1906     } else if (bytesRead == READ_ERROR) {
1907       readErr_ = READ_ERROR;
1908       if (readResult.exception) {
1909         return failRead(__func__, *readResult.exception);
1910       }
1911       auto errnoCopy = errno;
1912       AsyncSocketException ex(
1913           AsyncSocketException::INTERNAL_ERROR,
1914           withAddr("recv() failed"),
1915           errnoCopy);
1916       return failRead(__func__, ex);
1917     } else {
1918       assert(bytesRead == READ_EOF);
1919       readErr_ = READ_EOF;
1920       // EOF
1921       shutdownFlags_ |= SHUT_READ;
1922       if (!updateEventRegistration(0, EventHandler::READ)) {
1923         // we've already been moved into STATE_ERROR
1924         assert(state_ == StateEnum::ERROR);
1925         assert(readCallback_ == nullptr);
1926         return;
1927       }
1928
1929       ReadCallback* callback = readCallback_;
1930       readCallback_ = nullptr;
1931       callback->readEOF();
1932       return;
1933     }
1934     if (maxReadsPerEvent_ && (++numReads >= maxReadsPerEvent_)) {
1935       if (readCallback_ != nullptr) {
1936         // We might still have data in the socket.
1937         // (e.g. see comment in AsyncSSLSocket::checkForImmediateRead)
1938         scheduleImmediateRead();
1939       }
1940       return;
1941     }
1942   }
1943 }
1944
1945 /**
1946  * This function attempts to write as much data as possible, until no more data
1947  * can be written.
1948  *
1949  * - If it sends all available data, it unregisters for write events, and stops
1950  *   the writeTimeout_.
1951  *
1952  * - If not all of the data can be sent immediately, it reschedules
1953  *   writeTimeout_ (if a non-zero timeout is set), and ensures the handler is
1954  *   registered for write events.
1955  */
1956 void AsyncSocket::handleWrite() noexcept {
1957   VLOG(5) << "AsyncSocket::handleWrite() this=" << this << ", fd=" << fd_
1958           << ", state=" << state_;
1959   DestructorGuard dg(this);
1960
1961   if (state_ == StateEnum::CONNECTING) {
1962     handleConnect();
1963     return;
1964   }
1965
1966   // Normal write
1967   assert(state_ == StateEnum::ESTABLISHED);
1968   assert((shutdownFlags_ & SHUT_WRITE) == 0);
1969   assert(writeReqHead_ != nullptr);
1970
1971   // Loop until we run out of write requests,
1972   // or until this socket is moved to another EventBase.
1973   // (See the comment in handleRead() explaining how this can happen.)
1974   EventBase* originalEventBase = eventBase_;
1975   while (writeReqHead_ != nullptr && eventBase_ == originalEventBase) {
1976     auto writeResult = writeReqHead_->performWrite();
1977     if (writeResult.writeReturn < 0) {
1978       if (writeResult.exception) {
1979         return failWrite(__func__, *writeResult.exception);
1980       }
1981       auto errnoCopy = errno;
1982       AsyncSocketException ex(
1983           AsyncSocketException::INTERNAL_ERROR,
1984           withAddr("writev() failed"),
1985           errnoCopy);
1986       return failWrite(__func__, ex);
1987     } else if (writeReqHead_->isComplete()) {
1988       // We finished this request
1989       WriteRequest* req = writeReqHead_;
1990       writeReqHead_ = req->getNext();
1991
1992       if (writeReqHead_ == nullptr) {
1993         writeReqTail_ = nullptr;
1994         // This is the last write request.
1995         // Unregister for write events and cancel the send timer
1996         // before we invoke the callback.  We have to update the state properly
1997         // before calling the callback, since it may want to detach us from
1998         // the EventBase.
1999         if (eventFlags_ & EventHandler::WRITE) {
2000           if (!updateEventRegistration(0, EventHandler::WRITE)) {
2001             assert(state_ == StateEnum::ERROR);
2002             return;
2003           }
2004           // Stop the send timeout
2005           writeTimeout_.cancelTimeout();
2006         }
2007         assert(!writeTimeout_.isScheduled());
2008
2009         // If SHUT_WRITE_PENDING is set, we should shutdown the socket after
2010         // we finish sending the last write request.
2011         //
2012         // We have to do this before invoking writeSuccess(), since
2013         // writeSuccess() may detach us from our EventBase.
2014         if (shutdownFlags_ & SHUT_WRITE_PENDING) {
2015           assert(connectCallback_ == nullptr);
2016           shutdownFlags_ |= SHUT_WRITE;
2017
2018           if (shutdownFlags_ & SHUT_READ) {
2019             // Reads have already been shutdown.  Fully close the socket and
2020             // move to STATE_CLOSED.
2021             //
2022             // Note: This code currently moves us to STATE_CLOSED even if
2023             // close() hasn't ever been called.  This can occur if we have
2024             // received EOF from the peer and shutdownWrite() has been called
2025             // locally.  Should we bother staying in STATE_ESTABLISHED in this
2026             // case, until close() is actually called?  I can't think of a
2027             // reason why we would need to do so.  No other operations besides
2028             // calling close() or destroying the socket can be performed at
2029             // this point.
2030             assert(readCallback_ == nullptr);
2031             state_ = StateEnum::CLOSED;
2032             if (fd_ >= 0) {
2033               ioHandler_.changeHandlerFD(-1);
2034               doClose();
2035             }
2036           } else {
2037             // Reads are still enabled, so we are only doing a half-shutdown
2038             shutdown(fd_, SHUT_WR);
2039           }
2040         }
2041       }
2042
2043       // Invoke the callback
2044       WriteCallback* callback = req->getCallback();
2045       req->destroy();
2046       if (callback) {
2047         callback->writeSuccess();
2048       }
2049       // We'll continue around the loop, trying to write another request
2050     } else {
2051       // Partial write.
2052       if (bufferCallback_) {
2053         bufferCallback_->onEgressBuffered();
2054       }
2055       writeReqHead_->consume();
2056       // Stop after a partial write; it's highly likely that a subsequent write
2057       // attempt will just return EAGAIN.
2058       //
2059       // Ensure that we are registered for write events.
2060       if ((eventFlags_ & EventHandler::WRITE) == 0) {
2061         if (!updateEventRegistration(EventHandler::WRITE, 0)) {
2062           assert(state_ == StateEnum::ERROR);
2063           return;
2064         }
2065       }
2066
2067       // Reschedule the send timeout, since we have made some write progress.
2068       if (sendTimeout_ > 0) {
2069         if (!writeTimeout_.scheduleTimeout(sendTimeout_)) {
2070           AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
2071               withAddr("failed to reschedule write timeout"));
2072           return failWrite(__func__, ex);
2073         }
2074       }
2075       return;
2076     }
2077   }
2078   if (!writeReqHead_ && bufferCallback_) {
2079     bufferCallback_->onEgressBufferCleared();
2080   }
2081 }
2082
2083 void AsyncSocket::checkForImmediateRead() noexcept {
2084   // We currently don't attempt to perform optimistic reads in AsyncSocket.
2085   // (However, note that some subclasses do override this method.)
2086   //
2087   // Simply calling handleRead() here would be bad, as this would call
2088   // readCallback_->getReadBuffer(), forcing the callback to allocate a read
2089   // buffer even though no data may be available.  This would waste lots of
2090   // memory, since the buffer will sit around unused until the socket actually
2091   // becomes readable.
2092   //
2093   // Checking if the socket is readable now also seems like it would probably
2094   // be a pessimism.  In most cases it probably wouldn't be readable, and we
2095   // would just waste an extra system call.  Even if it is readable, waiting to
2096   // find out from libevent on the next event loop doesn't seem that bad.
2097   //
2098   // The exception to this is if we have pre-received data. In that case there
2099   // is definitely data available immediately.
2100   if (preReceivedData_ && !preReceivedData_->empty()) {
2101     handleRead();
2102   }
2103 }
2104
2105 void AsyncSocket::handleInitialReadWrite() noexcept {
2106   // Our callers should already be holding a DestructorGuard, but grab
2107   // one here just to make sure, in case one of our calling code paths ever
2108   // changes.
2109   DestructorGuard dg(this);
2110   // If we have a readCallback_, make sure we enable read events.  We
2111   // may already be registered for reads if connectSuccess() set
2112   // the read calback.
2113   if (readCallback_ && !(eventFlags_ & EventHandler::READ)) {
2114     assert(state_ == StateEnum::ESTABLISHED);
2115     assert((shutdownFlags_ & SHUT_READ) == 0);
2116     if (!updateEventRegistration(EventHandler::READ, 0)) {
2117       assert(state_ == StateEnum::ERROR);
2118       return;
2119     }
2120     checkForImmediateRead();
2121   } else if (readCallback_ == nullptr) {
2122     // Unregister for read events.
2123     updateEventRegistration(0, EventHandler::READ);
2124   }
2125
2126   // If we have write requests pending, try to send them immediately.
2127   // Since we just finished accepting, there is a very good chance that we can
2128   // write without blocking.
2129   //
2130   // However, we only process them if EventHandler::WRITE is not already set,
2131   // which means that we're already blocked on a write attempt.  (This can
2132   // happen if connectSuccess() called write() before returning.)
2133   if (writeReqHead_ && !(eventFlags_ & EventHandler::WRITE)) {
2134     // Call handleWrite() to perform write processing.
2135     handleWrite();
2136   } else if (writeReqHead_ == nullptr) {
2137     // Unregister for write event.
2138     updateEventRegistration(0, EventHandler::WRITE);
2139   }
2140 }
2141
2142 void AsyncSocket::handleConnect() noexcept {
2143   VLOG(5) << "AsyncSocket::handleConnect() this=" << this << ", fd=" << fd_
2144           << ", state=" << state_;
2145   assert(state_ == StateEnum::CONNECTING);
2146   // SHUT_WRITE can never be set while we are still connecting;
2147   // SHUT_WRITE_PENDING may be set, be we only set SHUT_WRITE once the connect
2148   // finishes
2149   assert((shutdownFlags_ & SHUT_WRITE) == 0);
2150
2151   // In case we had a connect timeout, cancel the timeout
2152   writeTimeout_.cancelTimeout();
2153   // We don't use a persistent registration when waiting on a connect event,
2154   // so we have been automatically unregistered now.  Update eventFlags_ to
2155   // reflect reality.
2156   assert(eventFlags_ == EventHandler::WRITE);
2157   eventFlags_ = EventHandler::NONE;
2158
2159   // Call getsockopt() to check if the connect succeeded
2160   int error;
2161   socklen_t len = sizeof(error);
2162   int rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &len);
2163   if (rv != 0) {
2164     auto errnoCopy = errno;
2165     AsyncSocketException ex(
2166         AsyncSocketException::INTERNAL_ERROR,
2167         withAddr("error calling getsockopt() after connect"),
2168         errnoCopy);
2169     VLOG(4) << "AsyncSocket::handleConnect(this=" << this << ", fd="
2170                << fd_ << " host=" << addr_.describe()
2171                << ") exception:" << ex.what();
2172     return failConnect(__func__, ex);
2173   }
2174
2175   if (error != 0) {
2176     AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2177                            "connect failed", error);
2178     VLOG(1) << "AsyncSocket::handleConnect(this=" << this << ", fd="
2179             << fd_ << " host=" << addr_.describe()
2180             << ") exception: " << ex.what();
2181     return failConnect(__func__, ex);
2182   }
2183
2184   // Move into STATE_ESTABLISHED
2185   state_ = StateEnum::ESTABLISHED;
2186
2187   // If SHUT_WRITE_PENDING is set and we don't have any write requests to
2188   // perform, immediately shutdown the write half of the socket.
2189   if ((shutdownFlags_ & SHUT_WRITE_PENDING) && writeReqHead_ == nullptr) {
2190     // SHUT_READ shouldn't be set.  If close() is called on the socket while we
2191     // are still connecting we just abort the connect rather than waiting for
2192     // it to complete.
2193     assert((shutdownFlags_ & SHUT_READ) == 0);
2194     shutdown(fd_, SHUT_WR);
2195     shutdownFlags_ |= SHUT_WRITE;
2196   }
2197
2198   VLOG(7) << "AsyncSocket " << this << ": fd " << fd_
2199           << "successfully connected; state=" << state_;
2200
2201   // Remember the EventBase we are attached to, before we start invoking any
2202   // callbacks (since the callbacks may call detachEventBase()).
2203   EventBase* originalEventBase = eventBase_;
2204
2205   invokeConnectSuccess();
2206   // Note that the connect callback may have changed our state.
2207   // (set or unset the read callback, called write(), closed the socket, etc.)
2208   // The following code needs to handle these situations correctly.
2209   //
2210   // If the socket has been closed, readCallback_ and writeReqHead_ will
2211   // always be nullptr, so that will prevent us from trying to read or write.
2212   //
2213   // The main thing to check for is if eventBase_ is still originalEventBase.
2214   // If not, we have been detached from this event base, so we shouldn't
2215   // perform any more operations.
2216   if (eventBase_ != originalEventBase) {
2217     return;
2218   }
2219
2220   handleInitialReadWrite();
2221 }
2222
2223 void AsyncSocket::timeoutExpired() noexcept {
2224   VLOG(7) << "AsyncSocket " << this << ", fd " << fd_ << ": timeout expired: "
2225           << "state=" << state_ << ", events=" << std::hex << eventFlags_;
2226   DestructorGuard dg(this);
2227   eventBase_->dcheckIsInEventBaseThread();
2228
2229   if (state_ == StateEnum::CONNECTING) {
2230     // connect() timed out
2231     // Unregister for I/O events.
2232     if (connectCallback_) {
2233       AsyncSocketException ex(
2234           AsyncSocketException::TIMED_OUT,
2235           folly::sformat(
2236               "connect timed out after {}ms", connectTimeout_.count()));
2237       failConnect(__func__, ex);
2238     } else {
2239       // we faced a connect error without a connect callback, which could
2240       // happen due to TFO.
2241       AsyncSocketException ex(
2242           AsyncSocketException::TIMED_OUT, "write timed out during connection");
2243       failWrite(__func__, ex);
2244     }
2245   } else {
2246     // a normal write operation timed out
2247     AsyncSocketException ex(
2248         AsyncSocketException::TIMED_OUT,
2249         folly::sformat("write timed out after {}ms", sendTimeout_));
2250     failWrite(__func__, ex);
2251   }
2252 }
2253
2254 ssize_t AsyncSocket::tfoSendMsg(int fd, struct msghdr* msg, int msg_flags) {
2255   return detail::tfo_sendmsg(fd, msg, msg_flags);
2256 }
2257
2258 AsyncSocket::WriteResult
2259 AsyncSocket::sendSocketMessage(int fd, struct msghdr* msg, int msg_flags) {
2260   ssize_t totalWritten = 0;
2261   if (state_ == StateEnum::FAST_OPEN) {
2262     sockaddr_storage addr;
2263     auto len = addr_.getAddress(&addr);
2264     msg->msg_name = &addr;
2265     msg->msg_namelen = len;
2266     totalWritten = tfoSendMsg(fd_, msg, msg_flags);
2267     if (totalWritten >= 0) {
2268       tfoFinished_ = true;
2269       state_ = StateEnum::ESTABLISHED;
2270       // We schedule this asynchrously so that we don't end up
2271       // invoking initial read or write while a write is in progress.
2272       scheduleInitialReadWrite();
2273     } else if (errno == EINPROGRESS) {
2274       VLOG(4) << "TFO falling back to connecting";
2275       // A normal sendmsg doesn't return EINPROGRESS, however
2276       // TFO might fallback to connecting if there is no
2277       // cookie.
2278       state_ = StateEnum::CONNECTING;
2279       try {
2280         scheduleConnectTimeout();
2281         registerForConnectEvents();
2282       } catch (const AsyncSocketException& ex) {
2283         return WriteResult(
2284             WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
2285       }
2286       // Let's fake it that no bytes were written and return an errno.
2287       errno = EAGAIN;
2288       totalWritten = -1;
2289     } else if (errno == EOPNOTSUPP) {
2290       // Try falling back to connecting.
2291       VLOG(4) << "TFO not supported";
2292       state_ = StateEnum::CONNECTING;
2293       try {
2294         int ret = socketConnect((const sockaddr*)&addr, len);
2295         if (ret == 0) {
2296           // connect succeeded immediately
2297           // Treat this like no data was written.
2298           state_ = StateEnum::ESTABLISHED;
2299           scheduleInitialReadWrite();
2300         }
2301         // If there was no exception during connections,
2302         // we would return that no bytes were written.
2303         errno = EAGAIN;
2304         totalWritten = -1;
2305       } catch (const AsyncSocketException& ex) {
2306         return WriteResult(
2307             WRITE_ERROR, std::make_unique<AsyncSocketException>(ex));
2308       }
2309     } else if (errno == EAGAIN) {
2310       // Normally sendmsg would indicate that the write would block.
2311       // However in the fast open case, it would indicate that sendmsg
2312       // fell back to a connect. This is a return code from connect()
2313       // instead, and is an error condition indicating no fds available.
2314       return WriteResult(
2315           WRITE_ERROR,
2316           std::make_unique<AsyncSocketException>(
2317               AsyncSocketException::UNKNOWN, "No more free local ports"));
2318     }
2319   } else {
2320     totalWritten = ::sendmsg(fd, msg, msg_flags);
2321   }
2322   return WriteResult(totalWritten);
2323 }
2324
2325 AsyncSocket::WriteResult AsyncSocket::performWrite(
2326     const iovec* vec,
2327     uint32_t count,
2328     WriteFlags flags,
2329     uint32_t* countWritten,
2330     uint32_t* partialWritten) {
2331   // We use sendmsg() instead of writev() so that we can pass in MSG_NOSIGNAL
2332   // We correctly handle EPIPE errors, so we never want to receive SIGPIPE
2333   // (since it may terminate the program if the main program doesn't explicitly
2334   // ignore it).
2335   struct msghdr msg;
2336   msg.msg_name = nullptr;
2337   msg.msg_namelen = 0;
2338   msg.msg_iov = const_cast<iovec *>(vec);
2339   msg.msg_iovlen = std::min<size_t>(count, kIovMax);
2340   msg.msg_flags = 0;
2341   msg.msg_controllen = sendMsgParamCallback_->getAncillaryDataSize(flags);
2342   CHECK_GE(AsyncSocket::SendMsgParamsCallback::maxAncillaryDataSize,
2343            msg.msg_controllen);
2344
2345   if (msg.msg_controllen != 0) {
2346     msg.msg_control = reinterpret_cast<char*>(alloca(msg.msg_controllen));
2347     sendMsgParamCallback_->getAncillaryData(flags, msg.msg_control);
2348   } else {
2349     msg.msg_control = nullptr;
2350   }
2351   int msg_flags = sendMsgParamCallback_->getFlags(flags, zeroCopyEnabled_);
2352
2353   auto writeResult = sendSocketMessage(fd_, &msg, msg_flags);
2354   auto totalWritten = writeResult.writeReturn;
2355   if (totalWritten < 0) {
2356     bool tryAgain = (errno == EAGAIN);
2357 #ifdef __APPLE__
2358     // Apple has a bug where doing a second write on a socket which we
2359     // have opened with TFO causes an ENOTCONN to be thrown. However the
2360     // socket is really connected, so treat ENOTCONN as a EAGAIN until
2361     // this bug is fixed.
2362     tryAgain |= (errno == ENOTCONN);
2363 #endif
2364
2365     // workaround for running with zerocopy enabled but without a proper
2366     // memlock value - see ulimit -l
2367     if (zeroCopyEnabled_ && (errno == ENOBUFS)) {
2368       tryAgain = true;
2369       zeroCopyEnabled_ = false;
2370     }
2371
2372     if (!writeResult.exception && tryAgain) {
2373       // TCP buffer is full; we can't write any more data right now.
2374       *countWritten = 0;
2375       *partialWritten = 0;
2376       return WriteResult(0);
2377     }
2378     // error
2379     *countWritten = 0;
2380     *partialWritten = 0;
2381     return writeResult;
2382   }
2383
2384   appBytesWritten_ += totalWritten;
2385
2386   uint32_t bytesWritten;
2387   uint32_t n;
2388   for (bytesWritten = uint32_t(totalWritten), n = 0; n < count; ++n) {
2389     const iovec* v = vec + n;
2390     if (v->iov_len > bytesWritten) {
2391       // Partial write finished in the middle of this iovec
2392       *countWritten = n;
2393       *partialWritten = bytesWritten;
2394       return WriteResult(totalWritten);
2395     }
2396
2397     bytesWritten -= uint32_t(v->iov_len);
2398   }
2399
2400   assert(bytesWritten == 0);
2401   *countWritten = n;
2402   *partialWritten = 0;
2403   return WriteResult(totalWritten);
2404 }
2405
2406 /**
2407  * Re-register the EventHandler after eventFlags_ has changed.
2408  *
2409  * If an error occurs, fail() is called to move the socket into the error state
2410  * and call all currently installed callbacks.  After an error, the
2411  * AsyncSocket is completely unregistered.
2412  *
2413  * @return Returns true on success, or false on error.
2414  */
2415 bool AsyncSocket::updateEventRegistration() {
2416   VLOG(5) << "AsyncSocket::updateEventRegistration(this=" << this
2417           << ", fd=" << fd_ << ", evb=" << eventBase_ << ", state=" << state_
2418           << ", events=" << std::hex << eventFlags_;
2419   eventBase_->dcheckIsInEventBaseThread();
2420   if (eventFlags_ == EventHandler::NONE) {
2421     ioHandler_.unregisterHandler();
2422     return true;
2423   }
2424
2425   // Always register for persistent events, so we don't have to re-register
2426   // after being called back.
2427   if (!ioHandler_.registerHandler(
2428           uint16_t(eventFlags_ | EventHandler::PERSIST))) {
2429     eventFlags_ = EventHandler::NONE; // we're not registered after error
2430     AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
2431         withAddr("failed to update AsyncSocket event registration"));
2432     fail("updateEventRegistration", ex);
2433     return false;
2434   }
2435
2436   return true;
2437 }
2438
2439 bool AsyncSocket::updateEventRegistration(uint16_t enable,
2440                                            uint16_t disable) {
2441   uint16_t oldFlags = eventFlags_;
2442   eventFlags_ |= enable;
2443   eventFlags_ &= ~disable;
2444   if (eventFlags_ == oldFlags) {
2445     return true;
2446   } else {
2447     return updateEventRegistration();
2448   }
2449 }
2450
2451 void AsyncSocket::startFail() {
2452   // startFail() should only be called once
2453   assert(state_ != StateEnum::ERROR);
2454   assert(getDestructorGuardCount() > 0);
2455   state_ = StateEnum::ERROR;
2456   // Ensure that SHUT_READ and SHUT_WRITE are set,
2457   // so all future attempts to read or write will be rejected
2458   shutdownFlags_ |= (SHUT_READ | SHUT_WRITE);
2459
2460   if (eventFlags_ != EventHandler::NONE) {
2461     eventFlags_ = EventHandler::NONE;
2462     ioHandler_.unregisterHandler();
2463   }
2464   writeTimeout_.cancelTimeout();
2465
2466   if (fd_ >= 0) {
2467     ioHandler_.changeHandlerFD(-1);
2468     doClose();
2469   }
2470 }
2471
2472 void AsyncSocket::invokeAllErrors(const AsyncSocketException& ex) {
2473   invokeConnectErr(ex);
2474   failAllWrites(ex);
2475
2476   if (readCallback_) {
2477     ReadCallback* callback = readCallback_;
2478     readCallback_ = nullptr;
2479     callback->readErr(ex);
2480   }
2481 }
2482
2483 void AsyncSocket::finishFail() {
2484   assert(state_ == StateEnum::ERROR);
2485   assert(getDestructorGuardCount() > 0);
2486
2487   AsyncSocketException ex(
2488       AsyncSocketException::INTERNAL_ERROR,
2489       withAddr("socket closing after error"));
2490   invokeAllErrors(ex);
2491 }
2492
2493 void AsyncSocket::finishFail(const AsyncSocketException& ex) {
2494   assert(state_ == StateEnum::ERROR);
2495   assert(getDestructorGuardCount() > 0);
2496   invokeAllErrors(ex);
2497 }
2498
2499 void AsyncSocket::fail(const char* fn, const AsyncSocketException& ex) {
2500   VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2501              << state_ << " host=" << addr_.describe()
2502              << "): failed in " << fn << "(): "
2503              << ex.what();
2504   startFail();
2505   finishFail();
2506 }
2507
2508 void AsyncSocket::failConnect(const char* fn, const AsyncSocketException& ex) {
2509   VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2510                << state_ << " host=" << addr_.describe()
2511                << "): failed while connecting in " << fn << "(): "
2512                << ex.what();
2513   startFail();
2514
2515   invokeConnectErr(ex);
2516   finishFail(ex);
2517 }
2518
2519 void AsyncSocket::failRead(const char* fn, const AsyncSocketException& ex) {
2520   VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2521                << state_ << " host=" << addr_.describe()
2522                << "): failed while reading in " << fn << "(): "
2523                << ex.what();
2524   startFail();
2525
2526   if (readCallback_ != nullptr) {
2527     ReadCallback* callback = readCallback_;
2528     readCallback_ = nullptr;
2529     callback->readErr(ex);
2530   }
2531
2532   finishFail();
2533 }
2534
2535 void AsyncSocket::failErrMessageRead(const char* fn,
2536                                      const AsyncSocketException& ex) {
2537   VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2538                << state_ << " host=" << addr_.describe()
2539                << "): failed while reading message in " << fn << "(): "
2540                << ex.what();
2541   startFail();
2542
2543   if (errMessageCallback_ != nullptr) {
2544     ErrMessageCallback* callback = errMessageCallback_;
2545     errMessageCallback_ = nullptr;
2546     callback->errMessageError(ex);
2547   }
2548
2549   finishFail();
2550 }
2551
2552 void AsyncSocket::failWrite(const char* fn, const AsyncSocketException& ex) {
2553   VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2554                << state_ << " host=" << addr_.describe()
2555                << "): failed while writing in " << fn << "(): "
2556                << ex.what();
2557   startFail();
2558
2559   // Only invoke the first write callback, since the error occurred while
2560   // writing this request.  Let any other pending write callbacks be invoked in
2561   // finishFail().
2562   if (writeReqHead_ != nullptr) {
2563     WriteRequest* req = writeReqHead_;
2564     writeReqHead_ = req->getNext();
2565     WriteCallback* callback = req->getCallback();
2566     uint32_t bytesWritten = req->getTotalBytesWritten();
2567     req->destroy();
2568     if (callback) {
2569       callback->writeErr(bytesWritten, ex);
2570     }
2571   }
2572
2573   finishFail();
2574 }
2575
2576 void AsyncSocket::failWrite(const char* fn, WriteCallback* callback,
2577                              size_t bytesWritten,
2578                              const AsyncSocketException& ex) {
2579   // This version of failWrite() is used when the failure occurs before
2580   // we've added the callback to writeReqHead_.
2581   VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_ << ", state="
2582              << state_ << " host=" << addr_.describe()
2583              <<"): failed while writing in " << fn << "(): "
2584              << ex.what();
2585   startFail();
2586
2587   if (callback != nullptr) {
2588     callback->writeErr(bytesWritten, ex);
2589   }
2590
2591   finishFail();
2592 }
2593
2594 void AsyncSocket::failAllWrites(const AsyncSocketException& ex) {
2595   // Invoke writeError() on all write callbacks.
2596   // This is used when writes are forcibly shutdown with write requests
2597   // pending, or when an error occurs with writes pending.
2598   while (writeReqHead_ != nullptr) {
2599     WriteRequest* req = writeReqHead_;
2600     writeReqHead_ = req->getNext();
2601     WriteCallback* callback = req->getCallback();
2602     if (callback) {
2603       callback->writeErr(req->getTotalBytesWritten(), ex);
2604     }
2605     req->destroy();
2606   }
2607 }
2608
2609 void AsyncSocket::invalidState(ConnectCallback* callback) {
2610   VLOG(5) << "AsyncSocket(this=" << this << ", fd=" << fd_
2611           << "): connect() called in invalid state " << state_;
2612
2613   /*
2614    * The invalidState() methods don't use the normal failure mechanisms,
2615    * since we don't know what state we are in.  We don't want to call
2616    * startFail()/finishFail() recursively if we are already in the middle of
2617    * cleaning up.
2618    */
2619
2620   AsyncSocketException ex(AsyncSocketException::ALREADY_OPEN,
2621                          "connect() called with socket in invalid state");
2622   connectEndTime_ = std::chrono::steady_clock::now();
2623   if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2624     if (callback) {
2625       callback->connectErr(ex);
2626     }
2627   } else {
2628     // We can't use failConnect() here since connectCallback_
2629     // may already be set to another callback.  Invoke this ConnectCallback
2630     // here; any other connectCallback_ will be invoked in finishFail()
2631     startFail();
2632     if (callback) {
2633       callback->connectErr(ex);
2634     }
2635     finishFail();
2636   }
2637 }
2638
2639 void AsyncSocket::invalidState(ErrMessageCallback* callback) {
2640   VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2641           << "): setErrMessageCB(" << callback
2642           << ") called in invalid state " << state_;
2643
2644   AsyncSocketException ex(
2645       AsyncSocketException::NOT_OPEN,
2646       msgErrQueueSupported
2647       ? "setErrMessageCB() called with socket in invalid state"
2648       : "This platform does not support socket error message notifications");
2649   if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2650     if (callback) {
2651       callback->errMessageError(ex);
2652     }
2653   } else {
2654     startFail();
2655     if (callback) {
2656       callback->errMessageError(ex);
2657     }
2658     finishFail();
2659   }
2660 }
2661
2662 void AsyncSocket::invokeConnectErr(const AsyncSocketException& ex) {
2663   connectEndTime_ = std::chrono::steady_clock::now();
2664   if (connectCallback_) {
2665     ConnectCallback* callback = connectCallback_;
2666     connectCallback_ = nullptr;
2667     callback->connectErr(ex);
2668   }
2669 }
2670
2671 void AsyncSocket::invokeConnectSuccess() {
2672   connectEndTime_ = std::chrono::steady_clock::now();
2673   if (connectCallback_) {
2674     ConnectCallback* callback = connectCallback_;
2675     connectCallback_ = nullptr;
2676     callback->connectSuccess();
2677   }
2678 }
2679
2680 void AsyncSocket::invalidState(ReadCallback* callback) {
2681   VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2682              << "): setReadCallback(" << callback
2683              << ") called in invalid state " << state_;
2684
2685   AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2686                          "setReadCallback() called with socket in "
2687                          "invalid state");
2688   if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2689     if (callback) {
2690       callback->readErr(ex);
2691     }
2692   } else {
2693     startFail();
2694     if (callback) {
2695       callback->readErr(ex);
2696     }
2697     finishFail();
2698   }
2699 }
2700
2701 void AsyncSocket::invalidState(WriteCallback* callback) {
2702   VLOG(4) << "AsyncSocket(this=" << this << ", fd=" << fd_
2703              << "): write() called in invalid state " << state_;
2704
2705   AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
2706                          withAddr("write() called with socket in invalid state"));
2707   if (state_ == StateEnum::CLOSED || state_ == StateEnum::ERROR) {
2708     if (callback) {
2709       callback->writeErr(0, ex);
2710     }
2711   } else {
2712     startFail();
2713     if (callback) {
2714       callback->writeErr(0, ex);
2715     }
2716     finishFail();
2717   }
2718 }
2719
2720 void AsyncSocket::doClose() {
2721   if (fd_ == -1) {
2722     return;
2723   }
2724   if (const auto shutdownSocketSet = wShutdownSocketSet_.lock()) {
2725     shutdownSocketSet->close(fd_);
2726   } else {
2727     ::close(fd_);
2728   }
2729   fd_ = -1;
2730 }
2731
2732 std::ostream& operator << (std::ostream& os,
2733                            const AsyncSocket::StateEnum& state) {
2734   os << static_cast<int>(state);
2735   return os;
2736 }
2737
2738 std::string AsyncSocket::withAddr(const std::string& s) {
2739   // Don't use addr_ directly because it may not be initialized
2740   // e.g. if constructed from fd
2741   folly::SocketAddress peer, local;
2742   try {
2743     getPeerAddress(&peer);
2744     getLocalAddress(&local);
2745   } catch (const std::exception&) {
2746     // ignore
2747   } catch (...) {
2748     // ignore
2749   }
2750   return s + " (peer=" + peer.describe() + ", local=" + local.describe() + ")";
2751 }
2752
2753 void AsyncSocket::setBufferCallback(BufferCallback* cb) {
2754   bufferCallback_ = cb;
2755 }
2756
2757 } // namespace folly