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