2004-05-09 Michael Poole <mdpoole@troilus.org>
[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 "config.h"
23
24 #include "ircd.h"
25 #include "IPcheck.h"
26 #include "class.h"
27 #include "client.h"
28 #include "crule.h"
29 #include "destruct_event.h"
30 #include "hash.h"
31 #include "ircd_alloc.h"
32 #include "ircd_events.h"
33 #include "ircd_features.h"
34 #include "ircd_log.h"
35 #include "ircd_reply.h"
36 #include "ircd_signal.h"
37 #include "ircd_string.h"
38 #include "jupe.h"
39 #include "list.h"
40 #include "match.h"
41 #include "motd.h"
42 #include "msg.h"
43 #include "numeric.h"
44 #include "numnicks.h"
45 #include "opercmds.h"
46 #include "parse.h"
47 #include "res.h"
48 #include "s_auth.h"
49 #include "s_bsd.h"
50 #include "s_conf.h"
51 #include "s_debug.h"
52 #include "s_misc.h"
53 #include "s_stats.h"
54 #include "send.h"
55 #include "sys.h"
56 #include "uping.h"
57 #include "userload.h"
58 #include "version.h"
59 #include "whowas.h"
60
61 #include <assert.h>
62 #include <errno.h>
63 #include <fcntl.h>
64 #include <netdb.h>
65 #include <pwd.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <sys/socket.h>
70 #include <sys/stat.h>
71 #include <sys/types.h>
72 #include <unistd.h>
73
74
75
76 /*----------------------------------------------------------------------------
77  * External stuff
78  *--------------------------------------------------------------------------*/
79 extern void init_counters(void);
80 extern void mem_dbg_initialise(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 Connection me_con;               /* That's me too */
96 struct Client *GlobalClientList  = &me; /* Pointer to beginning of
97                                            Client list */
98 time_t         TSoffset          = 0;/* Offset of timestamps to system clock */
99 int            GlobalRehashFlag  = 0;   /* do a rehash if set */
100 int            GlobalRestartFlag = 0;   /* do a restart if set */
101 time_t         CurrentTime;          /* Updated every time we leave select() */
102
103 char          *configfile        = CPATH; /* Server configuration file */
104 int            debuglevel        = -1;    /* Server debug level  */
105 char          *debugmode         = "";    /* Server debug level */
106 static char   *dpath             = DPATH;
107
108 static struct Timer connect_timer; /* timer structure for try_connections() */
109 static struct Timer ping_timer; /* timer structure for check_pings() */
110 static struct Timer destruct_event_timer; /* timer structure for exec_expired_destruct_events() */
111
112 static struct Daemon thisServer  = { 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0 };
113
114 int running = 1;
115
116
117 /*----------------------------------------------------------------------------
118  * API: server_die
119  *--------------------------------------------------------------------------*/
120 void server_die(const char *message)
121 {
122   /* log_write will send out message to both log file and as server notice */
123   log_write(LS_SYSTEM, L_CRIT, 0, "Server terminating: %s", message);
124   flush_connections(0);
125   close_connections(1);
126   running = 0;
127 }
128
129 /*----------------------------------------------------------------------------
130  * API: server_panic
131  *--------------------------------------------------------------------------*/
132 void server_panic(const char *message)
133 {
134   /* inhibit sending server notice--we may be panicing due to low memory */
135   log_write(LS_SYSTEM, L_CRIT, LOG_NOSNOTICE, "Server panic: %s", message);
136   flush_connections(0);
137   log_close();
138   close_connections(1);
139   exit(1);
140 }
141
142 /*----------------------------------------------------------------------------
143  * API: server_restart
144  *--------------------------------------------------------------------------*/
145 void server_restart(const char *message)
146 {
147   static int restarting = 0;
148
149   /* inhibit sending any server notices; we may be in a loop */
150   log_write(LS_SYSTEM, L_WARNING, LOG_NOSNOTICE, "Restarting Server: %s",
151             message);
152   if (restarting++) /* increment restarting to prevent looping */
153     return;
154
155   sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
156   Debug((DEBUG_NOTICE, "Restarting server..."));
157   flush_connections(0);
158
159   log_close();
160
161   close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG)));
162
163   execv(SPATH, thisServer.argv);
164
165   /* Have to reopen since it has been closed above */
166   log_reopen();
167
168   log_write(LS_SYSTEM, L_CRIT, 0, "execv(%s,%s) failed: %m", SPATH,
169             *thisServer.argv);
170
171   Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
172          SPATH, (strerror(errno)) ? strerror(errno) : ""));
173   exit(8);
174 }
175
176
177 /*----------------------------------------------------------------------------
178  * outofmemory:  Handler for out of memory conditions...
179  *--------------------------------------------------------------------------*/
180 static void outofmemory(void) {
181   Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
182   server_restart("Out of Memory");
183
184
185
186 /*----------------------------------------------------------------------------
187  * write_pidfile
188  *--------------------------------------------------------------------------*/
189 static void write_pidfile(void) {
190   char buff[20];
191
192   if (thisServer.pid_fd >= 0) {
193     memset(buff, 0, sizeof(buff));
194     sprintf(buff, "%5d\n", (int)getpid());
195     if (write(thisServer.pid_fd, buff, strlen(buff)) == -1)
196       Debug((DEBUG_NOTICE, "Error writing to pid file %s: %m",
197              feature_str(FEAT_PPATH)));
198     return;
199   }
200   Debug((DEBUG_NOTICE, "Error opening pid file %s: %m",
201          feature_str(FEAT_PPATH)));
202 }
203
204 /* check_pid
205  * 
206  * inputs: 
207  *   none
208  * returns:
209  *   true - if the pid file exists (and is readable), and the pid refered
210  *          to in the file is still running.
211  *   false - otherwise.
212  */
213 static int check_pid(void)
214 {
215   struct flock lock;
216
217   lock.l_type = F_WRLCK;
218   lock.l_start = 0;
219   lock.l_whence = SEEK_SET;
220   lock.l_len = 0;
221
222   if ((thisServer.pid_fd = open(feature_str(FEAT_PPATH), O_CREAT | O_RDWR,
223                                 0600)) >= 0)
224     return fcntl(thisServer.pid_fd, F_SETLK, &lock);
225
226   return 0;
227 }
228   
229
230 /*----------------------------------------------------------------------------
231  * try_connections
232  *
233  * Scan through configuration and try new connections.
234  *
235  * Returns the calendar time when the next call to this
236  * function should be made latest. (No harm done if this
237  * is called earlier or later...)
238  *--------------------------------------------------------------------------*/
239 static void try_connections(struct Event* ev) {
240   struct ConfItem*  aconf;
241   struct Client*    cptr;
242   struct ConfItem** pconf;
243   int               connecting;
244   int               confrq;
245   time_t            next        = 0;
246   struct ConnectionClass* cltmp;
247   struct ConfItem*  con_conf    = 0;
248   struct Jupe*      ajupe;
249   const char*       con_class   = NULL;
250
251   assert(ET_EXPIRE == ev_type(ev));
252   assert(0 != ev_timer(ev));
253
254   connecting = FALSE;
255   Debug((DEBUG_NOTICE, "Connection check at   : %s", myctime(CurrentTime)));
256   for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
257     /* Also when already connecting! (update holdtimes) --SRB */
258     if (!(aconf->status & CONF_SERVER) || aconf->port == 0 || aconf->hold == 0)
259       continue;
260
261     /* Also skip juped servers */
262     if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
263       continue;
264
265     /* Skip this entry if the use of it is still on hold until
266      * future. Otherwise handle this entry (and set it on hold until next
267      * time). Will reset only hold times, if already made one successfull
268      * connection... [this algorithm is a bit fuzzy... -- msa >;) ]
269      */
270     if (aconf->hold > CurrentTime && (next > aconf->hold || next == 0)) {
271       next = aconf->hold;
272       continue;
273     }
274
275     cltmp = aconf->conn_class;
276     confrq = get_con_freq(cltmp);
277     if(confrq == 0)
278       aconf->hold = next = 0;
279     else
280       aconf->hold = CurrentTime + confrq;
281
282     /* Found a CONNECT config with port specified, scan clients and see if
283      * this server is already connected?
284      */
285     cptr = FindServer(aconf->name);
286
287     if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
288         (!connecting /*|| (ConClass(cltmp) > con_class)*/)) {
289       /*
290        * Check connect rules to see if we're allowed to try
291        */
292       if (0 == conf_eval_crule(aconf->name, CRULE_MASK)) {
293         con_class = ConClass(cltmp);
294         con_conf = aconf;
295         /* We connect only one at time... */
296         connecting = TRUE;
297       }
298     }
299     if ((next > aconf->hold) || (next == 0))
300       next = aconf->hold;
301   }
302   if (connecting) {
303     if (con_conf->next) { /* are we already last? */
304       /* Put the current one at the end and make sure we try all connections */
305       for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
306         if (aconf == con_conf)
307           *pconf = aconf->next;
308       (*pconf = con_conf)->next = 0;
309     }
310
311     if (connect_server(con_conf, 0))
312       sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
313                            con_conf->name);
314   }
315
316   if (next == 0)
317     next = CurrentTime + feature_int(FEAT_CONNECTFREQUENCY);
318
319   Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
320
321   timer_add(&connect_timer, try_connections, 0, TT_ABSOLUTE, next);
322 }
323
324
325 /*----------------------------------------------------------------------------
326  * check_pings
327  *
328  * TODO: This should be moved out of ircd.c.  It's protocol-specific when you
329  *       get right down to it.  Can't really be done until the server is more
330  *       modular, however...
331  *--------------------------------------------------------------------------*/
332 static void check_pings(struct Event* ev) {
333   int expire     = 0;
334   int next_check = CurrentTime;
335   int max_ping   = 0;
336   int i;
337
338   assert(ET_EXPIRE == ev_type(ev));
339   assert(0 != ev_timer(ev));
340
341   next_check += feature_int(FEAT_PINGFREQUENCY);
342   
343   /* Scan through the client table */
344   for (i=0; i <= HighestFd; i++) {
345     struct Client *cptr = LocalClientArray[i];
346    
347     if (!cptr)
348       continue;
349      
350     assert(&me != cptr);  /* I should never be in the local client array! */
351    
352
353     /* Remove dead clients. */
354     if (IsDead(cptr)) {
355       exit_client(cptr, cptr, &me, cli_info(cptr));
356       continue;
357     }
358
359     max_ping = IsRegistered(cptr) ? client_get_ping(cptr) :
360       feature_int(FEAT_CONNECTTIMEOUT);
361    
362     Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
363            cli_name(cptr),
364            IsPingSent(cptr) ? "[Ping Sent]" : "[]", 
365            max_ping, (int)(CurrentTime - cli_lasttime(cptr))));
366           
367
368     /* Ok, the thing that will happen most frequently, is that someone will
369      * have sent something recently.  Cover this first for speed.
370      */
371     if (CurrentTime-cli_lasttime(cptr) < max_ping) {
372       expire = cli_lasttime(cptr) + max_ping;
373       if (expire < next_check) 
374         next_check = expire;
375       continue;
376     }
377
378     /* Quit the client after max_ping*2 - they should have answered by now */
379     if (CurrentTime-cli_lasttime(cptr) >= (max_ping*2) )
380     {
381       /* If it was a server, then tell ops about it. */
382       if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
383         sendto_opmask_butone(0, SNO_OLDSNO,
384                              "No response from %s, closing link",
385                              cli_name(cptr));
386       exit_client_msg(cptr, cptr, &me, "Ping timeout");
387       continue;
388     }
389
390     /* Unregistered clients pingout after max_ping seconds, they don't
391      * get given a second chance - if they were then people could not quite
392      * finish registration and hold resources without being subject to k/g
393      * lines
394      */
395     if (!IsRegistered(cptr))
396     {
397       /* Display message if they have sent a NICK and a USER but no
398        * nospoof PONG.
399        */
400       if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username)
401       {
402         send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
403                    ":Your client may not be compatible with this server.");
404         send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
405                    ":Compatible clients are available at %s",
406                    feature_str(FEAT_URL_CLIENTS));
407       }    
408       exit_client_msg(cptr,cptr,&me, "Ping Timeout");
409       continue;
410     }
411     
412     if (!IsPingSent(cptr))
413     {
414       /* If we havent PINGed the connection and we havent heard from it in a
415        * while, PING it to make sure it is still alive.
416        */
417       SetPingSent(cptr);
418
419       /* If we're late in noticing don't hold it against them :) */
420       cli_lasttime(cptr) = CurrentTime - max_ping;
421       
422       if (IsUser(cptr))
423         sendrawto_one(cptr, MSG_PING " :%s", cli_name(&me));
424       else
425       {
426         char *asll_ts = militime_float(NULL);
427         sendcmdto_one(&me, CMD_PING, cptr, "!%s %s %s", asll_ts,
428                       cli_name(cptr), asll_ts);
429       }
430     }
431     
432     expire = cli_lasttime(cptr) + max_ping * 2;
433     if (expire < next_check)
434       next_check=expire;
435   }
436   
437   assert(next_check >= CurrentTime);
438   
439   Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
440          CurrentTime, next_check-CurrentTime));
441   
442   timer_add(&ping_timer, check_pings, 0, TT_ABSOLUTE, next_check);
443 }
444
445
446 /*----------------------------------------------------------------------------
447  * parse_command_line
448  * Side Effects: changes GLOBALS me, thisServer, dpath, configfile, debuglevel
449  * debugmode
450  *--------------------------------------------------------------------------*/
451 static void parse_command_line(int argc, char** argv) {
452   const char *options = "d:f:h:ntvx:";
453   int opt;
454
455   if (thisServer.euid != thisServer.uid)
456     setuid(thisServer.uid);
457
458   /* Do we really need to santiy check the non-NULLness of optarg?  That's
459    * getopt()'s job...  Removing those... -zs
460    */
461   while ((opt = getopt(argc, argv, options)) != EOF)
462     switch (opt) {
463     case 'n':
464     case 't':  thisServer.bootopt |= BOOT_TTY;         break;
465     case 'd':  dpath      = optarg;                    break;
466     case 'f':  configfile = optarg;                    break;
467     case 'h':  ircd_strncpy(cli_name(&me), optarg, HOSTLEN); break;
468     case 'v':
469       printf("ircd %s\n", version);
470       printf("Event engines: ");
471 #ifdef USE_KQUEUE
472       printf("kqueue() ");
473 #endif
474 #ifdef USE_DEVPOLL
475       printf("/dev/poll ");
476 #endif
477 #ifdef USE_POLL
478       printf("poll()");
479 #else
480       printf("select()");
481 #endif
482       printf("\nCompiled for a maximum of %d connections.\n", MAXCONNECTIONS);
483
484
485       exit(0);
486       break;
487       
488     case 'x':
489       debuglevel = atoi(optarg);
490       if (debuglevel < 0)
491         debuglevel = 0;
492       debugmode = optarg;
493       thisServer.bootopt |= BOOT_DEBUG;
494       break;
495       
496     default:
497       printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
498       printf("\n -n -t\t Don't detach\n -v\t display version\n\n");
499       printf("Server not started.\n");
500       exit(1);
501     }
502 }
503
504
505 /*----------------------------------------------------------------------------
506  * daemon_init
507  *--------------------------------------------------------------------------*/
508 static void daemon_init(int no_fork) {
509   if (!init_connection_limits())
510     exit(9);
511
512   close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
513
514   if (no_fork)
515     return;
516
517   if (fork())
518     exit(0);
519
520 #ifdef TIOCNOTTY
521   {
522     int fd;
523     if ((fd = open("/dev/tty", O_RDWR)) > -1) {
524       ioctl(fd, TIOCNOTTY, 0);
525       close(fd);
526     }
527   }
528 #endif
529
530   setsid();
531 }
532
533 /*----------------------------------------------------------------------------
534  * check_file_access:  random helper function to make sure that a file is
535  *                     accessible in a certain way, and complain if not.
536  *--------------------------------------------------------------------------*/
537 static char check_file_access(const char *path, char which, int mode) {
538   if (!access(path, mode))
539     return 1;
540
541   fprintf(stderr, 
542           "Check on %cPATH (%s) failed: %s\n"
543           "Please create this file and/or rerun `configure' "
544           "using --with-%cpath and recompile to correct this.\n",
545           which, path, strerror(errno), which);
546
547   return 0;
548 }
549
550
551 /*----------------------------------------------------------------------------
552  * set_core_limit
553  *--------------------------------------------------------------------------*/
554 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
555 static void set_core_limit(void) {
556   struct rlimit corelim;
557
558   if (getrlimit(RLIMIT_CORE, &corelim)) {
559     fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
560     corelim.rlim_max = RLIM_INFINITY;   /* Try to recover */
561   }
562
563   corelim.rlim_cur = corelim.rlim_max;
564   if (setrlimit(RLIMIT_CORE, &corelim))
565     fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
566 }
567 #endif
568
569
570
571 /*----------------------------------------------------------------------------
572  * set_userid_if_needed()
573  *--------------------------------------------------------------------------*/
574 static int set_userid_if_needed(void) {
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 MDEBUG
601   mem_dbg_initialise();
602 #endif
603
604 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
605   set_core_limit();
606 #endif
607
608   umask(077);                   /* better safe than sorry --SRB */
609   memset(&me, 0, sizeof(me));
610   memset(&me_con, 0, sizeof(me_con));
611   cli_connect(&me) = &me_con;
612   cli_fd(&me) = -1;
613
614   parse_command_line(argc, argv);
615
616   if (chdir(dpath)) {
617     fprintf(stderr, "Fail: Cannot chdir(%s): %s, check DPATH\n", dpath, strerror(errno));
618     return 2;
619   }
620
621   if (!set_userid_if_needed())
622     return 3;
623
624   /* Check paths for accessibility */
625   if (!check_file_access(SPATH, 'S', X_OK) ||
626       !check_file_access(configfile, 'C', R_OK))
627     return 4;
628
629   debug_init(thisServer.bootopt & BOOT_TTY);
630   daemon_init(thisServer.bootopt & BOOT_TTY);
631   event_init(MAXCONNECTIONS);
632
633   setup_signals();
634   feature_init(); /* initialize features... */
635   log_init(*argv);
636   set_nomem_handler(outofmemory);
637   
638   if (!init_string()) {
639     log_write(LS_SYSTEM, L_CRIT, 0, "Failed to initialize string module");
640     return 6;
641   }
642
643   initload();
644   init_list();
645   init_hash();
646   init_class();
647   initwhowas();
648   initmsgtree();
649   initstats();
650
651   init_resolver();
652
653   motd_init();
654
655   if (!init_conf()) {
656     log_write(LS_SYSTEM, L_CRIT, 0, "Failed to read configuration file %s",
657               configfile);
658     return 7;
659   }
660
661   if (check_pid()) {
662     Debug((DEBUG_FATAL, "Failed to acquire PID file lock after fork"));
663     exit(2);
664   }
665
666   init_server_identity();
667
668   uping_init();
669
670   stats_init();
671
672   IPcheck_init();
673   timer_add(timer_init(&connect_timer), try_connections, 0, TT_RELATIVE, 1);
674   timer_add(timer_init(&ping_timer), check_pings, 0, TT_RELATIVE, 1);
675   timer_add(timer_init(&destruct_event_timer), exec_expired_destruct_events, 0, TT_PERIODIC, 60);
676
677   CurrentTime = time(NULL);
678
679   SetMe(&me);
680   cli_magic(&me) = CLIENT_MAGIC;
681   cli_from(&me) = &me;
682   make_server(&me);
683
684   cli_serv(&me)->timestamp = TStime();  /* Abuse own link timestamp as start TS */
685   cli_serv(&me)->prot      = atoi(MAJOR_PROTOCOL);
686   cli_serv(&me)->up        = &me;
687   cli_serv(&me)->down      = NULL;
688   cli_handler(&me)         = SERVER_HANDLER;
689
690   SetYXXCapacity(&me, MAXCLIENTS);
691
692   cli_lasttime(&me) = cli_since(&me) = cli_firsttime(&me) = CurrentTime;
693
694   hAddClient(&me);
695
696   write_pidfile();
697   init_counters();
698
699   Debug((DEBUG_NOTICE, "Server ready..."));
700   log_write(LS_SYSTEM, L_NOTICE, 0, "Server Ready");
701
702   event_loop();
703
704   return 0;
705 }
706
707