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