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