Allow per-port specification of address family, and use separate
[ircu2.10.12-pk.git] / ircd / listener.c
1 /************************************************************************
2  *   IRC - Internet Relay Chat, src/listener.c
3  *   Copyright (C) 1999 Thomas Helvey <tomh@inxpress.net>
4  *
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)
8  *   any later version.
9  *
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.
14  *
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.
18  */
19 /** @file
20  * @brief Implementation for handling listening sockets.
21  * @version $Id$
22  */
23 #include "config.h"
24
25 #include "listener.h"
26 #include "client.h"
27 #include "ircd.h"
28 #include "ircd_alloc.h"
29 #include "ircd_events.h"
30 #include "ircd_features.h"
31 #include "ircd_log.h"
32 #include "ircd_osdep.h"
33 #include "ircd_reply.h"
34 #include "ircd_snprintf.h"
35 #include "ircd_string.h"
36 #include "match.h"
37 #include "numeric.h"
38 #include "s_bsd.h"
39 #include "s_conf.h"
40 #include "s_misc.h"
41 #include "s_stats.h"
42 #include "send.h"
43 #include "sys.h"         /* MAXCLIENTS */
44
45 /* #include <assert.h> -- Now using assert in ircd_log.h */
46 #include <stdio.h>
47 #include <string.h>
48 #include <errno.h>
49 #include <stdlib.h>
50 #include <unistd.h>
51 #include <netdb.h>
52 #include <sys/socket.h>
53
54 /** List of listening sockets. */
55 struct Listener* ListenerPollList = 0;
56
57 static void accept_connection(struct Event* ev);
58
59 /** Allocate and initialize a new Listener structure for a particular
60  * socket address.
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.
64  */
65 static struct Listener* make_listener(int port, const struct irc_in_addr *addr)
66 {
67   struct Listener* listener =
68     (struct Listener*) MyMalloc(sizeof(struct Listener));
69   assert(0 != listener);
70
71   memset(listener, 0, sizeof(struct Listener));
72
73   listener->fd_v4       = -1;
74   listener->fd_v6       = -1;
75   listener->addr.port   = port;
76   memcpy(&listener->addr.addr, addr, sizeof(listener->addr.addr));
77
78 #ifdef NULL_POINTER_NOT_ZERO
79   listener->next = NULL;
80   listener->conf = NULL;
81 #endif
82   return listener;
83 }
84
85 /** Deallocate a Listener structure.
86  * @param[in] listener Listener to be freed.
87  */
88 static void free_listener(struct Listener* listener)
89 {
90   assert(0 != listener);
91   MyFree(listener);
92 }
93
94 /** Maximum length for a port number. */
95 #define PORTNAMELEN 10  /* ":31337" */
96
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".
100  */
101 const char* get_listener_name(const struct Listener* listener)
102 {
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);
106   return buf;
107 }
108
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.
112  */
113 void count_listener_memory(int* count_out, size_t* size_out)
114 {
115   struct Listener* l;
116   int              count = 0;
117   assert(0 != count_out);
118   assert(0 != size_out);
119   for (l = ListenerPollList; l; l = l->next)
120     ++count;
121   *count_out = count;
122   *size_out  = count * sizeof(struct Listener);
123 }
124
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).
129  */
130 void show_ports(struct Client* sptr, const struct StatDesc* sd,
131                 char* param)
132 {
133   struct Listener *listener = 0;
134   char flags[8];
135   int show_hidden = IsOper(sptr);
136   int count = (IsOper(sptr) || MyUser(sptr)) ? 100 : 8;
137   int port = 0;
138   int len;
139
140   assert(0 != sptr);
141
142   if (param)
143     port = atoi(param);
144
145   for (listener = ListenerPollList; listener; listener = listener->next) {
146     if (port && port != listener->addr.port)
147       continue;
148     len = 0;
149     flags[len++] = listener_server(listener) ? 'S' : 'C';
150     if (show_hidden && FlagHas(&listener->flags, LISTEN_HIDDEN))
151       flags[len++] = 'H';
152     flags[len] = '\0';
153
154     send_reply(sptr, RPL_STATSPLINE, listener->addr.port, listener->ref_count,
155                flags, listener_active(listener) ? "active" : "disabled");
156     if (--count == 0)
157       break;
158   }
159 }
160
161 /*
162  * inetport - create a listener socket in the AF_INET domain, 
163  * bind it to the port given in 'port' and listen to it  
164  * returns true (1) if successful false (0) on error.
165  *
166  * If the operating system has a define for SOMAXCONN, use it, otherwise
167  * use HYBRID_SOMAXCONN -Dianora
168  * NOTE: Do this in os_xxxx.c files
169  */
170 #ifdef SOMAXCONN
171 #define HYBRID_SOMAXCONN SOMAXCONN
172 #else
173 /** Maximum length of socket connection backlog. */
174 #define HYBRID_SOMAXCONN 64
175 #endif
176
177 /** Set or update socket options for \a listener.
178  * @param[in] listener Listener to determine socket option values.
179  * @param[in] fd File descriptor being updated.
180  * @return Non-zero on success, zero on failure.
181  */
182 static int set_listener_options(struct Listener *listener, int fd)
183 {
184   int is_server;
185
186   is_server = listener_server(listener);
187   /*
188    * Set the buffer sizes for the listener. Accepted connections
189    * inherit the accepting sockets settings for SO_RCVBUF S_SNDBUF
190    * The window size is set during the SYN ACK so setting it anywhere
191    * else has no effect whatsoever on the connection.
192    * NOTE: this must be set before listen is called
193    */
194   if (!os_set_sockbufs(fd,
195                        is_server ? feature_int(FEAT_SOCKSENDBUF) : CLIENT_TCP_WINDOW,
196                        is_server ? feature_int(FEAT_SOCKRECVBUF) : CLIENT_TCP_WINDOW)) {
197     report_error(SETBUFS_ERROR_MSG, get_listener_name(listener), errno);
198     close(fd);
199     return 0;
200   }
201
202   /*
203    * Set the TOS bits - this is nonfatal if it doesn't stick.
204    */
205   if (!os_set_tos(fd,feature_int(is_server ? FEAT_TOS_SERVER : FEAT_TOS_CLIENT))) {
206     report_error(TOS_ERROR_MSG, get_listener_name(listener), errno);
207   }
208
209   return 1;
210 }
211
212 /** Open listening socket for \a listener.
213  * @param[in,out] listener Listener to make a socket for.
214  * @param[in] family Socket address family to use.
215  * @return Negative on failure, file descriptor on success.
216  */
217 static int inetport(struct Listener* listener, int family)
218 {
219   struct Socket *sock;
220   int fd;
221
222   /*
223    * At first, open a new socket
224    */
225   fd = os_socket(&listener->addr, SOCK_STREAM, get_listener_name(listener), family);
226   if (fd < 0)
227     return -1;
228   if (!os_set_listen(fd, HYBRID_SOMAXCONN)) {
229     report_error(LISTEN_ERROR_MSG, get_listener_name(listener), errno);
230     close(fd);
231     return -1;
232   }
233   if (!set_listener_options(listener, fd))
234     return -1;
235   sock = (family == AF_INET) ? &listener->socket_v4 : &listener->socket_v6;
236   if (!socket_add(sock, accept_connection, (void*) listener,
237                   SS_LISTENING, 0, fd)) {
238     /* Error should already have been reported to the logs */
239     close(fd);
240     return -1;
241   }
242
243   return fd;
244 }
245
246 /** Find the listener (if any) for a particular port and address.
247  * @param[in] port Port number to search for.
248  * @param[in] addr Local address to search for.
249  * @return Listener that matches (or NULL if none match).
250  */
251 static struct Listener* find_listener(int port, const struct irc_in_addr *addr)
252 {
253   struct Listener* listener;
254   for (listener = ListenerPollList; listener; listener = listener->next) {
255     if (port == listener->addr.port && !memcmp(addr, &listener->addr.addr, sizeof(*addr)))
256       return listener;
257   }
258   return 0;
259 }
260
261 /** Make sure we have a listener for \a port on \a vhost_ip.
262  * If one does not exist, create it.  Then mark it as active and set
263  * the peer mask, server, and hidden flags according to the other
264  * arguments.
265  * @param[in] port Port number to listen on.
266  * @param[in] vhost_ip Local address to listen on.
267  * @param[in] mask Address mask to accept connections from.
268  * @param[in] flags Flags describing listener options.
269  */
270 void add_listener(int port, const char* vhost_ip, const char* mask,
271                   const struct ListenerFlags *flags)
272 {
273   struct Listener* listener;
274   struct irc_in_addr vaddr;
275   int okay = 0;
276   int new_listener = 0;
277   int fd;
278
279   /*
280    * if no port in conf line, don't bother
281    */
282   if (0 == port)
283     return;
284
285   memset(&vaddr, 0, sizeof(vaddr));
286
287   if (!EmptyString(vhost_ip)
288       && strcmp(vhost_ip, "*")
289       && !ircd_aton(&vaddr, vhost_ip))
290       return;
291
292   listener = find_listener(port, &vaddr);
293   if (!listener)
294   {
295     new_listener = 1;
296     listener = make_listener(port, &vaddr);
297   }
298   memcpy(&listener->flags, flags, sizeof(listener->flags));
299   FlagSet(&listener->flags, LISTEN_ACTIVE);
300   if (mask)
301     ipmask_parse(mask, &listener->mask, &listener->mask_bits);
302   else
303     listener->mask_bits = 0;
304
305 #ifdef IPV6
306   if (FlagHas(&listener->flags, LISTEN_IPV6)) {
307     if (listener->fd_v6 >= 0) {
308       set_listener_options(listener, listener->fd_v6);
309       okay = 1;
310     } else if ((fd = inetport(listener, AF_INET6)) >= 0) {
311       listener->fd_v6 = fd;
312       okay = 1;
313     }
314   } else if (-1 < listener->fd_v6) {
315     close(listener->fd_v6);
316     socket_del(&listener->socket_v6);
317     listener->fd_v6 = -1;
318   }
319 #endif
320
321   if (FlagHas(&listener->flags, LISTEN_IPV4)) {
322     if (listener->fd_v4 >= 0) {
323       set_listener_options(listener, listener->fd_v4);
324       okay = 1;
325     } else if ((fd = inetport(listener, AF_INET)) >= 0) {
326       listener->fd_v4 = fd;
327       okay = 1;
328     }
329   } else if (-1 < listener->fd_v4) {
330     close(listener->fd_v4);
331     socket_del(&listener->socket_v4);
332     listener->fd_v4 = -1;
333   }
334
335   if (!okay)
336     free_listener(listener);
337   else if (new_listener) {
338     listener->next   = ListenerPollList;
339     ListenerPollList = listener;
340   }
341 }
342
343 /** Mark all listeners as closing (inactive).
344  * This is done so unused listeners are closed after a rehash.
345  */
346 void mark_listeners_closing(void)
347 {
348   struct Listener* listener;
349   for (listener = ListenerPollList; listener; listener = listener->next)
350     FlagClr(&listener->flags, LISTEN_ACTIVE);
351 }
352
353 /** Close a single listener.
354  * @param[in] listener Listener to close.
355  */
356 void close_listener(struct Listener* listener)
357 {
358   assert(0 != listener);
359   /*
360    * remove from listener list
361    */
362   if (listener == ListenerPollList)
363     ListenerPollList = listener->next;
364   else {
365     struct Listener* prev = ListenerPollList;
366     for ( ; prev; prev = prev->next) {
367       if (listener == prev->next) {
368         prev->next = listener->next;
369         break; 
370       }
371     }
372   }
373   if (-1 < listener->fd_v4) {
374     close(listener->fd_v4);
375     socket_del(&listener->socket_v4);
376     listener->fd_v4 = -1;
377   }
378   if (-1 < listener->fd_v6) {
379     close(listener->fd_v6);
380     socket_del(&listener->socket_v6);
381     listener->fd_v6 = -1;
382   }
383   free_listener(listener);
384 }
385
386 /** Close all inactive listeners. */
387 void close_listeners(void)
388 {
389   struct Listener* listener;
390   struct Listener* listener_next = 0;
391   /*
392    * close all 'extra' listening ports we have
393    */
394   for (listener = ListenerPollList; listener; listener = listener_next) {
395     listener_next = listener->next;
396     if (!listener_active(listener) && 0 == listener->ref_count)
397       close_listener(listener);
398   }
399 }
400
401 /** Dereference the listener previously associated with a client.
402  * @param[in] listener Listener to dereference.
403  */
404 void release_listener(struct Listener* listener)
405 {
406   assert(0 != listener);
407   assert(0 < listener->ref_count);
408   if (0 == --listener->ref_count && !listener_active(listener))
409     close_listener(listener);
410 }
411
412 /** Accept a connection on a listener.
413  * @param[in] ev Socket callback structure.
414  */
415 static void accept_connection(struct Event* ev)
416 {
417   struct Listener*    listener;
418   struct irc_sockaddr addr;
419   int                 fd;
420
421   assert(0 != ev_socket(ev));
422   assert(0 != s_data(ev_socket(ev)));
423
424   listener = (struct Listener*) s_data(ev_socket(ev));
425
426   if (ev_type(ev) == ET_DESTROY) /* being destroyed */
427     return;
428   else {
429     assert(ev_type(ev) == ET_ACCEPT || ev_type(ev) == ET_ERROR);
430
431     listener->last_accept = CurrentTime;
432     /*
433      * There may be many reasons for error return, but
434      * in otherwise correctly working environment the
435      * probable cause is running out of file descriptors
436      * (EMFILE, ENFILE or others?). The man pages for
437      * accept don't seem to list these as possible,
438      * although it's obvious that it may happen here.
439      * Thus no specific errors are tested at this
440      * point, just assume that connections cannot
441      * be accepted until some old is closed first.
442      *
443      * This piece of code implements multi-accept, based
444      * on the idea that poll/select can only be efficient,
445      * if we succeed in handling all available events,
446      * i.e. accept all pending connections.
447      *
448      * http://www.hpl.hp.com/techreports/2000/HPL-2000-174.html
449      */
450     while (1)
451     {
452       if ((fd = os_accept(s_fd(ev_socket(ev)), &addr)) == -1)
453       {
454         if (errno == EAGAIN ||
455 #ifdef EWOULDBLOCK
456             errno == EWOULDBLOCK)
457 #endif
458           return;
459       /* Lotsa admins seem to have problems with not giving enough file
460        * descriptors to their server so we'll add a generic warning mechanism
461        * here.  If it turns out too many messages are generated for
462        * meaningless reasons we can filter them back.
463        */
464       sendto_opmask_butone(0, SNO_TCPCOMMON,
465                            "Unable to accept connection: %m");
466       return;
467       }
468       /*
469        * check for connection limit. If this fd exceeds the limit,
470        * all further accept()ed connections will also exceed it.
471        * Enable the server to clear out other connections before
472        * continuing to accept() new connections.
473        */
474       if (fd > MAXCLIENTS - 1)
475       {
476         ++ServerStats->is_ref;
477         send(fd, "ERROR :All connections in use\r\n", 32, 0);
478         close(fd);
479         return;
480       }
481       /*
482        * check to see if listener is shutting down. Continue
483        * to accept(), because it makes sense to clear our the
484        * socket's queue as fast as possible.
485        */
486       if (!listener_active(listener))
487       {
488         ++ServerStats->is_ref;
489         send(fd, "ERROR :Use another port\r\n", 25, 0);
490         close(fd);
491         continue;
492       }
493       /*
494        * check to see if connection is allowed for this address mask
495        */
496       if (!ipmask_check(&addr.addr, &listener->mask, listener->mask_bits))
497       {
498         ++ServerStats->is_ref;
499         send(fd, "ERROR :Use another port\r\n", 25, 0);
500         close(fd);
501         continue;
502       }
503       ++ServerStats->is_ac;
504       /* nextping = CurrentTime; */
505       add_connection(listener, fd);
506     }
507   }
508 }