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