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