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  */
make_listener(int port,const struct irc_in_addr * addr)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  */
free_listener(struct Listener * listener)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  */
get_listener_name(const struct Listener * listener)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  */
count_listener_memory(int * count_out,size_t * size_out)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  */
show_ports(struct Client * sptr,const struct StatDesc * sd,char * param)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'
150         : listener_webirc(listener) ? 'W'
151         : 'C';
152     if (FlagHas(&listener->flags, LISTEN_HIDDEN))
153     {
154       if (!show_hidden)
155         continue;
156       flags[len++] = 'H';
157     }
158     if (FlagHas(&listener->flags, LISTEN_IPV4))
159     {
160       flags[len++] = '4';
161       if (listener->fd_v4 < 0)
162         flags[len++] = '-';
163     }
164     if (FlagHas(&listener->flags, LISTEN_IPV6))
165     {
166       flags[len++] = '6';
167       if (listener->fd_v6 < 0)
168         flags[len++] = '-';
169     }
170     flags[len] = '\0';
171 
172     send_reply(sptr, RPL_STATSPLINE, listener->addr.port, listener->ref_count,
173 	       flags, listener_active(listener) ? "active" : "disabled");
174     if (--count == 0)
175       break;
176   }
177 }
178 
179 /*
180  * inetport - create a listener socket in the AF_INET domain,
181  * bind it to the port given in 'port' and listen to it
182  * returns true (1) if successful false (0) on error.
183  *
184  * If the operating system has a define for SOMAXCONN, use it, otherwise
185  * use HYBRID_SOMAXCONN -Dianora
186  * NOTE: Do this in os_xxxx.c files
187  */
188 #ifdef SOMAXCONN
189 #define HYBRID_SOMAXCONN SOMAXCONN
190 #else
191 /** Maximum length of socket connection backlog. */
192 #define HYBRID_SOMAXCONN 64
193 #endif
194 
195 /** Set or update socket options for \a listener.
196  * @param[in] listener Listener to determine socket option values.
197  * @param[in] fd File descriptor being updated.
198  * @param[in] family Address family for \a fd.
199  * @return Non-zero on success, zero on failure.
200  */
set_listener_options(struct Listener * listener,int fd,int family)201 static int set_listener_options(struct Listener *listener, int fd, int family)
202 {
203   int is_server;
204 
205   is_server = listener_server(listener);
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                        is_server ? feature_int(FEAT_SOCKSENDBUF) : CLIENT_TCP_WINDOW,
215                        is_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 
221   /*
222    * Set the TOS bits - this is nonfatal if it doesn't stick.
223    */
224   if (!os_set_tos(fd, feature_int(is_server ? FEAT_TOS_SERVER : FEAT_TOS_CLIENT), family)) {
225     report_error(TOS_ERROR_MSG, get_listener_name(listener), errno);
226   }
227 
228   return 1;
229 }
230 
231 /** Open listening socket for \a listener.
232  * @param[in,out] listener Listener to make a socket for.
233  * @param[in] family Socket address family to use.
234  * @return Negative on failure, file descriptor on success.
235  */
inetport(struct Listener * listener,int family)236 static int inetport(struct Listener* listener, int family)
237 {
238   struct Socket *sock;
239   int fd;
240 
241   /*
242    * At first, open a new socket
243    */
244   fd = os_socket(&listener->addr, SOCK_STREAM, get_listener_name(listener), family);
245   if (fd < 0)
246     return -1;
247   if (!os_set_listen(fd, HYBRID_SOMAXCONN)) {
248     report_error(LISTEN_ERROR_MSG, get_listener_name(listener), errno);
249     close(fd);
250     return -1;
251   }
252   if (!set_listener_options(listener, fd, family))
253     return -1;
254   sock = (family == AF_INET) ? &listener->socket_v4 : &listener->socket_v6;
255   if (!socket_add(sock, accept_connection, (void*) listener,
256 		  SS_LISTENING, 0, fd)) {
257     /* Error should already have been reported to the logs */
258     close(fd);
259     return -1;
260   }
261 
262   return fd;
263 }
264 
265 /** Find the listener (if any) for a particular port and address.
266  * @param[in] port Port number to search for.
267  * @param[in] addr Local address to search for.
268  * @return Listener that matches (or NULL if none match).
269  */
find_listener(int port,const struct irc_in_addr * addr)270 static struct Listener* find_listener(int port, const struct irc_in_addr *addr)
271 {
272   struct Listener* listener;
273   for (listener = ListenerPollList; listener; listener = listener->next) {
274     if (port == listener->addr.port && !memcmp(addr, &listener->addr.addr, sizeof(*addr)))
275       return listener;
276   }
277   return 0;
278 }
279 
280 /** Make sure we have a listener for \a port on \a vhost_ip.
281  * If one does not exist, create it.  Then mark it as active and set
282  * the peer mask, server, and hidden flags according to the other
283  * arguments.
284  * @param[in] port Port number to listen on.
285  * @param[in] vhost_ip Local address to listen on.
286  * @param[in] mask Address mask to accept connections from.
287  * @param[in] flags Flags describing listener options.
288  */
add_listener(int port,const char * vhost_ip,const char * mask,const struct ListenerFlags * flags)289 void add_listener(int port, const char* vhost_ip, const char* mask,
290                   const struct ListenerFlags *flags)
291 {
292   struct Listener* listener;
293   struct irc_in_addr vaddr;
294   int okay = 0;
295   int new_listener = 0;
296   int fd;
297 
298   /*
299    * if no port in conf line, don't bother
300    */
301   if (0 == port)
302     return;
303 
304   memset(&vaddr, 0, sizeof(vaddr));
305 
306   if (!EmptyString(vhost_ip)
307       && strcmp(vhost_ip, "*")
308       && !ircd_aton(&vaddr, vhost_ip))
309       return;
310 
311   listener = find_listener(port, &vaddr);
312   if (!listener)
313   {
314     new_listener = 1;
315     listener = make_listener(port, &vaddr);
316   }
317   memcpy(&listener->flags, flags, sizeof(listener->flags));
318   FlagSet(&listener->flags, LISTEN_ACTIVE);
319   if (mask)
320     ipmask_parse(mask, &listener->mask, &listener->mask_bits);
321   else
322     listener->mask_bits = 0;
323 
324 #ifdef IPV6
325   if (FlagHas(&listener->flags, LISTEN_IPV6)
326       && (irc_in_addr_unspec(&vaddr) || !irc_in_addr_is_ipv4(&vaddr))) {
327     if (listener->fd_v6 >= 0) {
328       set_listener_options(listener, listener->fd_v6, AF_INET6);
329       okay = 1;
330     } else if ((fd = inetport(listener, AF_INET6)) >= 0) {
331       listener->fd_v6 = fd;
332       okay = 1;
333     }
334   } else if (-1 < listener->fd_v6) {
335     close(listener->fd_v6);
336     socket_del(&listener->socket_v6);
337     listener->fd_v6 = -1;
338   }
339 #endif
340 
341   if (FlagHas(&listener->flags, LISTEN_IPV4)
342       && (irc_in_addr_unspec(&vaddr) || irc_in_addr_is_ipv4(&vaddr))) {
343     if (listener->fd_v4 >= 0) {
344       set_listener_options(listener, listener->fd_v4, AF_INET);
345       okay = 1;
346     } else if ((fd = inetport(listener, AF_INET)) >= 0) {
347       listener->fd_v4 = fd;
348       okay = 1;
349     }
350   } else if (-1 < listener->fd_v4) {
351     close(listener->fd_v4);
352     socket_del(&listener->socket_v4);
353     listener->fd_v4 = -1;
354   }
355 
356   if (!okay)
357     free_listener(listener);
358   else if (new_listener) {
359     listener->next   = ListenerPollList;
360     ListenerPollList = listener;
361   }
362 }
363 
364 /** Mark all listeners as closing (inactive).
365  * This is done so unused listeners are closed after a rehash.
366  */
mark_listeners_closing(void)367 void mark_listeners_closing(void)
368 {
369   struct Listener* listener;
370   for (listener = ListenerPollList; listener; listener = listener->next)
371     FlagClr(&listener->flags, LISTEN_ACTIVE);
372 }
373 
374 /** Close a single listener.
375  * @param[in] listener Listener to close.
376  */
close_listener(struct Listener * listener)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_v4) {
395     close(listener->fd_v4);
396     socket_del(&listener->socket_v4);
397     listener->fd_v4 = -1;
398   }
399   if (-1 < listener->fd_v6) {
400     close(listener->fd_v6);
401     socket_del(&listener->socket_v6);
402     listener->fd_v6 = -1;
403   }
404   free_listener(listener);
405 }
406 
407 /** Close all inactive listeners. */
close_listeners(void)408 void close_listeners(void)
409 {
410   struct Listener* listener;
411   struct Listener* listener_next = 0;
412   /*
413    * close all 'extra' listening ports we have
414    */
415   for (listener = ListenerPollList; listener; listener = listener_next) {
416     listener_next = listener->next;
417     if (!listener_active(listener) && 0 == listener->ref_count)
418       close_listener(listener);
419   }
420 }
421 
422 /** Dereference the listener previously associated with a client.
423  * @param[in] listener Listener to dereference.
424  */
release_listener(struct Listener * listener)425 void release_listener(struct Listener* listener)
426 {
427   assert(0 != listener);
428   assert(0 < listener->ref_count);
429   if (0 == --listener->ref_count && !listener_active(listener))
430     close_listener(listener);
431 }
432 
433 /** Accept a connection on a listener.
434  * @param[in] ev Socket callback structure.
435  */
accept_connection(struct Event * ev)436 static void accept_connection(struct Event* ev)
437 {
438   struct Listener*    listener;
439   struct irc_sockaddr addr;
440   const char*         msg;
441   int                 fd;
442   int                 len;
443   char                msgbuf[BUFSIZE];
444 
445   assert(0 != ev_socket(ev));
446   assert(0 != s_data(ev_socket(ev)));
447 
448   listener = (struct Listener*) s_data(ev_socket(ev));
449 
450   if (ev_type(ev) == ET_DESTROY) /* being destroyed */
451     return;
452   else {
453     assert(ev_type(ev) == ET_ACCEPT || ev_type(ev) == ET_ERROR);
454 
455     listener->last_accept = CurrentTime;
456     /*
457      * There may be many reasons for error return, but
458      * in otherwise correctly working environment the
459      * probable cause is running out of file descriptors
460      * (EMFILE, ENFILE or others?). The man pages for
461      * accept don't seem to list these as possible,
462      * although it's obvious that it may happen here.
463      * Thus no specific errors are tested at this
464      * point, just assume that connections cannot
465      * be accepted until some old is closed first.
466      *
467      * This piece of code implements multi-accept, based
468      * on the idea that poll/select can only be efficient,
469      * if we succeed in handling all available events,
470      * i.e. accept all pending connections.
471      *
472      * http://www.hpl.hp.com/techreports/2000/HPL-2000-174.html
473      */
474     while (1)
475     {
476       if ((fd = os_accept(s_fd(ev_socket(ev)), &addr)) == -1)
477       {
478         if (errno == EAGAIN) return;
479 #ifdef EWOULDBLOCK
480 	if (errno == EWOULDBLOCK) return;
481 #endif
482       /* Lotsa admins seem to have problems with not giving enough file
483        * descriptors to their server so we'll add a generic warning mechanism
484        * here.  If it turns out too many messages are generated for
485        * meaningless reasons we can filter them back.
486        */
487       sendto_opmask_butone(0, SNO_TCPCOMMON,
488 			   "Unable to accept connection: %m");
489       return;
490       }
491       /*
492        * check for connection limit. If this fd exceeds the limit,
493        * all further accept()ed connections will also exceed it.
494        * Enable the server to clear out other connections before
495        * continuing to accept() new connections.
496        */
497       if (fd > MAXCLIENTS - 1)
498       {
499         msg = "All connections in use";
500         ++ServerStats->is_all_inuse;
501       reject:
502         len = snprintf(msgbuf, sizeof(msgbuf), ":%s ERROR :%s\r\n",
503           cli_name(&me), msg);
504         if (len < sizeof(msgbuf))
505           send(fd, msgbuf, len, 0);
506         close(fd);
507         return;
508       }
509       /*
510        * check to see if listener is shutting down. Continue
511        * to accept(), because it makes sense to clear our the
512        * socket's queue as fast as possible.
513        */
514       if (!listener_active(listener))
515       {
516         msg = "Use another port";
517         ++ServerStats->is_inactive;
518         goto reject;
519       }
520       /*
521        * check to see if connection is allowed for this address mask
522        */
523       if (!ipmask_check(&addr.addr, &listener->mask, listener->mask_bits))
524       {
525         msg = "Use another port";
526         ++ServerStats->is_bad_ip;
527         goto reject;
528       }
529       ++ServerStats->is_ac;
530       /* nextping = CurrentTime; */
531       add_connection(listener, fd);
532     }
533   }
534 }
535