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