Author: Isomer <isomer@coders.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 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    Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
305           cptr->name, (cptr->flags & FLAGS_PINGSENT) ? "[Ping Sent]" : "[]", 
306           max_ping, (int)(CurrentTime - cptr->lasttime)));
307           
308    /* Ok, the thing that will happen most frequently, is that someone will
309     * have sent something recently.  Cover this first for speed.
310     */
311    if (CurrentTime-cptr->lasttime < max_ping) {
312         expire=cptr->lasttime + max_ping;
313         if (expire<next_check) 
314           next_check=expire;
315         continue;
316    }
317
318    /* Quit the client after max_ping*2 - they should have answered by now */
319    if (CurrentTime-cptr->lasttime >= (max_ping*2) ) {
320       
321       /* If it was a server, then tell ops about it. */
322       if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
323         sendto_ops("No response from %s, closing link", cptr->name);
324
325       exit_client_msg(cptr, cptr, &me, "Ping timeout");
326       continue;
327     } /* of testing to see if ping has been sent */
328     
329     /* Unregistered clients pingout after max_ping seconds, they don't
330      * get given a second chance - if they were then people could not quite
331      * finish registration and hold resources without being subject to k/g
332      * lines
333      */
334     if (!IsRegistered(cptr)) {
335       /* Display message if they have sent a NICK and a USER but no
336        * nospoof PONG.
337        */
338       if (*cptr->name && cptr->user && *cptr->user->username) {
339         sendto_one(cptr,
340             ":%s %d %s :Your client may not be compatible with this server.",
341             me.name, ERR_BADPING, cptr->name);
342         sendto_one(cptr,
343             ":%s %d %s :Compatible clients are available at "
344             "ftp://ftp.undernet.org/pub/irc/clients",
345             me.name, ERR_BADPING, cptr->name);
346       }    
347       exit_client_msg(cptr,cptr,&me, "Ping Timeout");
348       continue;
349     } /* of not registered */
350     
351     if (0 == (cptr->flags & FLAGS_PINGSENT)) {
352       /*
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       /*
359        * If we're late in noticing don't hold it against them :)
360        */
361       cptr->lasttime = CurrentTime - max_ping;
362       
363       if (IsUser(cptr))
364         sendto_one(cptr, MSG_PING " :%s", me.name);
365       else
366         sendto_one(cptr, "%s " TOK_PING " :%s", NumServ(&me), me.name);
367     } /* of if not ping sent... */
368     
369     expire=cptr->lasttime+max_ping*2;
370     
371     if (expire<next_check)
372         next_check=expire;
373
374   }  /* end of loop over clients */
375   
376   assert(next_check>=CurrentTime);
377   
378   Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",CurrentTime,next_check-CurrentTime));
379   
380   return next_check;
381 }
382
383 #if 0
384 static time_t check_pings(void)
385 {
386   struct Client *cptr;
387   int max_ping = 0;
388   int i;
389   time_t oldest = CurrentTime + PINGFREQUENCY;
390   time_t timeout;
391
392   /* For each client... */
393   for (i = 0; i <= HighestFd; i++) {
394     if (!(cptr = LocalClientArray[i])) /* oops! not a client... */
395       continue;
396     /*
397      * me is never in the local client array
398      */
399     assert(cptr != &me);
400     /*
401      * Note: No need to notify opers here.
402      * It's already done when "FLAGS_DEADSOCKET" is set.
403      */
404     if (IsDead(cptr)) {
405       exit_client(cptr, cptr, &me, cptr->info);
406       continue;
407     }
408
409     max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
410     
411     Debug((DEBUG_DEBUG, "check_pings(%s)=status:%d ping: %d current: %d",
412           cptr->name, cptr->status, max_ping, 
413           (int)(CurrentTime - cptr->lasttime)));
414           
415     /*
416      * Ok, so goto's are ugly and can be avoided here but this code
417      * is already indented enough so I think its justified. -avalon
418      */
419     /*
420      * If this is a registered client that we've heard of in a reasonable
421      * time, then skip them.
422      */
423     if (IsRegistered(cptr) && (max_ping >= CurrentTime - cptr->lasttime))
424       goto ping_timeout;
425     /*
426      * If the server hasnt talked to us in 2 * ping seconds
427      * and it has a ping time, then close its connection.
428      * If the client is a user and a KILL line was found
429      * to be active, close this connection too.
430      */
431     if (((CurrentTime - cptr->lasttime) >= (2 * ping) && (cptr->flags & FLAGS_PINGSENT)) ||
432         (!IsRegistered(cptr) && !IsHandshake(cptr) && (CurrentTime - cptr->firsttime) >= ping))
433     {
434       if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
435       {
436         sendto_ops("No response from %s, closing link", cptr->name);
437         exit_client(cptr, cptr, &me, "Ping timeout");
438         continue;
439       }
440       else {
441         if (!IsRegistered(cptr) && *cptr->name && *cptr->user->username) {
442           sendto_one(cptr,
443               ":%s %d %s :Your client may not be compatible with this server.",
444               me.name, ERR_BADPING, cptr->name);
445           sendto_one(cptr,
446               ":%s %d %s :Compatible clients are available at "
447               "ftp://ftp.undernet.org/pub/irc/clients",
448               me.name, ERR_BADPING, cptr->name);
449         }
450         exit_client_msg(cptr, cptr, &me, "Ping timeout");
451       }
452       continue;
453     }
454     else if (IsRegistered(cptr) && 0 == (cptr->flags & FLAGS_PINGSENT)) {
455       /*
456        * If we havent PINGed the connection and we havent
457        * heard from it in a while, PING it to make sure
458        * it is still alive.
459        */
460       cptr->flags |= FLAGS_PINGSENT;
461       /*
462        * not nice but does the job
463        */
464       cptr->lasttime = CurrentTime - ping;
465       if (IsUser(cptr))
466         sendto_one(cptr, "PING :%s", me.name);
467       else
468         sendto_one(cptr, "%s " TOK_PING " :%s", NumServ(&me), me.name);
469     }
470 ping_timeout:
471     timeout = cptr->lasttime + max_ping;
472     while (timeout <= CurrentTime)
473       timeout += max_ping;
474     if (timeout < oldest)
475       oldest = timeout;
476   }
477   if (oldest < CurrentTime)
478     oldest = CurrentTime + PINGFREQUENCY;
479   Debug((DEBUG_NOTICE,
480         "Next check_ping() call at: %s, %d " TIME_T_FMT " " TIME_T_FMT,
481         myctime(oldest), ping, oldest, CurrentTime));
482
483   return (oldest);
484 }
485 #endif
486
487 /*
488  * bad_command
489  *
490  * This is called when the commandline is not acceptable.
491  * Give error message and exit without starting anything.
492  */
493 static void print_usage(void)
494 {
495   printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
496   printf("\n -n -t\t Don't detach\n -v\t display version\n\n");
497   printf("Server not started\n");
498 }
499
500
501 /*
502  * for getopt
503  * ZZZ this is going to need confirmation on other OS's
504  *
505  * #include <getopt.h>
506  * Solaris has getopt.h, you should too... hopefully
507  * BSD declares them in stdlib.h
508  * extern char *optarg;
509  *
510  * for FreeBSD the following are defined:
511  *
512  * extern char *optarg;
513  * extern int optind;
514  * extern in optopt;
515  * extern int opterr;
516  * extern in optreset;
517  *
518  *
519  * All command line parameters have the syntax "-f string" or "-fstring"
520  * OPTIONS:
521  * -d filename - specify d:line file
522  * -f filename - specify config file
523  * -h hostname - specify server name
524  * -k filename - specify k:line file (hybrid)
525  * -l filename - specify log file
526  * -n          - do not fork, run in foreground
527  * -t          - do not fork send debugging info to tty
528  * -v          - print version and exit
529  * -x          - set debug level, if compiled for debug logging
530  */
531 static void parse_command_line(int argc, char** argv)
532 {
533   const char* options = "d:f:h:ntvx:";
534   int opt;
535
536   if (thisServer.euid != thisServer.uid)
537     setuid(thisServer.uid);
538
539   while ((opt = getopt(argc, argv, options)) != EOF) {
540     switch (opt) {
541     case 'd':
542       if (optarg)
543         dpath = optarg;
544       break;
545     case 'f':
546       if (optarg)
547         configfile = optarg;
548       break;
549     case 'h':
550       if (optarg)
551         ircd_strncpy(me.name, optarg, HOSTLEN);
552       break;
553     case 'n':
554     case 't':
555       thisServer.bootopt |= BOOT_TTY;
556       break;
557     case 'v':
558       printf("ircd %s\n", version);
559       exit(0);
560     case 'x':
561       if (optarg) {
562         debuglevel = atoi(optarg);
563         if (debuglevel < 0)
564           debuglevel = 0;
565         debugmode = optarg;
566         thisServer.bootopt |= BOOT_DEBUG;
567       }
568       break;
569     default:
570       print_usage();
571       exit(1);
572     }
573   }
574 }
575
576 /*
577  * daemon_init
578  */
579 static void daemon_init(int no_fork)
580 {
581   if (!init_connection_limits())
582     exit(2);
583
584   close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
585   if (no_fork)
586     return;
587
588   if (fork())
589     exit(0);
590 #ifdef TIOCNOTTY
591   {
592     int fd;
593     if ((fd = open("/dev/tty", O_RDWR)) > -1) {
594       ioctl(fd, TIOCNOTTY, 0);
595       close(fd);
596     }
597   }
598 #endif
599   setsid();
600 }
601
602
603 static void event_loop(void)
604 {
605   time_t delay = 0;
606
607   while (thisServer.running) {
608     /*
609      * We only want to connect if a connection is due,
610      * not every time through.   Note, if there are no
611      * active C lines, this call to Tryconnections is
612      * made once only; it will return 0. - avalon
613      */
614     if (nextconnect && CurrentTime >= nextconnect)
615       nextconnect = try_connections();
616     /*
617      * DNS checks. One to timeout queries, one for cache expiries.
618      */
619     nextdnscheck = timeout_resolver(CurrentTime);
620     /*
621      * Take the smaller of the two 'timed' event times as
622      * the time of next event (stops us being late :) - avalon
623      * WARNING - nextconnect can return 0!
624      */
625     if (nextconnect)
626       delay = IRCD_MIN(nextping, nextconnect);
627     else
628       delay = nextping;
629     delay = IRCD_MIN(nextdnscheck, delay);
630     delay -= CurrentTime;
631     /*
632      * Adjust delay to something reasonable [ad hoc values]
633      * (one might think something more clever here... --msa)
634      * We don't really need to check that often and as long
635      * as we don't delay too long, everything should be ok.
636      * waiting too long can cause things to timeout...
637      * i.e. PINGS -> a disconnection :(
638      * - avalon
639      */
640     if (delay < 1)
641       delay = 1;
642     else
643       delay = IRCD_MIN(delay, TIMESEC);
644     read_message(delay);
645
646     Debug((DEBUG_DEBUG, "Got message(s)"));
647
648     /*
649      * ...perhaps should not do these loops every time,
650      * but only if there is some chance of something
651      * happening (but, note that conf->hold times may
652      * be changed elsewhere--so precomputed next event
653      * time might be too far away... (similarly with
654      * ping times) --msa
655      */
656     if (CurrentTime >= nextping)
657       nextping = check_pings();
658     
659     /*
660      * timeout pending queries that haven't been responded to
661      */
662     timeout_auth_queries(CurrentTime);
663
664     if (GlobalRehashFlag) {
665       rehash(&me, 1);
666       GlobalRehashFlag = 0;
667     }
668     if (GlobalRestartFlag)
669       server_restart("caught signal: SIGINT");
670   }
671 }
672
673 int main(int argc, char *argv[])
674 {
675 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
676   struct rlimit corelim;
677 #endif
678
679   CurrentTime = time(NULL);
680   /*
681    * sanity check
682    */
683   if (MAXCONNECTIONS < 64 || MAXCONNECTIONS > 256000) {
684     fprintf(stderr, "%s: MAXCONNECTIONS insane: %d\n", *argv, MAXCONNECTIONS);
685     return 2;
686   }
687   thisServer.argc = argc;
688   thisServer.argv = argv;
689   thisServer.uid  = getuid();
690   thisServer.euid = geteuid();
691 #ifdef PROFIL
692   monstartup(0, etext);
693   moncontrol(1);
694   signal(SIGUSR1, s_monitor);
695 #endif
696
697 #ifdef CHROOTDIR
698   if (chdir(DPATH)) {
699     fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", DPATH, strerror(errno));
700     exit(2);
701   }
702   if (chroot(DPATH)) {
703     fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", DPATH, strerror(errno));
704     exit(5);
705   }
706   dpath = "/";
707 #endif /*CHROOTDIR */
708
709   umask(077);                   /* better safe than sorry --SRB */
710   memset(&me, 0, sizeof(me));
711   me.fd = -1;
712
713   setup_signals();
714   initload();
715
716 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
717   if (getrlimit(RLIMIT_CORE, &corelim))
718   {
719     fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
720     corelim.rlim_max = RLIM_INFINITY;   /* Try to recover */
721   }
722   corelim.rlim_cur = corelim.rlim_max;
723   if (setrlimit(RLIMIT_CORE, &corelim))
724     fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
725 #endif
726   parse_command_line(argc, argv);
727
728   if (chdir(dpath)) {
729     fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, strerror(errno));
730     exit(2);
731   }
732
733 #ifndef IRC_UID
734   if ((thisServer.uid != thisServer.euid) && !thisServer.euid) {
735     fprintf(stderr,
736         "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
737     exit(2);
738   }
739 #endif
740
741 #if !defined(CHROOTDIR) || (defined(IRC_UID) && defined(IRC_GID))
742   if (thisServer.euid != thisServer.uid) {
743     setuid(thisServer.uid);
744     setuid(thisServer.euid);
745   }
746
747   if (0 == getuid()) {
748 #if defined(IRC_UID) && defined(IRC_GID)
749
750     /* run as a specified user */
751     fprintf(stderr, "WARNING: running ircd with uid = %d\n", IRC_UID);
752     fprintf(stderr, "         changing to gid %d.\n", IRC_GID);
753     setuid(IRC_UID);
754     setgid(IRC_GID);
755 #else
756     /* check for setuid root as usual */
757     fprintf(stderr,
758         "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
759     exit(2);
760 #endif
761   }
762 #endif /*CHROOTDIR/UID/GID */
763
764   /* Sanity checks */
765   {
766     char c;
767     char *path;
768
769     c = 'S';
770     path = SPATH;
771     if (access(path, X_OK) == 0) {
772       c = 'C';
773       path = CPATH;
774       if (access(path, R_OK) == 0) {
775         c = 'M';
776         path = MPATH;
777         if (access(path, R_OK) == 0) {
778           c = 'R';
779           path = RPATH;
780           if (access(path, R_OK) == 0) {
781 #ifndef DEBUG
782             c = 0;
783 #else
784             c = 'L';
785             path = LPATH;
786             if (access(path, W_OK) == 0)
787               c = 0;
788 #endif
789           }
790         }
791       }
792     }
793     if (c) {
794       fprintf(stderr, "Check on %cPATH (%s) failed: %s\n", c, path, strerror(errno));
795       fprintf(stderr,
796           "Please create file and/or rerun `make config' and recompile to correct this.\n");
797 #ifdef CHROOTDIR
798       fprintf(stderr, "Keep in mind that all paths are relative to CHROOTDIR.\n");
799 #endif
800       exit(2);
801     }
802   }
803
804   init_list();
805   hash_init();
806   initclass();
807   initwhowas();
808   initmsgtree();
809   initstats();
810
811   debug_init(thisServer.bootopt & BOOT_TTY);
812   daemon_init(thisServer.bootopt & BOOT_TTY);
813
814   set_nomem_handler(outofmemory);
815   init_resolver();
816
817   open_log(*argv);
818
819   if (!conf_init()) {
820     Debug((DEBUG_FATAL, "Failed in reading configuration file %s", configfile));
821     printf("Couldn't open configuration file %s\n", configfile);
822     exit(2);
823   }
824   if (!init_server_identity()) {
825     Debug((DEBUG_FATAL, "Failed to initialize server identity"));
826     exit(2);
827   }
828   uping_init();
829   read_tlines();
830   rmotd = read_motd(RPATH);
831   motd = read_motd(MPATH);
832   CurrentTime = time(NULL);
833   me.from = &me;
834   SetMe(&me);
835   make_server(&me);
836   /*
837    * Abuse own link timestamp as start timestamp:
838    */
839   me.serv->timestamp = TStime();
840   me.serv->prot = atoi(MAJOR_PROTOCOL);
841   me.serv->up = &me;
842   me.serv->down = NULL;
843   me.handler = SERVER_HANDLER;
844
845   SetYXXCapacity(&me, MAXCLIENTS);
846
847   me.lasttime = me.since = me.firsttime = CurrentTime;
848   hAddClient(&me);
849
850   check_class();
851   write_pidfile();
852
853   init_counters();
854
855   Debug((DEBUG_NOTICE, "Server ready..."));
856   ircd_log(L_NOTICE, "Server Ready");
857   thisServer.running = 1;
858
859   event_loop();
860   return 0;
861 }
862
863