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