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