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