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