6fa51e5faa1e734ae2eae1889b939dffec3d9eb6
[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 enum {
68   BOOT_DEBUG = 1,
69   BOOT_TTY   = 2
70 };
71
72 struct Client  me;                      /* That's me */
73 struct Client* GlobalClientList = &me;  /* Pointer to beginning of Client list */
74 time_t         TSoffset = 0;      /* Offset of timestamps to system clock */
75 int            GlobalRehashFlag = 0;    /* do a rehash if set */
76 int            GlobalRestartFlag = 0;   /* do a restart if set */
77 time_t         CurrentTime;       /* Updated every time we leave select() */
78
79 static struct Daemon thisServer = { 0 };     /* server process info */
80
81 char *configfile = CPATH;       /* Server configuration file */
82 int debuglevel = -1;            /* Server debug level */
83 char *debugmode = "";           /*  -"-    -"-   -"-  */
84 static char *dpath = DPATH;
85
86 time_t nextconnect = 1;         /* time for next try_connections call */
87 time_t nextping = 1;            /* same as above for check_pings() */
88 time_t nextdnscheck = 0;        /* next time to poll dns to force timeouts */
89 time_t nextexpire = 1;          /* next expire run on the dns cache */
90
91 #ifdef PROFIL
92 extern etext(void);
93 #endif
94
95 static void server_reboot(const char* message)
96 {
97   sendto_ops("Restarting server: %s", message);
98   Debug((DEBUG_NOTICE, "Restarting server..."));
99   flush_connections(0);
100
101   close_log();
102   close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG)));
103
104   execv(SPATH, thisServer.argv);
105
106   /*
107    * Have to reopen since it has been closed above
108    */
109   open_log(*thisServer.argv);
110   ircd_log(L_CRIT, "execv(%s,%s) failed: %m\n", SPATH, *thisServer.argv);
111
112   Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
113          SPATH, (strerror(errno)) ? strerror(errno) : ""));
114   exit(2);
115 }
116
117 void server_die(const char* message)
118 {
119   ircd_log(L_CRIT, "Server terminating: %s", message);
120   sendto_ops("Server terminating: %s", message);
121   flush_connections(0);
122   close_connections(1);
123   thisServer.running = 0;
124 }
125
126 void server_restart(const char* message)
127 {
128   static int restarting = 0;
129
130   ircd_log(L_WARNING, "Restarting Server: %s", message);
131   if (restarting == 0) {
132     restarting = 1;
133     server_reboot(message);
134   }
135 }
136
137 static void outofmemory(void)
138 {
139   Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
140   server_restart("Out of Memory");
141
142
143 static void write_pidfile(void)
144 {
145 #ifdef PPATH
146   int fd;
147   char buff[20];
148   if ((fd = open(PPATH, O_CREAT | O_WRONLY, 0600)) == -1) {
149     Debug((DEBUG_NOTICE, "Error opening pid file \"%s\": %s",
150            PPATH, strerror(errno)));
151     return;
152   }
153   memset(buff, 0, sizeof(buff));
154   sprintf(buff, "%5d\n", getpid());
155   if (write(fd, buff, strlen(buff)) == -1)
156     Debug((DEBUG_NOTICE, "Error writing to pid file %s", PPATH));
157   close(fd);
158 #endif
159 }
160
161 /*
162  * try_connections
163  *
164  * Scan through configuration and try new connections.
165  *
166  * Returns the calendar time when the next call to this
167  * function should be made latest. (No harm done if this
168  * is called earlier or later...)
169  */
170 static time_t try_connections(void)
171 {
172   struct ConfItem*  aconf;
173   struct Client*    cptr;
174   struct ConfItem** pconf;
175   int               connecting;
176   int               confrq;
177   time_t            next = 0;
178   struct ConfClass* cltmp;
179   struct ConfItem*  cconf;
180   struct ConfItem*  con_conf = NULL;
181   struct Jupe*      ajupe;
182   unsigned int      con_class = 0;
183
184   connecting = FALSE;
185   Debug((DEBUG_NOTICE, "Connection check at   : %s", myctime(CurrentTime)));
186   for (aconf = GlobalConfList; aconf; aconf = aconf->next)
187   {
188     /* Also when already connecting! (update holdtimes) --SRB */
189     if (!(aconf->status & CONF_SERVER) || aconf->port == 0)
190       continue;
191
192     /* Also skip juped servers */
193     if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
194       continue;
195
196     cltmp = aconf->confClass;
197     /*
198      * Skip this entry if the use of it is still on hold until
199      * future. Otherwise handle this entry (and set it on hold
200      * until next time). Will reset only hold times, if already
201      * made one successfull connection... [this algorithm is
202      * a bit fuzzy... -- msa >;) ]
203      */
204
205     if ((aconf->hold > CurrentTime))
206     {
207       if ((next > aconf->hold) || (next == 0))
208         next = aconf->hold;
209       continue;
210     }
211
212     confrq = get_con_freq(cltmp);
213     aconf->hold = CurrentTime + confrq;
214     /*
215      * Found a CONNECT config with port specified, scan clients
216      * and see if this server is already connected?
217      */
218     cptr = FindServer(aconf->name);
219
220     if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
221         (!connecting || (ConClass(cltmp) > con_class)))
222     {
223       /* Check connect rules to see if we're allowed to try */
224       for (cconf = GlobalConfList; cconf; cconf = cconf->next)
225         if ((cconf->status & CONF_CRULE) &&
226             (match(cconf->host, aconf->name) == 0))
227           if (crule_eval(cconf->passwd))
228             break;
229       if (!cconf)
230       {
231         con_class = ConClass(cltmp);
232         con_conf = aconf;
233         /* We connect only one at time... */
234         connecting = TRUE;
235       }
236     }
237     if ((next > aconf->hold) || (next == 0))
238       next = aconf->hold;
239   }
240   if (connecting)
241   {
242     if (con_conf->next)         /* are we already last? */
243     {
244       /* Put the current one at the end and make sure we try all connections */
245       for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
246         if (aconf == con_conf)
247           *pconf = aconf->next;
248       (*pconf = con_conf)->next = 0;
249     }
250     if (connect_server(con_conf, 0, 0))
251       sendto_ops("Connection to %s activated.", con_conf->name);
252   }
253   Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
254   return (next);
255 }
256
257 static time_t check_pings(void)
258 {
259  int expire=0; 
260              /* Temp to figure out what time this connection will next need
261               * to be checked.
262               */
263  int next_check = CurrentTime + PINGFREQUENCY;
264             /*
265              * The current lowest expire time - ie: the time that check_pings
266              * needs to be called next.
267              */
268  int max_ping = 0;
269             /* 
270              * The time you've got before a ping is sent/your connection is
271              * terminated.
272              */
273              
274  int i=0; /* loop counter */
275   
276  /* Scan through the client table */
277  for (i=0; i <= HighestFd; i++) {
278    struct Client *cptr;
279    
280    cptr = LocalClientArray[i];
281    
282    /* Skip empty entries */
283    if (!cptr)
284      continue;
285      
286    assert(&me != cptr); /* I should never be in the local client array,
287                          * so if I am, dying is a good thing(tm).
288                          */
289    
290    /* Remove dead clients.
291     * We will have sent opers a message when we set the dead flag,
292     * so don't bother to send one now.
293     */
294    if (IsDead(cptr)) {
295      exit_client(cptr, cptr, &me, cptr->info);
296      continue;
297    }
298
299    /* Should we concider adding a class 0 for 'unregistered clients',
300     * where we can specify their 'ping timeout' etc?
301     */
302    max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
303    
304    /* Ok, the thing that will happen most frequently, is that someone will
305     * have sent something recently.  Cover this first for speed.
306     */
307    if (CurrentTime-cptr->lasttime <= max_ping) {
308         expire=cptr->lasttime + max_ping;
309         if (next_check<expire) 
310           next_check=expire;
311         continue;
312    }
313
314    /* Quit the client after max_ping*2 - they should have answered by now */
315    if (CurrentTime-cptr->lasttime <= (max_ping*2) ) {
316       
317       /* If it was a server, then tell ops about it. */
318       if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
319         sendto_ops("No response from %s, closing link", cptr->name);
320
321       exit_client_msg(cptr, cptr, &me, "Ping timeout");
322       continue;
323     } /* of testing to see if ping has been sent */
324     
325     /* Unregistered clients pingout after max_ping seconds, they don't
326      * get given a second chance. 
327      */
328     if (!IsRegistered(cptr)) {
329       /* Display message if they have sent a NICK and a USER but no
330        * nospoof PONG.
331        */
332       if (*cptr->name && *cptr->user->username) {
333         sendto_one(cptr,
334             ":%s %d %s :Your client may not be compatible with this server.",
335             me.name, ERR_BADPING, cptr->name);
336         sendto_one(cptr,
337             ":%s %d %s :Compatible clients are available at "
338             "ftp://ftp.undernet.org/pub/irc/clients",
339             me.name, ERR_BADPING, cptr->name);
340       }    
341       exit_client_msg(cptr,cptr,&me, "Ping Timeout");
342       continue;
343     } /* of not registered */
344     
345     if (0 == (cptr->flags & FLAGS_PINGSENT)) {
346       /*
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       cptr->flags |= FLAGS_PINGSENT;
351
352       /*
353        * If we're late in noticing don't hold it against them :)
354        */
355       cptr->lasttime = CurrentTime - max_ping;
356       
357       if (IsUser(cptr))
358         sendto_one(cptr, "PING :%s", me.name);
359       else
360         sendto_one(cptr, "%s " TOK_PING " :%s", NumServ(&me), me.name);
361     } /* of if not ping sent... */
362     
363     expire=cptr->lasttime+max_ping*2;
364     
365     if (expire<next_check)
366         next_check=expire;
367
368   }  /* end of loop over clients */
369   
370   assert(next_check>=CurrentTime);
371   
372   return next_check;
373 }
374
375 #if 0
376 static time_t check_pings(void)
377 {
378   struct Client *cptr;
379   int max_ping = 0;
380   int i;
381   time_t oldest = CurrentTime + PINGFREQUENCY;
382   time_t timeout;
383
384   /* For each client... */
385   for (i = 0; i <= HighestFd; i++) {
386     if (!(cptr = LocalClientArray[i])) /* oops! not a client... */
387       continue;
388     /*
389      * me is never in the local client array
390      */
391     assert(cptr != &me);
392     /*
393      * Note: No need to notify opers here.
394      * It's already done when "FLAGS_DEADSOCKET" is set.
395      */
396     if (IsDead(cptr)) {
397       exit_client(cptr, cptr, &me, cptr->info);
398       continue;
399     }
400
401     max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
402     
403     Debug((DEBUG_DEBUG, "check_pings(%s)=status:%d ping: %d current: %d",
404           cptr->name, cptr->status, max_ping, 
405           (int)(CurrentTime - cptr->lasttime)));
406           
407     /*
408      * Ok, so goto's are ugly and can be avoided here but this code
409      * is already indented enough so I think its justified. -avalon
410      */
411     /*
412      * If this is a registered client that we've heard of in a reasonable
413      * time, then skip them.
414      */
415     if (IsRegistered(cptr) && (max_ping >= CurrentTime - cptr->lasttime))
416       goto ping_timeout;
417     /*
418      * If the server hasnt talked to us in 2 * ping seconds
419      * and it has a ping time, then close its connection.
420      * If the client is a user and a KILL line was found
421      * to be active, close this connection too.
422      */
423     if (((CurrentTime - cptr->lasttime) >= (2 * ping) && (cptr->flags & FLAGS_PINGSENT)) ||
424         (!IsRegistered(cptr) && !IsHandshake(cptr) && (CurrentTime - cptr->firsttime) >= ping))
425     {
426       if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
427       {
428         sendto_ops("No response from %s, closing link", cptr->name);
429         exit_client(cptr, cptr, &me, "Ping timeout");
430         continue;
431       }
432       else {
433         if (!IsRegistered(cptr) && *cptr->name && *cptr->user->username) {
434           sendto_one(cptr,
435               ":%s %d %s :Your client may not be compatible with this server.",
436               me.name, ERR_BADPING, cptr->name);
437           sendto_one(cptr,
438               ":%s %d %s :Compatible clients are available at "
439               "ftp://ftp.undernet.org/pub/irc/clients",
440               me.name, ERR_BADPING, cptr->name);
441         }
442         exit_client_msg(cptr, cptr, &me, "Ping timeout");
443       }
444       continue;
445     }
446     else if (IsRegistered(cptr) && 0 == (cptr->flags & FLAGS_PINGSENT)) {
447       /*
448        * If we havent PINGed the connection and we havent
449        * heard from it in a while, PING it to make sure
450        * it is still alive.
451        */
452       cptr->flags |= FLAGS_PINGSENT;
453       /*
454        * not nice but does the job
455        */
456       cptr->lasttime = CurrentTime - ping;
457       if (IsUser(cptr))
458         sendto_one(cptr, "PING :%s", me.name);
459       else
460         sendto_one(cptr, "%s " TOK_PING " :%s", NumServ(&me), me.name);
461     }
462 ping_timeout:
463     timeout = cptr->lasttime + max_ping;
464     while (timeout <= CurrentTime)
465       timeout += max_ping;
466     if (timeout < oldest)
467       oldest = timeout;
468   }
469   if (oldest < CurrentTime)
470     oldest = CurrentTime + PINGFREQUENCY;
471   Debug((DEBUG_NOTICE,
472         "Next check_ping() call at: %s, %d " TIME_T_FMT " " TIME_T_FMT,
473         myctime(oldest), ping, oldest, CurrentTime));
474
475   return (oldest);
476 }
477 #endif
478
479 /*
480  * bad_command
481  *
482  * This is called when the commandline is not acceptable.
483  * Give error message and exit without starting anything.
484  */
485 static void print_usage(void)
486 {
487   printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
488   printf("Server not started\n");
489 }
490
491
492 /*
493  * for getopt
494  * ZZZ this is going to need confirmation on other OS's
495  *
496  * #include <getopt.h>
497  * Solaris has getopt.h, you should too... hopefully
498  * BSD declares them in stdlib.h
499  * extern char *optarg;
500  *
501  * for FreeBSD the following are defined:
502  *
503  * extern char *optarg;
504  * extern int optind;
505  * extern in optopt;
506  * extern int opterr;
507  * extern in optreset;
508  *
509  *
510  * All command line parameters have the syntax "-f string" or "-fstring"
511  * OPTIONS:
512  * -d filename - specify d:line file
513  * -f filename - specify config file
514  * -h hostname - specify server name
515  * -k filename - specify k:line file (hybrid)
516  * -l filename - specify log file
517  * -n          - do not fork, run in foreground
518  * -t          - do not fork send debugging info to tty
519  * -v          - print version and exit
520  * -x          - set debug level, if compiled for debug logging
521  */
522 static void parse_command_line(int argc, char** argv)
523 {
524   const char* options = "d:f:h:ntvx:";
525   int opt;
526
527   if (thisServer.euid != thisServer.uid)
528     setuid(thisServer.uid);
529
530   while ((opt = getopt(argc, argv, options)) != EOF) {
531     switch (opt) {
532     case 'd':
533       if (optarg)
534         dpath = optarg;
535       break;
536     case 'f':
537       if (optarg)
538         configfile = optarg;
539       break;
540     case 'h':
541       if (optarg)
542         ircd_strncpy(me.name, optarg, HOSTLEN);
543       break;
544     case 'n':
545     case 't':
546       thisServer.bootopt |= BOOT_TTY;
547       break;
548     case 'v':
549       printf("ircd %s\n", version);
550       exit(0);
551     case 'x':
552       if (optarg) {
553         debuglevel = atoi(optarg);
554         if (debuglevel < 0)
555           debuglevel = 0;
556         debugmode = optarg;
557         thisServer.bootopt |= BOOT_DEBUG;
558       }
559       break;
560     default:
561       print_usage();
562       exit(1);
563     }
564   }
565 }
566
567 /*
568  * daemon_init
569  */
570 static void daemon_init(int no_fork)
571 {
572   if (!init_connection_limits())
573     exit(2);
574
575   close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
576   if (no_fork)
577     return;
578
579   if (fork())
580     exit(0);
581 #ifdef TIOCNOTTY
582   {
583     int fd;
584     if ((fd = open("/dev/tty", O_RDWR)) > -1) {
585       ioctl(fd, TIOCNOTTY, 0);
586       close(fd);
587     }
588   }
589 #endif
590   setsid();
591 }
592
593
594 static void event_loop(void)
595 {
596   time_t delay = 0;
597
598   while (thisServer.running) {
599     /*
600      * We only want to connect if a connection is due,
601      * not every time through.   Note, if there are no
602      * active C lines, this call to Tryconnections is
603      * made once only; it will return 0. - avalon
604      */
605     if (nextconnect && CurrentTime >= nextconnect)
606       nextconnect = try_connections();
607     /*
608      * DNS checks. One to timeout queries, one for cache expiries.
609      */
610     nextdnscheck = timeout_resolver(CurrentTime);
611     /*
612      * Take the smaller of the two 'timed' event times as
613      * the time of next event (stops us being late :) - avalon
614      * WARNING - nextconnect can return 0!
615      */
616     if (nextconnect)
617       delay = IRCD_MIN(nextping, nextconnect);
618     else
619       delay = nextping;
620     delay = IRCD_MIN(nextdnscheck, delay);
621     delay -= CurrentTime;
622     /*
623      * Adjust delay to something reasonable [ad hoc values]
624      * (one might think something more clever here... --msa)
625      * We don't really need to check that often and as long
626      * as we don't delay too long, everything should be ok.
627      * waiting too long can cause things to timeout...
628      * i.e. PINGS -> a disconnection :(
629      * - avalon
630      */
631     if (delay < 1)
632       delay = 1;
633     else
634       delay = IRCD_MIN(delay, TIMESEC);
635     read_message(delay);
636
637     Debug((DEBUG_DEBUG, "Got message(s)"));
638
639     /*
640      * ...perhaps should not do these loops every time,
641      * but only if there is some chance of something
642      * happening (but, note that conf->hold times may
643      * be changed elsewhere--so precomputed next event
644      * time might be too far away... (similarly with
645      * ping times) --msa
646      */
647     if (CurrentTime >= nextping)
648       nextping = check_pings();
649     
650     /*
651      * timeout pending queries that haven't been responded to
652      */
653     timeout_auth_queries(CurrentTime);
654
655     if (GlobalRehashFlag) {
656       rehash(&me, 1);
657       GlobalRehashFlag = 0;
658     }
659     if (GlobalRestartFlag)
660       server_restart("caught signal: SIGINT");
661   }
662 }
663
664 int main(int argc, char *argv[])
665 {
666 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
667   struct rlimit corelim;
668 #endif
669
670   CurrentTime = time(NULL);
671   /*
672    * sanity check
673    */
674   if (MAXCONNECTIONS < 64 || MAXCONNECTIONS > 256000) {
675     fprintf(stderr, "%s: MAXCONNECTIONS insane: %d\n", *argv, MAXCONNECTIONS);
676     return 2;
677   }
678   thisServer.argc = argc;
679   thisServer.argv = argv;
680   thisServer.uid  = getuid();
681   thisServer.euid = geteuid();
682 #ifdef PROFIL
683   monstartup(0, etext);
684   moncontrol(1);
685   signal(SIGUSR1, s_monitor);
686 #endif
687
688 #ifdef CHROOTDIR
689   if (chdir(DPATH)) {
690     fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", DPATH, strerror(errno));
691     exit(2);
692   }
693   if (chroot(DPATH)) {
694     fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", DPATH, strerror(errno));
695     exit(5);
696   }
697   dpath = "/";
698 #endif /*CHROOTDIR */
699
700   umask(077);                   /* better safe than sorry --SRB */
701   memset(&me, 0, sizeof(me));
702   me.fd = -1;
703
704   setup_signals();
705   initload();
706
707 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
708   if (getrlimit(RLIMIT_CORE, &corelim))
709   {
710     fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
711     corelim.rlim_max = RLIM_INFINITY;   /* Try to recover */
712   }
713   corelim.rlim_cur = corelim.rlim_max;
714   if (setrlimit(RLIMIT_CORE, &corelim))
715     fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
716 #endif
717   parse_command_line(argc, argv);
718
719   if (chdir(dpath)) {
720     fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, strerror(errno));
721     exit(2);
722   }
723
724 #ifndef IRC_UID
725   if ((thisServer.uid != thisServer.euid) && !thisServer.euid) {
726     fprintf(stderr,
727         "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
728     exit(2);
729   }
730 #endif
731
732 #if !defined(CHROOTDIR) || (defined(IRC_UID) && defined(IRC_GID))
733   if (thisServer.euid != thisServer.uid) {
734     setuid(thisServer.uid);
735     setuid(thisServer.euid);
736   }
737
738   if (0 == getuid()) {
739 #if defined(IRC_UID) && defined(IRC_GID)
740
741     /* run as a specified user */
742     fprintf(stderr, "WARNING: running ircd with uid = %d\n", IRC_UID);
743     fprintf(stderr, "         changing to gid %d.\n", IRC_GID);
744     setuid(IRC_UID);
745     setgid(IRC_GID);
746 #else
747     /* check for setuid root as usual */
748     fprintf(stderr,
749         "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
750     exit(2);
751 #endif
752   }
753 #endif /*CHROOTDIR/UID/GID */
754
755   /* Sanity checks */
756   {
757     char c;
758     char *path;
759
760     c = 'S';
761     path = SPATH;
762     if (access(path, X_OK) == 0) {
763       c = 'C';
764       path = CPATH;
765       if (access(path, R_OK) == 0) {
766         c = 'M';
767         path = MPATH;
768         if (access(path, R_OK) == 0) {
769           c = 'R';
770           path = RPATH;
771           if (access(path, R_OK) == 0) {
772 #ifndef DEBUG
773             c = 0;
774 #else
775             c = 'L';
776             path = LPATH;
777             if (access(path, W_OK) == 0)
778               c = 0;
779 #endif
780           }
781         }
782       }
783     }
784     if (c) {
785       fprintf(stderr, "Check on %cPATH (%s) failed: %s\n", c, path, strerror(errno));
786       fprintf(stderr,
787           "Please create file and/or rerun `make config' and recompile to correct this.\n");
788 #ifdef CHROOTDIR
789       fprintf(stderr, "Keep in mind that all paths are relative to CHROOTDIR.\n");
790 #endif
791       exit(2);
792     }
793   }
794
795   init_list();
796   hash_init();
797   initclass();
798   initwhowas();
799   initmsgtree();
800   initstats();
801
802   debug_init(thisServer.bootopt & BOOT_TTY);
803   daemon_init(thisServer.bootopt & BOOT_TTY);
804
805   set_nomem_handler(outofmemory);
806   init_resolver();
807
808   open_log(*argv);
809
810   if (!conf_init()) {
811     Debug((DEBUG_FATAL, "Failed in reading configuration file %s", configfile));
812     printf("Couldn't open configuration file %s\n", configfile);
813     exit(2);
814   }
815   if (!init_server_identity()) {
816     Debug((DEBUG_FATAL, "Failed to initialize server identity"));
817     exit(2);
818   }
819   uping_init();
820   read_tlines();
821   rmotd = read_motd(RPATH);
822   motd = read_motd(MPATH);
823   CurrentTime = time(NULL);
824   me.from = &me;
825   SetMe(&me);
826   make_server(&me);
827   /*
828    * Abuse own link timestamp as start timestamp:
829    */
830   me.serv->timestamp = TStime();
831   me.serv->prot = atoi(MAJOR_PROTOCOL);
832   me.serv->up = &me;
833   me.serv->down = NULL;
834   me.handler = SERVER_HANDLER;
835
836   SetYXXCapacity(&me, MAXCLIENTS);
837
838   me.lasttime = me.since = me.firsttime = CurrentTime;
839   hAddClient(&me);
840
841   check_class();
842   write_pidfile();
843
844   init_counters();
845
846   Debug((DEBUG_NOTICE, "Server ready..."));
847   ircd_log(L_NOTICE, "Server Ready");
848   thisServer.running = 1;
849
850   event_loop();
851   return 0;
852 }
853
854