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