1 /************************************************************************
2 * IRC - Internet Relay Chat, src/listener.c
3 * Copyright (C) 1999 Thomas Helvey <tomh@inxpress.net>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 1, or (at your option)
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 * @brief Implementation for handling listening sockets.
28 #include "ircd_alloc.h"
29 #include "ircd_events.h"
30 #include "ircd_features.h"
32 #include "ircd_osdep.h"
33 #include "ircd_reply.h"
34 #include "ircd_snprintf.h"
35 #include "ircd_string.h"
43 #include "sys.h" /* MAXCLIENTS */
45 /* #include <assert.h> -- Now using assert in ircd_log.h */
52 #include <sys/socket.h>
54 /** List of listening sockets. */
55 struct Listener* ListenerPollList = 0;
57 static void accept_connection(struct Event* ev);
59 /** Allocate and initialize a new Listener structure for a particular
61 * @param[in] port Port number to listen on.
62 * @param[in] addr Local address to listen on.
63 * @return Newly allocated and initialized Listener.
65 static struct Listener* make_listener(int port, const struct irc_in_addr *addr)
67 struct Listener* listener =
68 (struct Listener*) MyMalloc(sizeof(struct Listener));
69 assert(0 != listener);
71 memset(listener, 0, sizeof(struct Listener));
75 listener->addr.port = port;
76 memcpy(&listener->addr.addr, addr, sizeof(listener->addr.addr));
78 #ifdef NULL_POINTER_NOT_ZERO
79 listener->next = NULL;
80 listener->conf = NULL;
85 /** Deallocate a Listener structure.
86 * @param[in] listener Listener to be freed.
88 static void free_listener(struct Listener* listener)
90 assert(0 != listener);
94 /** Maximum length for a port number. */
95 #define PORTNAMELEN 10 /* ":31337" */
97 /** Return displayable listener name and port.
98 * @param[in] listener %Listener to format as a text string.
99 * @return Pointer to a static buffer that contains "server.name:6667".
101 const char* get_listener_name(const struct Listener* listener)
103 static char buf[HOSTLEN + PORTNAMELEN + 4];
104 assert(0 != listener);
105 ircd_snprintf(0, buf, sizeof(buf), "%s:%u", cli_name(&me), listener->addr.port);
109 /** Count allocated listeners and the memory they use.
110 * @param[out] count_out Receives number of allocated listeners.
111 * @param[out] size_out Receives bytes used by listeners.
113 void count_listener_memory(int* count_out, size_t* size_out)
117 assert(0 != count_out);
118 assert(0 != size_out);
119 for (l = ListenerPollList; l; l = l->next)
122 *size_out = count * sizeof(struct Listener);
125 /** Report listening ports to a client.
126 * @param[in] sptr Client requesting statistics.
127 * @param[in] sd Stats descriptor for request (ignored).
128 * @param[in] param Extra parameter from user (port number to search for).
130 void show_ports(struct Client* sptr, const struct StatDesc* sd,
133 struct Listener *listener = 0;
135 int show_hidden = IsOper(sptr);
136 int count = (IsOper(sptr) || MyUser(sptr)) ? 100 : 8;
145 for (listener = ListenerPollList; listener; listener = listener->next) {
146 if (port && port != listener->addr.port)
149 flags[len++] = listener_server(listener) ? 'S' : 'C';
150 if (show_hidden && FlagHas(&listener->flags, LISTEN_HIDDEN))
152 if (FlagHas(&listener->flags, LISTEN_IPV4))
155 if (listener->fd_v4 < 0)
158 if (FlagHas(&listener->flags, LISTEN_IPV6))
161 if (listener->fd_v6 < 0)
166 send_reply(sptr, RPL_STATSPLINE, listener->addr.port, listener->ref_count,
167 flags, listener_active(listener) ? "active" : "disabled");
174 * inetport - create a listener socket in the AF_INET domain,
175 * bind it to the port given in 'port' and listen to it
176 * returns true (1) if successful false (0) on error.
178 * If the operating system has a define for SOMAXCONN, use it, otherwise
179 * use HYBRID_SOMAXCONN -Dianora
180 * NOTE: Do this in os_xxxx.c files
183 #define HYBRID_SOMAXCONN SOMAXCONN
185 /** Maximum length of socket connection backlog. */
186 #define HYBRID_SOMAXCONN 64
189 /** Set or update socket options for \a listener.
190 * @param[in] listener Listener to determine socket option values.
191 * @param[in] fd File descriptor being updated.
192 * @return Non-zero on success, zero on failure.
194 static int set_listener_options(struct Listener *listener, int fd)
198 is_server = listener_server(listener);
200 * Set the buffer sizes for the listener. Accepted connections
201 * inherit the accepting sockets settings for SO_RCVBUF S_SNDBUF
202 * The window size is set during the SYN ACK so setting it anywhere
203 * else has no effect whatsoever on the connection.
204 * NOTE: this must be set before listen is called
206 if (!os_set_sockbufs(fd,
207 is_server ? feature_int(FEAT_SOCKSENDBUF) : CLIENT_TCP_WINDOW,
208 is_server ? feature_int(FEAT_SOCKRECVBUF) : CLIENT_TCP_WINDOW)) {
209 report_error(SETBUFS_ERROR_MSG, get_listener_name(listener), errno);
215 * Set the TOS bits - this is nonfatal if it doesn't stick.
217 if (!os_set_tos(fd,feature_int(is_server ? FEAT_TOS_SERVER : FEAT_TOS_CLIENT))) {
218 report_error(TOS_ERROR_MSG, get_listener_name(listener), errno);
224 /** Open listening socket for \a listener.
225 * @param[in,out] listener Listener to make a socket for.
226 * @param[in] family Socket address family to use.
227 * @return Negative on failure, file descriptor on success.
229 static int inetport(struct Listener* listener, int family)
235 * At first, open a new socket
237 fd = os_socket(&listener->addr, SOCK_STREAM, get_listener_name(listener), family);
240 if (!os_set_listen(fd, HYBRID_SOMAXCONN)) {
241 report_error(LISTEN_ERROR_MSG, get_listener_name(listener), errno);
245 if (!set_listener_options(listener, fd))
247 sock = (family == AF_INET) ? &listener->socket_v4 : &listener->socket_v6;
248 if (!socket_add(sock, accept_connection, (void*) listener,
249 SS_LISTENING, 0, fd)) {
250 /* Error should already have been reported to the logs */
258 /** Find the listener (if any) for a particular port and address.
259 * @param[in] port Port number to search for.
260 * @param[in] addr Local address to search for.
261 * @return Listener that matches (or NULL if none match).
263 static struct Listener* find_listener(int port, const struct irc_in_addr *addr)
265 struct Listener* listener;
266 for (listener = ListenerPollList; listener; listener = listener->next) {
267 if (port == listener->addr.port && !memcmp(addr, &listener->addr.addr, sizeof(*addr)))
273 /** Make sure we have a listener for \a port on \a vhost_ip.
274 * If one does not exist, create it. Then mark it as active and set
275 * the peer mask, server, and hidden flags according to the other
277 * @param[in] port Port number to listen on.
278 * @param[in] vhost_ip Local address to listen on.
279 * @param[in] mask Address mask to accept connections from.
280 * @param[in] flags Flags describing listener options.
282 void add_listener(int port, const char* vhost_ip, const char* mask,
283 const struct ListenerFlags *flags)
285 struct Listener* listener;
286 struct irc_in_addr vaddr;
288 int new_listener = 0;
292 * if no port in conf line, don't bother
297 memset(&vaddr, 0, sizeof(vaddr));
299 if (!EmptyString(vhost_ip)
300 && strcmp(vhost_ip, "*")
301 && !ircd_aton(&vaddr, vhost_ip))
304 listener = find_listener(port, &vaddr);
308 listener = make_listener(port, &vaddr);
310 memcpy(&listener->flags, flags, sizeof(listener->flags));
311 FlagSet(&listener->flags, LISTEN_ACTIVE);
313 ipmask_parse(mask, &listener->mask, &listener->mask_bits);
315 listener->mask_bits = 0;
318 if (FlagHas(&listener->flags, LISTEN_IPV6)) {
319 if (listener->fd_v6 >= 0) {
320 set_listener_options(listener, listener->fd_v6);
322 } else if ((fd = inetport(listener, AF_INET6)) >= 0) {
323 listener->fd_v6 = fd;
326 } else if (-1 < listener->fd_v6) {
327 close(listener->fd_v6);
328 socket_del(&listener->socket_v6);
329 listener->fd_v6 = -1;
333 if (FlagHas(&listener->flags, LISTEN_IPV4)) {
334 if (listener->fd_v4 >= 0) {
335 set_listener_options(listener, listener->fd_v4);
337 } else if ((fd = inetport(listener, AF_INET)) >= 0) {
338 listener->fd_v4 = fd;
341 } else if (-1 < listener->fd_v4) {
342 close(listener->fd_v4);
343 socket_del(&listener->socket_v4);
344 listener->fd_v4 = -1;
348 free_listener(listener);
349 else if (new_listener) {
350 listener->next = ListenerPollList;
351 ListenerPollList = listener;
355 /** Mark all listeners as closing (inactive).
356 * This is done so unused listeners are closed after a rehash.
358 void mark_listeners_closing(void)
360 struct Listener* listener;
361 for (listener = ListenerPollList; listener; listener = listener->next)
362 FlagClr(&listener->flags, LISTEN_ACTIVE);
365 /** Close a single listener.
366 * @param[in] listener Listener to close.
368 void close_listener(struct Listener* listener)
370 assert(0 != listener);
372 * remove from listener list
374 if (listener == ListenerPollList)
375 ListenerPollList = listener->next;
377 struct Listener* prev = ListenerPollList;
378 for ( ; prev; prev = prev->next) {
379 if (listener == prev->next) {
380 prev->next = listener->next;
385 if (-1 < listener->fd_v4) {
386 close(listener->fd_v4);
387 socket_del(&listener->socket_v4);
388 listener->fd_v4 = -1;
390 if (-1 < listener->fd_v6) {
391 close(listener->fd_v6);
392 socket_del(&listener->socket_v6);
393 listener->fd_v6 = -1;
395 free_listener(listener);
398 /** Close all inactive listeners. */
399 void close_listeners(void)
401 struct Listener* listener;
402 struct Listener* listener_next = 0;
404 * close all 'extra' listening ports we have
406 for (listener = ListenerPollList; listener; listener = listener_next) {
407 listener_next = listener->next;
408 if (!listener_active(listener) && 0 == listener->ref_count)
409 close_listener(listener);
413 /** Dereference the listener previously associated with a client.
414 * @param[in] listener Listener to dereference.
416 void release_listener(struct Listener* listener)
418 assert(0 != listener);
419 assert(0 < listener->ref_count);
420 if (0 == --listener->ref_count && !listener_active(listener))
421 close_listener(listener);
424 /** Accept a connection on a listener.
425 * @param[in] ev Socket callback structure.
427 static void accept_connection(struct Event* ev)
429 struct Listener* listener;
430 struct irc_sockaddr addr;
433 assert(0 != ev_socket(ev));
434 assert(0 != s_data(ev_socket(ev)));
436 listener = (struct Listener*) s_data(ev_socket(ev));
438 if (ev_type(ev) == ET_DESTROY) /* being destroyed */
441 assert(ev_type(ev) == ET_ACCEPT || ev_type(ev) == ET_ERROR);
443 listener->last_accept = CurrentTime;
445 * There may be many reasons for error return, but
446 * in otherwise correctly working environment the
447 * probable cause is running out of file descriptors
448 * (EMFILE, ENFILE or others?). The man pages for
449 * accept don't seem to list these as possible,
450 * although it's obvious that it may happen here.
451 * Thus no specific errors are tested at this
452 * point, just assume that connections cannot
453 * be accepted until some old is closed first.
455 * This piece of code implements multi-accept, based
456 * on the idea that poll/select can only be efficient,
457 * if we succeed in handling all available events,
458 * i.e. accept all pending connections.
460 * http://www.hpl.hp.com/techreports/2000/HPL-2000-174.html
464 if ((fd = os_accept(s_fd(ev_socket(ev)), &addr)) == -1)
466 if (errno == EAGAIN ||
468 errno == EWOULDBLOCK)
471 /* Lotsa admins seem to have problems with not giving enough file
472 * descriptors to their server so we'll add a generic warning mechanism
473 * here. If it turns out too many messages are generated for
474 * meaningless reasons we can filter them back.
476 sendto_opmask_butone(0, SNO_TCPCOMMON,
477 "Unable to accept connection: %m");
481 * check for connection limit. If this fd exceeds the limit,
482 * all further accept()ed connections will also exceed it.
483 * Enable the server to clear out other connections before
484 * continuing to accept() new connections.
486 if (fd > MAXCLIENTS - 1)
488 ++ServerStats->is_ref;
489 send(fd, "ERROR :All connections in use\r\n", 32, 0);
494 * check to see if listener is shutting down. Continue
495 * to accept(), because it makes sense to clear our the
496 * socket's queue as fast as possible.
498 if (!listener_active(listener))
500 ++ServerStats->is_ref;
501 send(fd, "ERROR :Use another port\r\n", 25, 0);
506 * check to see if connection is allowed for this address mask
508 if (!ipmask_check(&addr.addr, &listener->mask, listener->mask_bits))
510 ++ServerStats->is_ref;
511 send(fd, "ERROR :Use another port\r\n", 25, 0);
515 ++ServerStats->is_ac;
516 /* nextping = CurrentTime; */
517 add_connection(listener, fd);