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