Author: ZenShadow
[ircu2.10.12-pk.git] / ircd / ircd.c
1 /*
2  * IRC - Internet Relay Chat, ircd/ircd.c
3  * Copyright (C) 1990 Jarkko Oikarinen and
4  *                    University of Oulu, Computing Center
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 1, or (at your option)
9  * any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  *
20  * $Id$
21  */
22
23
24 /*----------------------------------------------------------------------------
25  * Platform Includes
26  *--------------------------------------------------------------------------*/
27 #include <assert.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <pwd.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sys/socket.h>
35 #include <sys/stat.h>
36 #include <unistd.h>
37 #include <netdb.h>
38
39
40 /*----------------------------------------------------------------------------
41  * ircu Includes
42  *--------------------------------------------------------------------------*/
43 #include "config.h"
44
45 #include "IPcheck.h"
46 #include "class.h"
47 #include "client.h"
48 #include "crule.h"
49 #include "hash.h"
50 #include "ircd.h"
51 #include "ircd_alloc.h"
52 #include "ircd_log.h"
53 #include "ircd_reply.h"
54 #include "ircd_signal.h"
55 #include "ircd_string.h"
56 #include "jupe.h"
57 #include "list.h"
58 #include "match.h"
59 #include "msg.h"
60 #include "numeric.h"
61 #include "numnicks.h"
62 #include "parse.h"
63 #include "res.h"
64 #include "s_auth.h"
65 #include "s_bsd.h"
66 #include "s_conf.h"
67 #include "s_debug.h"
68 #include "s_misc.h"
69 #include "send.h"
70 #include "sys.h"
71 #include "uping.h"
72 #include "userload.h"
73 #include "version.h"
74 #include "whowas.h"
75
76
77 /*----------------------------------------------------------------------------
78  * External stuff
79  *--------------------------------------------------------------------------*/
80 extern void init_counters(void);
81
82 /*----------------------------------------------------------------------------
83  * Constants / Enums
84  *--------------------------------------------------------------------------*/
85 enum {
86   BOOT_DEBUG = 1,
87   BOOT_TTY   = 2
88 };
89
90
91 /*----------------------------------------------------------------------------
92  * Global data (YUCK!)
93  *--------------------------------------------------------------------------*/
94 struct Client  me;                      // That's me
95 struct Client *GlobalClientList  = &me; // Pointer to beginning of Client list
96 time_t         TSoffset          = 0;   // Offset of timestamps to system clock
97 int            GlobalRehashFlag  = 0;   // do a rehash if set
98 int            GlobalRestartFlag = 0;   // do a restart if set
99 time_t         CurrentTime;             // Updated every time we leave select()
100
101 char          *configfile        = CPATH; // Server configuration file
102 int            debuglevel        = -1;    // Server debug level 
103 char          *debugmode         = "";    // Server debug level
104 static char   *dpath             = DPATH;
105
106 time_t         nextconnect       = 1; // time for next try_connections call
107 time_t         nextping          = 1; // same as above for check_pings()
108
109 static struct Daemon thisServer  = { 0 };     // server process info 
110
111
112
113 /*----------------------------------------------------------------------------
114  * API: server_die
115  *--------------------------------------------------------------------------*/
116 void server_die(const char* message) {
117   ircd_log(L_CRIT, "Server terminating: %s", message);
118   sendto_opmask_butone(0, SNO_OLDSNO, "Server terminating: %s", message);
119   flush_connections(0);
120   close_connections(1);
121   thisServer.running = 0;
122 }
123
124
125 /*----------------------------------------------------------------------------
126  * API: server_restart
127  *--------------------------------------------------------------------------*/
128 void server_restart(const char* message) {
129   static int restarting = 0;
130
131   ircd_log(L_WARNING, "Restarting Server: %s", message);
132   if (restarting)
133     return;
134
135   sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
136   Debug((DEBUG_NOTICE, "Restarting server..."));
137   flush_connections(0);
138
139   close_log();
140   close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG)));
141
142   execv(SPATH, thisServer.argv);
143
144   /* Have to reopen since it has been closed above */
145   open_log(*thisServer.argv);
146   ircd_log(L_CRIT, "execv(%s,%s) failed: %m\n", SPATH, *thisServer.argv);
147
148   Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
149          SPATH, (strerror(errno)) ? strerror(errno) : ""));
150   exit(8);
151 }
152
153
154 /*----------------------------------------------------------------------------
155  * outofmemory:  Handler for out of memory conditions...
156  *--------------------------------------------------------------------------*/
157 static void outofmemory(void) {
158   Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
159   server_restart("Out of Memory");
160
161
162
163 /*----------------------------------------------------------------------------
164  * write_pidfile
165  *--------------------------------------------------------------------------*/
166 static void write_pidfile(void) {
167   FILE *pidf;
168
169   if (!(pidf = fopen(PPATH, "w+"))) {
170     Debug((DEBUG_NOTICE, 
171            "Error opening pid file \"%s\": %s", PPATH, strerror(errno)));
172     return;
173   }
174     
175   if (fprintf(pidf, "%5d\n", getpid()) < 5)
176     Debug((DEBUG_NOTICE, "Error writing to pid file %s", PPATH));
177
178   fclose(pidf);
179 }
180
181
182 /*----------------------------------------------------------------------------
183  * try_connections
184  *
185  * Scan through configuration and try new connections.
186  *
187  * Returns the calendar time when the next call to this
188  * function should be made latest. (No harm done if this
189  * is called earlier or later...)
190  *--------------------------------------------------------------------------*/
191 static time_t try_connections(void) {
192   struct ConfItem   *aconf;
193   struct Client     *cptr;
194   struct ConfItem  **pconf;
195   int                connecting;
196   int                confrq;
197   time_t             next        = 0;
198   struct ConfClass  *cltmp;
199   struct ConfItem   *cconf;
200   struct ConfItem   *con_conf    = NULL;
201   struct Jupe       *ajupe;
202   unsigned int       con_class   = 0;
203
204   connecting = FALSE;
205   Debug((DEBUG_NOTICE, "Connection check at   : %s", myctime(CurrentTime)));
206   for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
207     /* Also when already connecting! (update holdtimes) --SRB */
208     if (!(aconf->status & CONF_SERVER) || aconf->port == 0)
209       continue;
210
211     /* Also skip juped servers */
212     if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
213       continue;
214
215     /* Skip this entry if the use of it is still on hold until
216      * future. Otherwise handle this entry (and set it on hold until next
217      * time). Will reset only hold times, if already made one successfull
218      * connection... [this algorithm is a bit fuzzy... -- msa >;) ]
219      */
220     if (aconf->hold > CurrentTime && (next > aconf->hold || next == 0)) {
221       next = aconf->hold;
222       continue;
223     }
224
225     cltmp = aconf->confClass;
226     confrq = get_con_freq(cltmp);
227     aconf->hold = CurrentTime + confrq;
228
229     /* Found a CONNECT config with port specified, scan clients and see if
230      * this server is already connected?
231      */
232     cptr = FindServer(aconf->name);
233
234     if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
235         (!connecting || (ConClass(cltmp) > con_class))) {
236       /* Check connect rules to see if we're allowed to try */
237       for (cconf = GlobalConfList; cconf; cconf = cconf->next) {
238         if ((cconf->status & CONF_CRULE) && !match(cconf->host, aconf->name))
239           if (crule_eval(cconf->passwd))
240             break;
241       }
242       if (!cconf) {
243         con_class = ConClass(cltmp);
244         con_conf = aconf;
245         /* We connect only one at time... */
246         connecting = TRUE;
247       }
248     }
249     if ((next > aconf->hold) || (next == 0))
250       next = aconf->hold;
251   }
252   if (connecting) {
253     if (con_conf->next) { /* are we already last? */
254       /* Put the current one at the end and make sure we try all connections */
255       for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
256         if (aconf == con_conf)
257           *pconf = aconf->next;
258       (*pconf = con_conf)->next = 0;
259     }
260
261     if (connect_server(con_conf, 0, 0))
262       sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
263                            con_conf->name);
264   }
265
266   Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
267   return(next);
268 }
269
270
271 /*----------------------------------------------------------------------------
272  * check_pings
273  *
274  * TODO: This should be moved out of ircd.c.  It's protocol-specific when you
275  *       get right down to it.  Can't really be done until the server is more
276  *       modular, however...
277  *--------------------------------------------------------------------------*/
278 static time_t check_pings(void) {
279   int expire     = 0; 
280   int next_check = CurrentTime + PINGFREQUENCY;
281   int max_ping   = 0;
282   int i;
283   
284   /* Scan through the client table */
285   for (i=0; i <= HighestFd; i++) {
286     struct Client *cptr = LocalClientArray[i];
287    
288     if (!cptr)
289       continue;
290      
291     assert(&me != cptr);  /* I should never be in the local client array! */
292    
293
294     /* Remove dead clients. */
295     if (IsDead(cptr)) {
296       exit_client(cptr, cptr, &me, cptr->info);
297       continue;
298     }
299
300     max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
301    
302     Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
303            cptr->name, (cptr->flags & FLAGS_PINGSENT) ? "[Ping Sent]" : "[]", 
304            max_ping, (int)(CurrentTime - cptr->lasttime)));
305           
306
307     /* Ok, the thing that will happen most frequently, is that someone will
308      * have sent something recently.  Cover this first for speed.
309      */
310     if (CurrentTime-cptr->lasttime < max_ping) {
311       expire = cptr->lasttime + max_ping;
312       if (expire < next_check) 
313         next_check = expire;
314       continue;
315     }
316
317     /* Quit the client after max_ping*2 - they should have answered by now */
318     if (CurrentTime-cptr->lasttime >= (max_ping*2) ) {
319       /* If it was a server, then tell ops about it. */
320       if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
321         sendto_opmask_butone(0, SNO_OLDSNO,
322                              "No response from %s, closing link", cptr->name);
323       exit_client_msg(cptr, cptr, &me, "Ping timeout");
324       continue;
325     }
326     
327     /* Unregistered clients pingout after max_ping seconds, they don't
328      * get given a second chance - if they were then people could not quite
329      * finish registration and hold resources without being subject to k/g
330      * lines
331      */
332     if (!IsRegistered(cptr)) {
333       /* Display message if they have sent a NICK and a USER but no
334        * nospoof PONG.
335        */
336       if (*cptr->name && cptr->user && *cptr->user->username) {
337         send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
338                    ":Your client may not be compatible with this server.");
339         send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
340                    ":Compatible clients are available at "
341                    "ftp://ftp.undernet.org/pub/irc/clients");
342       }    
343       exit_client_msg(cptr,cptr,&me, "Ping Timeout");
344       continue;
345     }
346     
347     if (!(cptr->flags & FLAGS_PINGSENT)) {
348       /* If we havent PINGed the connection and we havent heard from it in a
349        * while, PING it to make sure it is still alive.
350        */
351       cptr->flags |= FLAGS_PINGSENT;
352
353       /* If we're late in noticing don't hold it against them :) */
354       cptr->lasttime = CurrentTime - max_ping;
355       
356       if (IsUser(cptr))
357         sendrawto_one(cptr, MSG_PING " :%s", me.name);
358       else
359         sendcmdto_one(&me, CMD_PING, cptr, ":%s", me.name);
360     }
361     
362     expire = cptr->lasttime + max_ping * 2;
363     if (expire < next_check)
364       next_check=expire;
365   }
366   
367   assert(next_check >= CurrentTime);
368   
369   Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
370          CurrentTime, next_check-CurrentTime));
371   
372   return next_check;
373 }
374
375
376 /*----------------------------------------------------------------------------
377  * parse_command_line
378  *--------------------------------------------------------------------------*/
379 static void parse_command_line(int argc, char** argv) {
380   const char *options = "d:f:h:ntvx:";
381   int opt;
382
383   if (thisServer.euid != thisServer.uid)
384     setuid(thisServer.uid);
385
386   /* Do we really need to santiy check the non-NULLness of optarg?  That's
387    * getopt()'s job...  Removing those... -zs
388    */
389   while ((opt = getopt(argc, argv, options)) != EOF)
390     switch (opt) {
391     case 'n':
392     case 't':  thisServer.bootopt |= BOOT_TTY;         break;
393     case 'd':  dpath      = optarg;                    break;
394     case 'f':  configfile = optarg;                    break;
395     case 'h':  ircd_strncpy(me.name, optarg, HOSTLEN); break;
396     case 'v':  printf("ircd %s\n", version);           exit(0);
397       
398     case 'x':
399       debuglevel = atoi(optarg);
400       if (debuglevel < 0)
401         debuglevel = 0;
402       debugmode = optarg;
403       thisServer.bootopt |= BOOT_DEBUG;
404       break;
405       
406     default:
407       printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
408       printf("\n -n -t\t Don't detach\n -v\t display version\n\n");
409       printf("Server not started.\n");
410       exit(1);
411     }
412 }
413
414
415 /*----------------------------------------------------------------------------
416  * daemon_init
417  *--------------------------------------------------------------------------*/
418 static void daemon_init(int no_fork) {
419   if (!init_connection_limits())
420     exit(9);
421
422   close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
423
424   if (no_fork)
425     return;
426
427   if (fork())
428     exit(0);
429
430 #ifdef TIOCNOTTY
431   {
432     int fd;
433     if ((fd = open("/dev/tty", O_RDWR)) > -1) {
434       ioctl(fd, TIOCNOTTY, 0);
435       close(fd);
436     }
437   }
438 #endif
439
440   setsid();
441 }
442
443
444 /*----------------------------------------------------------------------------
445  * event_loop
446  *--------------------------------------------------------------------------*/
447 static void event_loop(void) {
448   time_t nextdnscheck = 0;
449   time_t delay        = 0;
450
451   thisServer.running = 1;
452   while (thisServer.running) {
453     /* We only want to connect if a connection is due, not every time through.
454      * Note, if there are no active C lines, this call to Tryconnections is
455      * made once only; it will return 0. - avalon
456      */
457     if (nextconnect && CurrentTime >= nextconnect)
458       nextconnect = try_connections();
459
460     /* DNS checks. One to timeout queries, one for cache expiries. */
461     nextdnscheck = timeout_resolver(CurrentTime);
462
463     /* Take the smaller of the two 'timed' event times as the time of next
464      * event (stops us being late :) - avalon
465      * WARNING - nextconnect can return 0!
466      */
467     if (nextconnect)
468       delay = IRCD_MIN(nextping, nextconnect);
469     else
470       delay = nextping;
471
472     delay = IRCD_MIN(nextdnscheck, delay) - CurrentTime;
473
474     /* Adjust delay to something reasonable [ad hoc values] (one might think
475      * something more clever here... --msa) We don't really need to check that
476      * often and as long as we don't delay too long, everything should be ok.
477      * waiting too long can cause things to timeout...  i.e. PINGS -> a
478      * disconnection :( - avalon
479      */
480     if (delay < 1)
481       read_message(1);
482     else
483       read_message(IRCD_MIN(delay, TIMESEC));
484
485     Debug((DEBUG_DEBUG, "Got message(s)"));
486
487     /* ...perhaps should not do these loops every time, but only if there is
488      * some chance of something happening (but, note that conf->hold times may
489      * be changed elsewhere--so precomputed next event time might be too far
490      * away... (similarly with ping times) --msa
491      */
492     if (CurrentTime >= nextping)
493       nextping = check_pings();
494     
495     /* timeout pending queries that haven't been responded to */
496     timeout_auth_queries(CurrentTime);
497
498     ip_registry_expire();
499
500     if (GlobalRehashFlag) {
501       rehash(&me, 1);
502       GlobalRehashFlag = 0;
503     }
504
505     if (GlobalRestartFlag)
506       server_restart("caught signal: SIGINT");
507   }
508 }
509
510
511 /*----------------------------------------------------------------------------
512  * check_file_access:  random helper function to make sure that a file is
513  *                     accessible in a certain way, and complain if not.
514  *--------------------------------------------------------------------------*/
515 static char check_file_access(const char *path, char which, int mode) {
516   if (!access(path, mode))
517     return 1;
518
519   fprintf(stderr, 
520           "Check on %cPATH (%s) failed: %s\n"
521           "Please create file and/or rerun `make config' and "
522           "recompile to correct this.\n",
523           which, path, strerror(errno));
524
525 #ifdef CHROOTDIR
526   fprintf(stderr, "Keep in mind that paths are relative to CHROOTDIR.\n");
527 #endif
528
529   return 0;
530 }
531
532
533 /*----------------------------------------------------------------------------
534  * set_core_limit
535  *--------------------------------------------------------------------------*/
536 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
537 static void set_core_limit(void) {
538   struct rlimit corelim;
539
540   if (getrlimit(RLIMIT_CORE, &corelim)) {
541     fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
542     corelim.rlim_max = RLIM_INFINITY;   /* Try to recover */
543   }
544
545   corelim.rlim_cur = corelim.rlim_max;
546   if (setrlimit(RLIMIT_CORE, &corelim))
547     fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
548 }
549 #endif
550
551
552
553 /*----------------------------------------------------------------------------
554  * set_chroot_environment
555  *--------------------------------------------------------------------------*/
556 #ifdef CHROOTDIR
557 static char set_chroot_environment(void) {
558   /* Must be root to chroot! Silly if you ask me... */
559   if (geteuid())
560     seteuid(0);
561
562   if (chdir(DPATH)) {
563     fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", DPATH, strerror(errno));
564     return 0;
565   }
566   if (chroot(DPATH)) {
567     fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", DPATH, strerror(errno));
568     return 0;
569   }
570   dpath = "/";
571   return 1;
572 }
573 #endif
574
575
576 /*----------------------------------------------------------------------------
577  * set_userid_if_needed()
578  *--------------------------------------------------------------------------*/
579 static int set_userid_if_needed(void) {
580   /* TODO: Drop privs correctly! */
581 #if defined(IRC_GID) && defined(IRC_UID)
582   setgid (IRC_GID);
583   setegid(IRC_GID);
584   setuid (IRC_UID);
585   seteuid(IRC_UID);
586 #endif
587
588   if (getuid() == 0 || geteuid() == 0 ||
589       getgid() == 0 || getegid() == 0) {
590     fprintf(stderr, "ERROR:  This server will not run as superuser.\n");
591     return 0;
592   }
593
594   return 1;
595 }
596
597
598 /*----------------------------------------------------------------------------
599  * main - entrypoint
600  *
601  * TODO:  This should set the basic environment up and start the main loop.
602  *        we're doing waaaaaaaaay too much server initialization here.  I hate
603  *        long and ugly control paths...  -smd
604  *--------------------------------------------------------------------------*/
605 int main(int argc, char **argv) {
606   CurrentTime = time(NULL);
607
608   thisServer.argc = argc;
609   thisServer.argv = argv;
610   thisServer.uid  = getuid();
611   thisServer.euid = geteuid();
612
613 #ifdef CHROOTDIR
614   if (!set_chroot_environment())
615     exit(1);
616 #endif
617
618 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
619   set_core_limit();
620 #endif
621
622   umask(077);                   /* better safe than sorry --SRB */
623   memset(&me, 0, sizeof(me));
624   me.fd = -1;
625
626   setup_signals();
627   initload();
628
629   parse_command_line(argc, argv);
630
631   if (chdir(dpath)) {
632     fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, strerror(errno));
633     exit(2);
634   }
635
636   if (!set_userid_if_needed())
637     exit(3);
638
639   /* Check paths for accessibility */
640   if (!check_file_access(SPATH, 'S', X_OK) ||
641       !check_file_access(CPATH, 'C', R_OK) ||
642       !check_file_access(MPATH, 'M', R_OK) ||
643       !check_file_access(RPATH, 'R', R_OK))
644     exit(4);
645       
646 #ifdef DEBUG
647   if (!check_file_access(LPATH, 'L', W_OK))
648     exit(5);
649 #endif
650
651   init_list();
652   hash_init();
653   initclass();
654   initwhowas();
655   initmsgtree();
656   initstats();
657
658   debug_init(thisServer.bootopt & BOOT_TTY);
659   daemon_init(thisServer.bootopt & BOOT_TTY);
660
661   set_nomem_handler(outofmemory);
662   init_resolver();
663
664   open_log(*argv);
665
666   if (!conf_init()) {
667     Debug((DEBUG_FATAL, "Failed to read configuration file %s", configfile));
668     printf("Couldn't open configuration file %s\n", configfile);
669     exit(6);
670   }
671
672   if (!init_server_identity()) {
673     Debug((DEBUG_FATAL, "Failed to initialize server identity"));
674     exit(7);
675   }
676
677   uping_init();
678   read_tlines();
679
680   rmotd       = read_motd(RPATH);
681   motd        = read_motd(MPATH);
682   CurrentTime = time(NULL);
683   me.from     = &me;
684
685   SetMe(&me);
686   make_server(&me);
687
688   me.serv->timestamp = TStime();  /* Abuse own link timestamp as start TS */
689   me.serv->prot      = atoi(MAJOR_PROTOCOL);
690   me.serv->up        = &me;
691   me.serv->down      = NULL;
692   me.handler         = SERVER_HANDLER;
693
694   SetYXXCapacity(&me, MAXCLIENTS);
695
696   me.lasttime = me.since = me.firsttime = CurrentTime;
697
698   hAddClient(&me);
699
700   check_class();
701   write_pidfile();
702   init_counters();
703
704   Debug((DEBUG_NOTICE, "Server ready..."));
705   ircd_log(L_NOTICE, "Server Ready");
706
707   event_loop();
708
709   return 0;
710 }
711
712