Make DestructorCheck::Safety no-copy, no-move
[folly.git] / folly / io / async / AsyncServerSocket.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 #ifndef __STDC_FORMAT_MACROS
18   #define __STDC_FORMAT_MACROS
19 #endif
20
21 #include <folly/io/async/AsyncServerSocket.h>
22
23 #include <folly/FileUtil.h>
24 #include <folly/Portability.h>
25 #include <folly/SocketAddress.h>
26 #include <folly/String.h>
27 #include <folly/detail/SocketFastOpen.h>
28 #include <folly/io/async/EventBase.h>
29 #include <folly/io/async/NotificationQueue.h>
30 #include <folly/portability/Fcntl.h>
31 #include <folly/portability/Sockets.h>
32 #include <folly/portability/Unistd.h>
33
34 #include <errno.h>
35 #include <string.h>
36 #include <sys/types.h>
37
38 namespace fsp = folly::portability::sockets;
39
40 namespace folly {
41
42 const uint32_t AsyncServerSocket::kDefaultMaxAcceptAtOnce;
43 const uint32_t AsyncServerSocket::kDefaultCallbackAcceptAtOnce;
44 const uint32_t AsyncServerSocket::kDefaultMaxMessagesInQueue;
45
46 int setCloseOnExec(int fd, int value) {
47   // Read the current flags
48   int old_flags = fcntl(fd, F_GETFD, 0);
49
50   // If reading the flags failed, return error indication now
51   if (old_flags < 0)
52     return -1;
53
54   // Set just the flag we want to set
55   int new_flags;
56   if (value != 0)
57     new_flags = old_flags | FD_CLOEXEC;
58   else
59     new_flags = old_flags & ~FD_CLOEXEC;
60
61   // Store modified flag word in the descriptor
62   return fcntl(fd, F_SETFD, new_flags);
63 }
64
65 void AsyncServerSocket::RemoteAcceptor::start(
66   EventBase* eventBase, uint32_t maxAtOnce, uint32_t maxInQueue) {
67   setMaxReadAtOnce(maxAtOnce);
68   queue_.setMaxQueueSize(maxInQueue);
69
70   if (!eventBase->runInEventBaseThread([=](){
71         callback_->acceptStarted();
72         this->startConsuming(eventBase, &queue_);
73       })) {
74     throw std::invalid_argument("unable to start waiting on accept "
75                             "notification queue in the specified "
76                             "EventBase thread");
77   }
78 }
79
80 void AsyncServerSocket::RemoteAcceptor::stop(
81   EventBase* eventBase, AcceptCallback* callback) {
82   if (!eventBase->runInEventBaseThread([=](){
83         callback->acceptStopped();
84         delete this;
85       })) {
86     throw std::invalid_argument("unable to start waiting on accept "
87                             "notification queue in the specified "
88                             "EventBase thread");
89   }
90 }
91
92 void AsyncServerSocket::RemoteAcceptor::messageAvailable(
93     QueueMessage&& msg) noexcept {
94   switch (msg.type) {
95     case MessageType::MSG_NEW_CONN:
96     {
97       if (connectionEventCallback_) {
98         connectionEventCallback_->onConnectionDequeuedByAcceptorCallback(
99             msg.fd, msg.address);
100       }
101       callback_->connectionAccepted(msg.fd, msg.address);
102       break;
103     }
104     case MessageType::MSG_ERROR:
105     {
106       std::runtime_error ex(msg.msg);
107       callback_->acceptError(ex);
108       break;
109     }
110     default:
111     {
112       LOG(ERROR) << "invalid accept notification message type "
113                  << int(msg.type);
114       std::runtime_error ex(
115         "received invalid accept notification message type");
116       callback_->acceptError(ex);
117     }
118   }
119 }
120
121 /*
122  * AsyncServerSocket::BackoffTimeout
123  */
124 class AsyncServerSocket::BackoffTimeout : public AsyncTimeout {
125  public:
126   // Disallow copy, move, and default constructors.
127   BackoffTimeout(BackoffTimeout&&) = delete;
128   explicit BackoffTimeout(AsyncServerSocket* socket)
129       : AsyncTimeout(socket->getEventBase()), socket_(socket) {}
130
131   void timeoutExpired() noexcept override { socket_->backoffTimeoutExpired(); }
132
133  private:
134   AsyncServerSocket* socket_;
135 };
136
137 /*
138  * AsyncServerSocket methods
139  */
140
141 AsyncServerSocket::AsyncServerSocket(EventBase* eventBase)
142 :   eventBase_(eventBase),
143     accepting_(false),
144     maxAcceptAtOnce_(kDefaultMaxAcceptAtOnce),
145     maxNumMsgsInQueue_(kDefaultMaxMessagesInQueue),
146     acceptRateAdjustSpeed_(0),
147     acceptRate_(1),
148     lastAccepTimestamp_(std::chrono::steady_clock::now()),
149     numDroppedConnections_(0),
150     callbackIndex_(0),
151     backoffTimeout_(nullptr),
152     callbacks_(),
153     keepAliveEnabled_(true),
154     closeOnExec_(true),
155     shutdownSocketSet_(nullptr) {
156 }
157
158 void AsyncServerSocket::setShutdownSocketSet(ShutdownSocketSet* newSS) {
159   if (shutdownSocketSet_ == newSS) {
160     return;
161   }
162   if (shutdownSocketSet_) {
163     for (auto& h : sockets_) {
164       shutdownSocketSet_->remove(h.socket_);
165     }
166   }
167   shutdownSocketSet_ = newSS;
168   if (shutdownSocketSet_) {
169     for (auto& h : sockets_) {
170       shutdownSocketSet_->add(h.socket_);
171     }
172   }
173 }
174
175 AsyncServerSocket::~AsyncServerSocket() {
176   assert(callbacks_.empty());
177 }
178
179 int AsyncServerSocket::stopAccepting(int shutdownFlags) {
180   int result = 0;
181   for (auto& handler : sockets_) {
182     VLOG(10) << "AsyncServerSocket::stopAccepting " << this <<
183               handler.socket_;
184   }
185   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
186
187   // When destroy is called, unregister and close the socket immediately.
188   accepting_ = false;
189
190   // Close the sockets in reverse order as they were opened to avoid
191   // the condition where another process concurrently tries to open
192   // the same port, succeed to bind the first socket but fails on the
193   // second because it hasn't been closed yet.
194   for (; !sockets_.empty(); sockets_.pop_back()) {
195     auto& handler = sockets_.back();
196     handler.unregisterHandler();
197     if (shutdownSocketSet_) {
198       shutdownSocketSet_->close(handler.socket_);
199     } else if (shutdownFlags >= 0) {
200       result = shutdownNoInt(handler.socket_, shutdownFlags);
201       pendingCloseSockets_.push_back(handler.socket_);
202     } else {
203       closeNoInt(handler.socket_);
204     }
205   }
206
207   // Destroy the backoff timout.  This will cancel it if it is running.
208   delete backoffTimeout_;
209   backoffTimeout_ = nullptr;
210
211   // Close all of the callback queues to notify them that they are being
212   // destroyed.  No one should access the AsyncServerSocket any more once
213   // destroy() is called.  However, clear out callbacks_ before invoking the
214   // accept callbacks just in case.  This will potentially help us detect the
215   // bug if one of the callbacks calls addAcceptCallback() or
216   // removeAcceptCallback().
217   std::vector<CallbackInfo> callbacksCopy;
218   callbacks_.swap(callbacksCopy);
219   for (std::vector<CallbackInfo>::iterator it = callbacksCopy.begin();
220        it != callbacksCopy.end();
221        ++it) {
222     // consumer may not be set if we are running in primary event base
223     if (it->consumer) {
224       DCHECK(it->eventBase);
225       it->consumer->stop(it->eventBase, it->callback);
226     } else {
227       DCHECK(it->callback);
228       it->callback->acceptStopped();
229     }
230   }
231
232   return result;
233 }
234
235 void AsyncServerSocket::destroy() {
236   stopAccepting();
237   for (auto s : pendingCloseSockets_) {
238     closeNoInt(s);
239   }
240   // Then call DelayedDestruction::destroy() to take care of
241   // whether or not we need immediate or delayed destruction
242   DelayedDestruction::destroy();
243 }
244
245 void AsyncServerSocket::attachEventBase(EventBase *eventBase) {
246   assert(eventBase_ == nullptr);
247   assert(eventBase->isInEventBaseThread());
248
249   eventBase_ = eventBase;
250   for (auto& handler : sockets_) {
251     handler.attachEventBase(eventBase);
252   }
253 }
254
255 void AsyncServerSocket::detachEventBase() {
256   assert(eventBase_ != nullptr);
257   assert(eventBase_->isInEventBaseThread());
258   assert(!accepting_);
259
260   eventBase_ = nullptr;
261   for (auto& handler : sockets_) {
262     handler.detachEventBase();
263   }
264 }
265
266 void AsyncServerSocket::useExistingSockets(const std::vector<int>& fds) {
267   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
268
269   if (sockets_.size() > 0) {
270     throw std::invalid_argument(
271                               "cannot call useExistingSocket() on a "
272                               "AsyncServerSocket that already has a socket");
273   }
274
275   for (auto fd: fds) {
276     // Set addressFamily_ from this socket.
277     // Note that the socket may not have been bound yet, but
278     // setFromLocalAddress() will still work and get the correct address family.
279     // We will update addressFamily_ again anyway if bind() is called later.
280     SocketAddress address;
281     address.setFromLocalAddress(fd);
282
283 #if __linux__
284     if (noTransparentTls_) {
285       // Ignore return value, errors are ok
286       setsockopt(fd, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0);
287     }
288 #endif
289
290     setupSocket(fd, address.getFamily());
291     sockets_.emplace_back(eventBase_, fd, this, address.getFamily());
292     sockets_.back().changeHandlerFD(fd);
293   }
294 }
295
296 void AsyncServerSocket::useExistingSocket(int fd) {
297   useExistingSockets({fd});
298 }
299
300 void AsyncServerSocket::bindSocket(
301     int fd,
302     const SocketAddress& address,
303     bool isExistingSocket) {
304   sockaddr_storage addrStorage;
305   address.getAddress(&addrStorage);
306   sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
307
308   if (fsp::bind(fd, saddr, address.getActualSize()) != 0) {
309     if (!isExistingSocket) {
310       closeNoInt(fd);
311     }
312     folly::throwSystemError(errno,
313         "failed to bind to async server socket: " +
314         address.describe());
315   }
316
317 #if __linux__
318   if (noTransparentTls_) {
319     // Ignore return value, errors are ok
320     setsockopt(fd, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0);
321   }
322 #endif
323
324   // If we just created this socket, update the EventHandler and set socket_
325   if (!isExistingSocket) {
326     sockets_.emplace_back(eventBase_, fd, this, address.getFamily());
327   }
328 }
329
330 void AsyncServerSocket::bind(const SocketAddress& address) {
331   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
332
333   // useExistingSocket() may have been called to initialize socket_ already.
334   // However, in the normal case we need to create a new socket now.
335   // Don't set socket_ yet, so that socket_ will remain uninitialized if an
336   // error occurs.
337   int fd;
338   if (sockets_.size() == 0) {
339     fd = createSocket(address.getFamily());
340   } else if (sockets_.size() == 1) {
341     if (address.getFamily() != sockets_[0].addressFamily_) {
342       throw std::invalid_argument(
343                                 "Attempted to bind address to socket with "
344                                 "different address family");
345     }
346     fd = sockets_[0].socket_;
347   } else {
348     throw std::invalid_argument(
349                               "Attempted to bind to multiple fds");
350   }
351
352   bindSocket(fd, address, !sockets_.empty());
353 }
354
355 void AsyncServerSocket::bind(
356     const std::vector<IPAddress>& ipAddresses,
357     uint16_t port) {
358   if (ipAddresses.empty()) {
359     throw std::invalid_argument("No ip addresses were provided");
360   }
361   if (!sockets_.empty()) {
362     throw std::invalid_argument("Cannot call bind on a AsyncServerSocket "
363                                 "that already has a socket.");
364   }
365
366   for (const IPAddress& ipAddress : ipAddresses) {
367     SocketAddress address(ipAddress.toFullyQualified(), port);
368     int fd = createSocket(address.getFamily());
369
370     bindSocket(fd, address, false);
371   }
372   if (sockets_.size() == 0) {
373     throw std::runtime_error(
374         "did not bind any async server socket for port and addresses");
375   }
376 }
377
378 void AsyncServerSocket::bind(uint16_t port) {
379   struct addrinfo hints, *res0;
380   char sport[sizeof("65536")];
381
382   memset(&hints, 0, sizeof(hints));
383   hints.ai_family = AF_UNSPEC;
384   hints.ai_socktype = SOCK_STREAM;
385   hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV;
386   snprintf(sport, sizeof(sport), "%u", port);
387
388   // On Windows the value we need to pass to bind to all available
389   // addresses is an empty string. Everywhere else, it's nullptr.
390   constexpr const char* kWildcardNode = kIsWindows ? "" : nullptr;
391   if (getaddrinfo(kWildcardNode, sport, &hints, &res0)) {
392     throw std::invalid_argument(
393                               "Attempted to bind address to socket with "
394                               "bad getaddrinfo");
395   }
396
397   SCOPE_EXIT { freeaddrinfo(res0); };
398
399   auto setupAddress = [&] (struct addrinfo* res) {
400     int s = fsp::socket(res->ai_family, res->ai_socktype, res->ai_protocol);
401     // IPv6/IPv4 may not be supported by the kernel
402     if (s < 0 && errno == EAFNOSUPPORT) {
403       return;
404     }
405     CHECK_GE(s, 0);
406
407     try {
408       setupSocket(s, res->ai_family);
409     } catch (...) {
410       closeNoInt(s);
411       throw;
412     }
413
414     if (res->ai_family == AF_INET6) {
415       int v6only = 1;
416       CHECK(0 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
417                             &v6only, sizeof(v6only)));
418     }
419
420     // Bind to the socket
421     if (fsp::bind(s, res->ai_addr, socklen_t(res->ai_addrlen)) != 0) {
422       folly::throwSystemError(
423           errno,
424           "failed to bind to async server socket for port ",
425           SocketAddress::getPortFrom(res->ai_addr),
426           " family ",
427           SocketAddress::getFamilyNameFrom(res->ai_addr, "<unknown>"));
428     }
429
430 #if __linux__
431     if (noTransparentTls_) {
432       // Ignore return value, errors are ok
433       setsockopt(s, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0);
434     }
435 #endif
436
437     SocketAddress address;
438     address.setFromLocalAddress(s);
439
440     sockets_.emplace_back(eventBase_, s, this, address.getFamily());
441   };
442
443   const int kNumTries = 25;
444   for (int tries = 1; true; tries++) {
445     // Prefer AF_INET6 addresses. RFC 3484 mandates that getaddrinfo
446     // should return IPv6 first and then IPv4 addresses, but glibc's
447     // getaddrinfo(nullptr) with AI_PASSIVE returns:
448     // - 0.0.0.0 (IPv4-only)
449     // - :: (IPv6+IPv4) in this order
450     // See: https://sourceware.org/bugzilla/show_bug.cgi?id=9981
451     for (struct addrinfo* res = res0; res; res = res->ai_next) {
452       if (res->ai_family == AF_INET6) {
453         setupAddress(res);
454       }
455     }
456
457     // If port == 0, then we should try to bind to the same port on ipv4 and
458     // ipv6.  So if we did bind to ipv6, figure out that port and use it.
459     if (sockets_.size() == 1 && port == 0) {
460       SocketAddress address;
461       address.setFromLocalAddress(sockets_.back().socket_);
462       snprintf(sport, sizeof(sport), "%u", address.getPort());
463       freeaddrinfo(res0);
464       CHECK_EQ(0, getaddrinfo(nullptr, sport, &hints, &res0));
465     }
466
467     try {
468       for (struct addrinfo* res = res0; res; res = res->ai_next) {
469         if (res->ai_family != AF_INET6) {
470           setupAddress(res);
471         }
472       }
473     } catch (const std::system_error&) {
474       // If we can't bind to the same port on ipv4 as ipv6 when using
475       // port=0 then we will retry again before giving up after
476       // kNumTries attempts.  We do this by closing the sockets that
477       // were opened, then restarting from scratch.
478       if (port == 0 && !sockets_.empty() && tries != kNumTries) {
479         for (const auto& socket : sockets_) {
480           if (socket.socket_ <= 0) {
481             continue;
482           } else if (shutdownSocketSet_) {
483             shutdownSocketSet_->close(socket.socket_);
484           } else {
485             closeNoInt(socket.socket_);
486           }
487         }
488         sockets_.clear();
489         snprintf(sport, sizeof(sport), "%u", port);
490         freeaddrinfo(res0);
491         CHECK_EQ(0, getaddrinfo(nullptr, sport, &hints, &res0));
492         continue;
493       }
494
495       throw;
496     }
497
498     break;
499   }
500
501   if (sockets_.size() == 0) {
502     throw std::runtime_error(
503         "did not bind any async server socket for port");
504   }
505 }
506
507 void AsyncServerSocket::listen(int backlog) {
508   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
509
510   // Start listening
511   for (auto& handler : sockets_) {
512     if (fsp::listen(handler.socket_, backlog) == -1) {
513       folly::throwSystemError(errno,
514                                     "failed to listen on async server socket");
515     }
516   }
517 }
518
519 void AsyncServerSocket::getAddress(SocketAddress* addressReturn) const {
520   CHECK(sockets_.size() >= 1);
521   VLOG_IF(2, sockets_.size() > 1)
522     << "Warning: getAddress() called and multiple addresses available ("
523     << sockets_.size() << "). Returning only the first one.";
524
525   addressReturn->setFromLocalAddress(sockets_[0].socket_);
526 }
527
528 std::vector<SocketAddress> AsyncServerSocket::getAddresses()
529     const {
530   CHECK(sockets_.size() >= 1);
531   auto tsaVec = std::vector<SocketAddress>(sockets_.size());
532   auto tsaIter = tsaVec.begin();
533   for (const auto& socket : sockets_) {
534     (tsaIter++)->setFromLocalAddress(socket.socket_);
535   };
536   return tsaVec;
537 }
538
539 void AsyncServerSocket::addAcceptCallback(AcceptCallback *callback,
540                                            EventBase *eventBase,
541                                            uint32_t maxAtOnce) {
542   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
543
544   // If this is the first accept callback and we are supposed to be accepting,
545   // start accepting once the callback is installed.
546   bool runStartAccepting = accepting_ && callbacks_.empty();
547
548   callbacks_.emplace_back(callback, eventBase);
549
550   SCOPE_SUCCESS {
551     // If this is the first accept callback and we are supposed to be accepting,
552     // start accepting.
553     if (runStartAccepting) {
554       startAccepting();
555     }
556   };
557
558   if (!eventBase) {
559     // Run in AsyncServerSocket's eventbase; notify that we are
560     // starting to accept connections
561     callback->acceptStarted();
562     return;
563   }
564
565   // Start the remote acceptor.
566   //
567   // It would be nice if we could avoid starting the remote acceptor if
568   // eventBase == eventBase_.  However, that would cause issues if
569   // detachEventBase() and attachEventBase() were ever used to change the
570   // primary EventBase for the server socket.  Therefore we require the caller
571   // to specify a nullptr EventBase if they want to ensure that the callback is
572   // always invoked in the primary EventBase, and to be able to invoke that
573   // callback more efficiently without having to use a notification queue.
574   RemoteAcceptor* acceptor = nullptr;
575   try {
576     acceptor = new RemoteAcceptor(callback, connectionEventCallback_);
577     acceptor->start(eventBase, maxAtOnce, maxNumMsgsInQueue_);
578   } catch (...) {
579     callbacks_.pop_back();
580     delete acceptor;
581     throw;
582   }
583   callbacks_.back().consumer = acceptor;
584 }
585
586 void AsyncServerSocket::removeAcceptCallback(AcceptCallback *callback,
587                                               EventBase *eventBase) {
588   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
589
590   // Find the matching AcceptCallback.
591   // We just do a simple linear search; we don't expect removeAcceptCallback()
592   // to be called frequently, and we expect there to only be a small number of
593   // callbacks anyway.
594   std::vector<CallbackInfo>::iterator it = callbacks_.begin();
595   uint32_t n = 0;
596   while (true) {
597     if (it == callbacks_.end()) {
598       throw std::runtime_error("AsyncServerSocket::removeAcceptCallback(): "
599                               "accept callback not found");
600     }
601     if (it->callback == callback &&
602         (it->eventBase == eventBase || eventBase == nullptr)) {
603       break;
604     }
605     ++it;
606     ++n;
607   }
608
609   // Remove this callback from callbacks_.
610   //
611   // Do this before invoking the acceptStopped() callback, in case
612   // acceptStopped() invokes one of our methods that examines callbacks_.
613   //
614   // Save a copy of the CallbackInfo first.
615   CallbackInfo info(*it);
616   callbacks_.erase(it);
617   if (n < callbackIndex_) {
618     // We removed an element before callbackIndex_.  Move callbackIndex_ back
619     // one step, since things after n have been shifted back by 1.
620     --callbackIndex_;
621   } else {
622     // We removed something at or after callbackIndex_.
623     // If we removed the last element and callbackIndex_ was pointing at it,
624     // we need to reset callbackIndex_ to 0.
625     if (callbackIndex_ >= callbacks_.size()) {
626       callbackIndex_ = 0;
627     }
628   }
629
630   if (info.consumer) {
631     // consumer could be nullptr is we run callbacks in primary event
632     // base
633     DCHECK(info.eventBase);
634     info.consumer->stop(info.eventBase, info.callback);
635   } else {
636     // callback invoked in the primary event base, just call directly
637     DCHECK(info.callback);
638     callback->acceptStopped();
639   }
640
641   // If we are supposed to be accepting but the last accept callback
642   // was removed, unregister for events until a callback is added.
643   if (accepting_ && callbacks_.empty()) {
644     for (auto& handler : sockets_) {
645       handler.unregisterHandler();
646     }
647   }
648 }
649
650 void AsyncServerSocket::startAccepting() {
651   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
652
653   accepting_ = true;
654   if (callbacks_.empty()) {
655     // We can't actually begin accepting if no callbacks are defined.
656     // Wait until a callback is added to start accepting.
657     return;
658   }
659
660   for (auto& handler : sockets_) {
661     if (!handler.registerHandler(
662           EventHandler::READ | EventHandler::PERSIST)) {
663       throw std::runtime_error("failed to register for accept events");
664     }
665   }
666 }
667
668 void AsyncServerSocket::pauseAccepting() {
669   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
670   accepting_ = false;
671   for (auto& handler : sockets_) {
672    handler. unregisterHandler();
673   }
674
675   // If we were in the accept backoff state, disable the backoff timeout
676   if (backoffTimeout_) {
677     backoffTimeout_->cancelTimeout();
678   }
679 }
680
681 int AsyncServerSocket::createSocket(int family) {
682   int fd = fsp::socket(family, SOCK_STREAM, 0);
683   if (fd == -1) {
684     folly::throwSystemError(errno, "error creating async server socket");
685   }
686
687   try {
688     setupSocket(fd, family);
689   } catch (...) {
690     closeNoInt(fd);
691     throw;
692   }
693   return fd;
694 }
695
696 void AsyncServerSocket::setupSocket(int fd, int family) {
697   // Put the socket in non-blocking mode
698   if (fcntl(fd, F_SETFL, O_NONBLOCK) != 0) {
699     folly::throwSystemError(errno,
700                             "failed to put socket in non-blocking mode");
701   }
702
703   // Set reuseaddr to avoid 2MSL delay on server restart
704   int one = 1;
705   if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) != 0) {
706     // This isn't a fatal error; just log an error message and continue
707     LOG(ERROR) << "failed to set SO_REUSEADDR on async server socket " << errno;
708   }
709
710   // Set reuseport to support multiple accept threads
711   int zero = 0;
712   if (reusePortEnabled_ &&
713       setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(int)) != 0) {
714     LOG(ERROR) << "failed to set SO_REUSEPORT on async server socket "
715                << strerror(errno);
716 #ifdef WIN32
717     folly::throwSystemError(errno, "failed to bind to the async server socket");
718 #else
719     SocketAddress address;
720     address.setFromLocalAddress(fd);
721     folly::throwSystemError(errno,
722                             "failed to bind to async server socket: " +
723                             address.describe());
724 #endif
725   }
726
727   // Set keepalive as desired
728   if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
729                  (keepAliveEnabled_) ? &one : &zero, sizeof(int)) != 0) {
730     LOG(ERROR) << "failed to set SO_KEEPALIVE on async server socket: " <<
731             strerror(errno);
732   }
733
734   // Setup FD_CLOEXEC flag
735   if (closeOnExec_ &&
736       (-1 == folly::setCloseOnExec(fd, closeOnExec_))) {
737     LOG(ERROR) << "failed to set FD_CLOEXEC on async server socket: " <<
738             strerror(errno);
739   }
740
741   // Set TCP nodelay if available, MAC OS X Hack
742   // See http://lists.danga.com/pipermail/memcached/2005-March/001240.html
743 #ifndef TCP_NOPUSH
744   if (family != AF_UNIX) {
745     if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)) != 0) {
746       // This isn't a fatal error; just log an error message and continue
747       LOG(ERROR) << "failed to set TCP_NODELAY on async server socket: " <<
748               strerror(errno);
749     }
750   }
751 #endif
752
753 #if FOLLY_ALLOW_TFO
754   if (tfo_ && detail::tfo_enable(fd, tfoMaxQueueSize_) != 0) {
755     // This isn't a fatal error; just log an error message and continue
756     LOG(WARNING) << "failed to set TCP_FASTOPEN on async server socket: "
757                  << folly::errnoStr(errno);
758   }
759 #endif
760
761   if (shutdownSocketSet_) {
762     shutdownSocketSet_->add(fd);
763   }
764 }
765
766 void AsyncServerSocket::handlerReady(uint16_t /* events */,
767                                      int fd,
768                                      sa_family_t addressFamily) noexcept {
769   assert(!callbacks_.empty());
770   DestructorGuard dg(this);
771
772   // Only accept up to maxAcceptAtOnce_ connections at a time,
773   // to avoid starving other I/O handlers using this EventBase.
774   for (uint32_t n = 0; n < maxAcceptAtOnce_; ++n) {
775     SocketAddress address;
776
777     sockaddr_storage addrStorage;
778     socklen_t addrLen = sizeof(addrStorage);
779     sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
780
781     // In some cases, accept() doesn't seem to update these correctly.
782     saddr->sa_family = addressFamily;
783     if (addressFamily == AF_UNIX) {
784       addrLen = sizeof(struct sockaddr_un);
785     }
786
787     // Accept a new client socket
788 #ifdef SOCK_NONBLOCK
789     int clientSocket = accept4(fd, saddr, &addrLen, SOCK_NONBLOCK);
790 #else
791     int clientSocket = accept(fd, saddr, &addrLen);
792 #endif
793
794     address.setFromSockaddr(saddr, addrLen);
795
796     if (clientSocket >= 0 && connectionEventCallback_) {
797       connectionEventCallback_->onConnectionAccepted(clientSocket, address);
798     }
799
800     std::chrono::time_point<std::chrono::steady_clock> nowMs =
801       std::chrono::steady_clock::now();
802     auto timeSinceLastAccept = std::max<int64_t>(
803       0,
804       nowMs.time_since_epoch().count() -
805       lastAccepTimestamp_.time_since_epoch().count());
806     lastAccepTimestamp_ = nowMs;
807     if (acceptRate_ < 1) {
808       acceptRate_ *= 1 + acceptRateAdjustSpeed_ * timeSinceLastAccept;
809       if (acceptRate_ >= 1) {
810         acceptRate_ = 1;
811       } else if (rand() > acceptRate_ * RAND_MAX) {
812         ++numDroppedConnections_;
813         if (clientSocket >= 0) {
814           closeNoInt(clientSocket);
815           if (connectionEventCallback_) {
816             connectionEventCallback_->onConnectionDropped(clientSocket,
817                                                           address);
818           }
819         }
820         continue;
821       }
822     }
823
824     if (clientSocket < 0) {
825       if (errno == EAGAIN) {
826         // No more sockets to accept right now.
827         // Check for this code first, since it's the most common.
828         return;
829       } else if (errno == EMFILE || errno == ENFILE) {
830         // We're out of file descriptors.  Perhaps we're accepting connections
831         // too quickly. Pause accepting briefly to back off and give the server
832         // a chance to recover.
833         LOG(ERROR) << "accept failed: out of file descriptors; entering accept "
834                 "back-off state";
835         enterBackoff();
836
837         // Dispatch the error message
838         dispatchError("accept() failed", errno);
839       } else {
840         dispatchError("accept() failed", errno);
841       }
842       if (connectionEventCallback_) {
843         connectionEventCallback_->onConnectionAcceptError(errno);
844       }
845       return;
846     }
847
848 #ifndef SOCK_NONBLOCK
849     // Explicitly set the new connection to non-blocking mode
850     if (fcntl(clientSocket, F_SETFL, O_NONBLOCK) != 0) {
851       closeNoInt(clientSocket);
852       dispatchError("failed to set accepted socket to non-blocking mode",
853                     errno);
854       if (connectionEventCallback_) {
855         connectionEventCallback_->onConnectionDropped(clientSocket, address);
856       }
857       return;
858     }
859 #endif
860
861     // Inform the callback about the new connection
862     dispatchSocket(clientSocket, std::move(address));
863
864     // If we aren't accepting any more, break out of the loop
865     if (!accepting_ || callbacks_.empty()) {
866       break;
867     }
868   }
869 }
870
871 void AsyncServerSocket::dispatchSocket(int socket,
872                                         SocketAddress&& address) {
873   uint32_t startingIndex = callbackIndex_;
874
875   // Short circuit if the callback is in the primary EventBase thread
876
877   CallbackInfo *info = nextCallback();
878   if (info->eventBase == nullptr) {
879     info->callback->connectionAccepted(socket, address);
880     return;
881   }
882
883   const SocketAddress addr(address);
884   // Create a message to send over the notification queue
885   QueueMessage msg;
886   msg.type = MessageType::MSG_NEW_CONN;
887   msg.address = std::move(address);
888   msg.fd = socket;
889
890   // Loop until we find a free queue to write to
891   while (true) {
892     if (info->consumer->getQueue()->tryPutMessageNoThrow(std::move(msg))) {
893       if (connectionEventCallback_) {
894         connectionEventCallback_->onConnectionEnqueuedForAcceptorCallback(
895             socket,
896             addr);
897       }
898       // Success! return.
899       return;
900     }
901
902     // We couldn't add to queue.  Fall through to below
903
904     ++numDroppedConnections_;
905     if (acceptRateAdjustSpeed_ > 0) {
906       // aggressively decrease accept rate when in trouble
907       static const double kAcceptRateDecreaseSpeed = 0.1;
908       acceptRate_ *= 1 - kAcceptRateDecreaseSpeed;
909     }
910
911
912     if (callbackIndex_ == startingIndex) {
913       // The notification queue was full
914       // We can't really do anything at this point other than close the socket.
915       //
916       // This should only happen if a user's service is behaving extremely
917       // badly and none of the EventBase threads are looping fast enough to
918       // process the incoming connections.  If the service is overloaded, it
919       // should use pauseAccepting() to temporarily back off accepting new
920       // connections, before they reach the point where their threads can't
921       // even accept new messages.
922       LOG(ERROR) << "failed to dispatch newly accepted socket:"
923                  << " all accept callback queues are full";
924       closeNoInt(socket);
925       if (connectionEventCallback_) {
926         connectionEventCallback_->onConnectionDropped(socket, addr);
927       }
928       return;
929     }
930
931     info = nextCallback();
932   }
933 }
934
935 void AsyncServerSocket::dispatchError(const char *msgstr, int errnoValue) {
936   uint32_t startingIndex = callbackIndex_;
937   CallbackInfo *info = nextCallback();
938
939   // Create a message to send over the notification queue
940   QueueMessage msg;
941   msg.type = MessageType::MSG_ERROR;
942   msg.err = errnoValue;
943   msg.msg = std::move(msgstr);
944
945   while (true) {
946     // Short circuit if the callback is in the primary EventBase thread
947     if (info->eventBase == nullptr) {
948       std::runtime_error ex(
949         std::string(msgstr) +  folly::to<std::string>(errnoValue));
950       info->callback->acceptError(ex);
951       return;
952     }
953
954     if (info->consumer->getQueue()->tryPutMessageNoThrow(std::move(msg))) {
955       return;
956     }
957     // Fall through and try another callback
958
959     if (callbackIndex_ == startingIndex) {
960       // The notification queues for all of the callbacks were full.
961       // We can't really do anything at this point.
962       LOG(ERROR) << "failed to dispatch accept error: all accept callback "
963         "queues are full: error msg:  " <<
964         msg.msg.c_str() << errnoValue;
965       return;
966     }
967     info = nextCallback();
968   }
969 }
970
971 void AsyncServerSocket::enterBackoff() {
972   // If this is the first time we have entered the backoff state,
973   // allocate backoffTimeout_.
974   if (backoffTimeout_ == nullptr) {
975     try {
976       backoffTimeout_ = new BackoffTimeout(this);
977     } catch (const std::bad_alloc&) {
978       // Man, we couldn't even allocate the timer to re-enable accepts.
979       // We must be in pretty bad shape.  Don't pause accepting for now,
980       // since we won't be able to re-enable ourselves later.
981       LOG(ERROR) << "failed to allocate AsyncServerSocket backoff"
982                  << " timer; unable to temporarly pause accepting";
983       if (connectionEventCallback_) {
984         connectionEventCallback_->onBackoffError();
985       }
986       return;
987     }
988   }
989
990   // For now, we simply pause accepting for 1 second.
991   //
992   // We could add some smarter backoff calculation here in the future.  (e.g.,
993   // start sleeping for longer if we keep hitting the backoff frequently.)
994   // Typically the user needs to figure out why the server is overloaded and
995   // fix it in some other way, though.  The backoff timer is just a simple
996   // mechanism to try and give the connection processing code a little bit of
997   // breathing room to catch up, and to avoid just spinning and failing to
998   // accept over and over again.
999   const uint32_t timeoutMS = 1000;
1000   if (!backoffTimeout_->scheduleTimeout(timeoutMS)) {
1001     LOG(ERROR) << "failed to schedule AsyncServerSocket backoff timer;"
1002                << "unable to temporarly pause accepting";
1003     if (connectionEventCallback_) {
1004       connectionEventCallback_->onBackoffError();
1005     }
1006     return;
1007   }
1008
1009   // The backoff timer is scheduled to re-enable accepts.
1010   // Go ahead and disable accepts for now.  We leave accepting_ set to true,
1011   // since that tracks the desired state requested by the user.
1012   for (auto& handler : sockets_) {
1013     handler.unregisterHandler();
1014   }
1015   if (connectionEventCallback_) {
1016     connectionEventCallback_->onBackoffStarted();
1017   }
1018 }
1019
1020 void AsyncServerSocket::backoffTimeoutExpired() {
1021   // accepting_ should still be true.
1022   // If pauseAccepting() was called while in the backoff state it will cancel
1023   // the backoff timeout.
1024   assert(accepting_);
1025   // We can't be detached from the EventBase without being paused
1026   assert(eventBase_ != nullptr && eventBase_->isInEventBaseThread());
1027
1028   // If all of the callbacks were removed, we shouldn't re-enable accepts
1029   if (callbacks_.empty()) {
1030     if (connectionEventCallback_) {
1031       connectionEventCallback_->onBackoffEnded();
1032     }
1033     return;
1034   }
1035
1036   // Register the handler.
1037   for (auto& handler : sockets_) {
1038     if (!handler.registerHandler(
1039           EventHandler::READ | EventHandler::PERSIST)) {
1040       // We're hosed.  We could just re-schedule backoffTimeout_ to
1041       // re-try again after a little bit.  However, we don't want to
1042       // loop retrying forever if we can't re-enable accepts.  Just
1043       // abort the entire program in this state; things are really bad
1044       // and restarting the entire server is probably the best remedy.
1045       LOG(ERROR)
1046         << "failed to re-enable AsyncServerSocket accepts after backoff; "
1047         << "crashing now";
1048       abort();
1049     }
1050   }
1051   if (connectionEventCallback_) {
1052     connectionEventCallback_->onBackoffEnded();
1053   }
1054 }
1055
1056
1057
1058 } // folly