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