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