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