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