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