f7802879162604ab47e1753fdea3105b191c6716
[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  *  $Id$
20  */
21 #include "config.h"
22
23 #include "listener.h"
24 #include "client.h"
25 #include "ircd.h"
26 #include "ircd_alloc.h"
27 #include "ircd_events.h"
28 #include "ircd_features.h"
29 #include "ircd_osdep.h"
30 #include "ircd_reply.h"
31 #include "ircd_string.h"
32 #include "numeric.h"
33 #include "s_bsd.h"
34 #include "s_conf.h"
35 #include "s_misc.h"
36 #include "send.h"
37 #include "sprintf_irc.h"
38 #include "sys.h"         /* MAXCLIENTS */
39
40 #include <assert.h>
41 #include <stdio.h>
42 #include <string.h>
43 #include <errno.h>
44 #include <stdlib.h>
45 #include <unistd.h>
46 #include <netdb.h>
47 #include <sys/socket.h>
48 #include <arpa/inet.h>
49
50 #ifndef INADDR_NONE
51 #define INADDR_NONE ((unsigned int) 0xffffffff)
52 #endif
53
54 struct Listener* ListenerPollList = 0;
55
56 static void accept_connection(struct Event* ev);
57
58 static struct Listener* make_listener(int port, struct in_addr addr)
59 {
60   struct Listener* listener = 
61     (struct Listener*) MyMalloc(sizeof(struct Listener));
62   assert(0 != listener);
63
64   memset(listener, 0, sizeof(struct Listener));
65
66   listener->fd          = -1;
67   listener->port        = port;
68   listener->addr.s_addr = addr.s_addr;
69
70 #ifdef NULL_POINTER_NOT_ZERO
71   listener->next = NULL;
72   listener->conf = NULL;
73 #endif
74   return listener;
75 }
76
77 static void free_listener(struct Listener* listener)
78 {
79   assert(0 != listener);
80   MyFree(listener);
81 }
82
83 #define PORTNAMELEN 10  /* ":31337" */
84
85 /*
86  * get_listener_name - return displayable listener name and port
87  * returns "host.foo.org:6667" for a given listener
88  */
89 const char* get_listener_name(const struct Listener* listener)
90 {
91   static char buf[HOSTLEN + PORTNAMELEN + 4];
92   assert(0 != listener);
93   sprintf_irc(buf, "%s:%u", cli_name(&me), listener->port);
94   return buf;
95 }
96
97 /*
98  * count_listener_memory - count memory and listeners
99  */
100 void count_listener_memory(int* count_out, size_t* size_out)
101 {
102   struct Listener* l;
103   int              count = 0;
104   assert(0 != count_out);
105   assert(0 != size_out);
106   for (l = ListenerPollList; l; l = l->next)
107     ++count;
108   *count_out = count;
109   *size_out  = count * sizeof(struct Listener);
110 }
111   
112 /*
113  * show_ports - send port listing to a client
114  * inputs       - pointer to client to show ports to
115  * output       - none
116  * side effects - show ports
117  * author       - Dianora
118  */
119 void show_ports(struct Client* sptr, int show_hidden, int port, int count)
120 {
121   struct Listener* listener = 0;
122   char             flags[8];
123   assert(0 != sptr);
124
125   for (listener = ListenerPollList; listener; listener = listener->next) {
126     if (port && port != listener->port)
127       continue;
128     flags[0] = (listener->server) ? 'S' : 'C';
129     if (listener->hidden) {
130       if (!show_hidden)
131         continue;
132       flags[1] = 'H';
133       flags[2] = '\0';
134     }
135     else
136       flags[1] = '\0';
137
138     send_reply(sptr, RPL_STATSPLINE, listener->port, listener->ref_count,
139                flags, (listener->active) ? "active" : "disabled");
140     if (--count == 0)
141       break;
142   }
143 }
144
145 /*
146  * inetport - create a listener socket in the AF_INET domain, 
147  * bind it to the port given in 'port' and listen to it  
148  * returns true (1) if successful false (0) on error.
149  *
150  * If the operating system has a define for SOMAXCONN, use it, otherwise
151  * use HYBRID_SOMAXCONN -Dianora
152  * NOTE: Do this in os_xxxx.c files
153  */
154 #ifdef SOMAXCONN
155 #define HYBRID_SOMAXCONN SOMAXCONN
156 #else
157 #define HYBRID_SOMAXCONN 64
158 #endif
159
160 static int inetport(struct Listener* listener)
161 {
162   struct sockaddr_in sin;
163   int                fd;
164
165   /*
166    * At first, open a new socket
167    */
168   if (-1 == (fd = socket(AF_INET, SOCK_STREAM, 0))) {
169     report_error(SOCKET_ERROR_MSG, get_listener_name(listener), errno);
170     return 0;
171   }
172   else if (fd > MAXCLIENTS - 1) {
173     report_error(CONNLIMIT_ERROR_MSG, get_listener_name(listener), 0);
174     close(fd);
175     return 0;
176   }
177
178   if (!os_set_reuseaddr(fd)) {
179     report_error(REUSEADDR_ERROR_MSG, get_listener_name(listener), errno);
180     close(fd);
181     return 0;
182   }
183   /*
184    * Bind a port to listen for new connections if port is non-null,
185    * else assume it is already open and try get something from it.
186    */
187   memset(&sin, 0, sizeof(sin));
188   sin.sin_family = AF_INET;
189   sin.sin_addr   = listener->addr;
190   sin.sin_port   = htons(listener->port);
191
192   if (bind(fd, (struct sockaddr*) &sin, sizeof(sin))) {
193     report_error(BIND_ERROR_MSG, get_listener_name(listener), errno);
194     close(fd);
195     return 0;
196   }
197   /*
198    * Set the buffer sizes for the listener. Accepted connections
199    * inherit the accepting sockets settings for SO_RCVBUF S_SNDBUF
200    * The window size is set during the SYN ACK so setting it anywhere
201    * else has no effect whatsoever on the connection.
202    * NOTE: this must be set before listen is called
203    */
204   if (!os_set_sockbufs(fd, (listener->server) ? SERVER_TCP_WINDOW : CLIENT_TCP_WINDOW)) {
205     report_error(SETBUFS_ERROR_MSG, get_listener_name(listener), errno);
206     close(fd);
207     return 0;
208   }
209   if (!os_set_listen(fd, HYBRID_SOMAXCONN)) {
210     report_error(LISTEN_ERROR_MSG, get_listener_name(listener), errno);
211     close(fd);
212     return 0;
213   }
214   /*
215    * XXX - this should always work, performance will suck if it doesn't
216    */
217   if (!os_set_nonblocking(fd)) {
218     report_error(NONB_ERROR_MSG, get_listener_name(listener), errno);
219     close(fd);
220     return 0;
221   }
222   /*
223    * Set the TOS bits - this is nonfatal if it doesn't stick.
224    */
225   if (!os_set_tos(fd,feature_int((listener->server)?FEAT_TOS_SERVER : FEAT_TOS_CLIENT))) {
226     report_error(TOS_ERROR_MSG, get_listener_name(listener), errno);
227   }
228
229   if (!socket_add(&listener->socket, accept_connection, (void*) listener,
230                   SS_LISTENING, 0, fd)) {
231     /* Error should already have been reported to the logs */
232     close(fd);
233     return 0;
234   }
235
236   listener->fd = fd;
237
238   return 1;
239 }
240
241 /*
242  * find_listener - find a listener in the list
243  *
244  * XXX - this function does N comparisons so if the list is huge
245  * we may want to do something else for this. (rehash and init use this)
246  */
247 static struct Listener* find_listener(int port, struct in_addr addr)
248 {
249   struct Listener* listener;
250   for (listener = ListenerPollList; listener; listener = listener->next) {
251     if (port == listener->port && addr.s_addr == listener->addr.s_addr)
252       return listener;
253   }
254   return 0;
255 }
256
257 /*
258  * set_listener_mask - set the connection mask for this listener
259  */
260 static void set_listener_mask(struct Listener* listener, const char* mask)
261 {
262   int  ad[4];
263   char ipname[20];
264
265   assert(0 != listener);
266
267   if (EmptyString(mask) || 0 == strcmp(mask, "*")) {
268     listener->mask.s_addr = 0;
269     return;
270   }
271   ad[0] = ad[1] = ad[2] = ad[3] = 0;
272   /*
273    * do it this way because building ip# from separate values for each
274    * byte requires endian knowledge or some nasty messing. Also means
275    * easy conversion of "*" 0.0.0.0 or 134.* to 134.0.0.0 :-)
276    */
277   sscanf(mask, "%d.%d.%d.%d", &ad[0], &ad[1], &ad[2], &ad[3]);
278   sprintf_irc(ipname, "%d.%d.%d.%d", ad[0], ad[1], ad[2], ad[3]);
279   listener->mask.s_addr = inet_addr(ipname);
280 }
281
282 /*
283  * connection_allowed - spin through mask and addr passed to see if connect 
284  * allowed on a listener, uses mask generated by set_listener_mask
285  */
286 static int connection_allowed(const char* addr, const char* mask)
287 {
288   int i = 4;
289   for ( ; i > 0; --i) {
290     if (*mask && *addr != *mask)
291       break;
292     ++addr;
293     ++mask;
294   }
295   return (0 == i);
296 }
297
298
299 /*
300  * add_listener- create a new listener 
301  * port - the port number to listen on
302  * vhost_ip - if non-null must contain a valid IP address string in
303  * the format "255.255.255.255"
304  */
305 void add_listener(int port, const char* vhost_ip, const char* mask,
306                   int is_server, int is_hidden) 
307 {
308   struct Listener* listener;
309   struct in_addr   vaddr;
310
311   /*
312    * if no port in conf line, don't bother
313    */
314   if (0 == port)
315     return;
316
317   vaddr.s_addr = INADDR_ANY;
318
319   if (!EmptyString(vhost_ip) && strcmp(vhost_ip,"*") != 0) {
320     vaddr.s_addr = inet_addr(vhost_ip);
321     if (INADDR_NONE == vaddr.s_addr)
322       return;
323   }
324
325   if ((listener = find_listener(port, vaddr))) {
326     /*
327      * set active flag and change connect mask here, it's the only thing 
328      * that can change on a rehash
329      */
330     listener->active = 1;
331     set_listener_mask(listener, mask);
332     listener->hidden = is_hidden;
333     listener->server = is_server;
334     return;
335   }
336
337   listener = make_listener(port, vaddr);
338
339   if (inetport(listener)) {
340     listener->active = 1;
341     set_listener_mask(listener, mask);
342     listener->hidden = is_hidden;
343     listener->server = is_server;
344     listener->next   = ListenerPollList;
345     ListenerPollList = listener; 
346   }
347   else
348     free_listener(listener);
349 }
350
351 /*
352  * mark_listeners_closing - iterate through listeners and mark them as
353  * inactive
354  */
355 void mark_listeners_closing(void)
356 {
357   struct Listener* listener;
358   for (listener = ListenerPollList; listener; listener = listener->next)
359     listener->active = 0;
360 }
361
362 /*
363  * close_listener - close a single listener
364  */
365 void close_listener(struct Listener* listener)
366 {
367   assert(0 != listener);
368   /*
369    * remove from listener list
370    */
371   if (listener == ListenerPollList)
372     ListenerPollList = listener->next;
373   else {
374     struct Listener* prev = ListenerPollList;
375     for ( ; prev; prev = prev->next) {
376       if (listener == prev->next) {
377         prev->next = listener->next;
378         break; 
379       }
380     }
381   }
382   if (-1 < listener->fd)
383     close(listener->fd);
384   socket_del(&listener->socket);
385 }
386  
387 /*
388  * close_listeners - close and free all listeners that are not being used
389  */
390 void close_listeners()
391 {
392   struct Listener* listener;
393   struct Listener* listener_next = 0;
394   /*
395    * close all 'extra' listening ports we have
396    */
397   for (listener = ListenerPollList; listener; listener = listener_next) {
398     listener_next = listener->next;
399     if (0 == listener->active && 0 == listener->ref_count)
400       close_listener(listener);
401   }
402 }
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)
409     close_listener(listener);
410 }
411
412 /*
413  * accept_connection - accept a connection on a listener
414  */
415 static void accept_connection(struct Event* ev)
416 {
417   struct Listener* listener;
418   struct sockaddr_in addr = { 0 };
419   unsigned int       addrlen = sizeof(struct sockaddr_in);
420   int                fd;
421
422   assert(0 != ev_socket(ev));
423   assert(0 != s_data(ev_socket(ev)));
424
425   listener = s_data(ev_socket(ev));
426
427   if (ev_type(ev) == ET_DESTROY) /* being destroyed */
428     free_listener(listener);
429   else {
430     assert(ev_type(ev) == ET_ACCEPT);
431
432     listener->last_accept = CurrentTime;
433     /*
434      * There may be many reasons for error return, but
435      * in otherwise correctly working environment the
436      * probable cause is running out of file descriptors
437      * (EMFILE, ENFILE or others?). The man pages for
438      * accept don't seem to list these as possible,
439      * although it's obvious that it may happen here.
440      * Thus no specific errors are tested at this
441      * point, just assume that connections cannot
442      * be accepted until some old is closed first.
443      */
444     if (-1 == (fd = accept(listener->fd, (struct sockaddr*) &addr,
445                            &addrlen))) {
446       /* Lotsa admins seem to have problems with not giving enough file
447        * descriptors to their server so we'll add a generic warning mechanism
448        * here.  If it turns out too many messages are generated for
449        * meaningless reasons we can filter them back.
450        */
451       sendto_opmask_butone(0, SNO_TCPCOMMON,
452                            "Unable to accept connection: %m");
453       return;
454     }
455     /*
456      * check for connection limit
457      */
458     if (fd > MAXCLIENTS - 1) {
459       ++ServerStats->is_ref;
460       send(fd, "ERROR :All connections in use\r\n", 32, 0);
461       close(fd);
462       return;
463     }
464     /*
465      * check to see if listener is shutting down
466      */
467     if (!listener->active) {
468       ++ServerStats->is_ref;
469       send(fd, "ERROR :Use another port\r\n", 25, 0);
470       close(fd);
471       return;
472     }
473     /*
474      * check to see if connection is allowed for this address mask
475      */
476     if (!connection_allowed((const char*) &addr,
477                             (const char*) &listener->mask)) {
478       ++ServerStats->is_ref;
479       send(fd, "ERROR :Use another port\r\n", 25, 0);
480       close(fd);
481       return;
482     }
483 #if 0
484     /*
485      * check conf for ip address access
486      */
487     if (!conf_connect_allowed(addr.sin_addr)) {
488       ++ServerStats->is_ref;
489       send(fd, "ERROR :Not authorized\r\n", 23, 0);
490       close(fd);
491       return;
492     }
493 #endif
494     ++ServerStats->is_ac;
495 /*      nextping = CurrentTime; */
496
497     add_connection(listener, fd);
498   }
499 }