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