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