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