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