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