ircu2.10.12 pk910 fork
[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 /** @file
21  * @brief Entry point and other initialization functions for the daemon.
22  * @version $Id: ircd.c 1907 2009-02-09 04:11:04Z entrope $
23  */
24 #include "config.h"
25
26 #include "ircd.h"
27 #include "IPcheck.h"
28 #include "class.h"
29 #include "client.h"
30 #include "crule.h"
31 #include "destruct_event.h"
32 #include "hash.h"
33 #include "ircd_alloc.h"
34 #include "ircd_events.h"
35 #include "ircd_features.h"
36 #include "ircd_log.h"
37 #include "ircd_reply.h"
38 #include "ircd_signal.h"
39 #include "ircd_string.h"
40 #include "ircd_crypt.h"
41 #include "jupe.h"
42 #include "list.h"
43 #include "match.h"
44 #include "motd.h"
45 #include "msg.h"
46 #include "numeric.h"
47 #include "numnicks.h"
48 #include "opercmds.h"
49 #include "parse.h"
50 #include "res.h"
51 #include "s_auth.h"
52 #include "s_bsd.h"
53 #include "s_conf.h"
54 #include "s_debug.h"
55 #include "s_misc.h"
56 #include "s_stats.h"
57 #include "send.h"
58 #include "ssl.h"
59 #include "sys.h"
60 #include "uping.h"
61 #include "userload.h"
62 #include "version.h"
63 #include "whowas.h"
64
65 /* #include <assert.h> -- Now using assert in ircd_log.h */
66 #include <errno.h>
67 #include <fcntl.h>
68 #include <netdb.h>
69 #include <pwd.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <sys/time.h>
74 #ifdef HAVE_SYS_RESOURCE_H
75 #include <sys/resource.h>
76 #endif
77 #include <sys/socket.h>
78 #include <sys/stat.h>
79 #include <sys/types.h>
80 #include <unistd.h>
81
82
83
84 /*----------------------------------------------------------------------------
85  * External stuff
86  *--------------------------------------------------------------------------*/
87 extern void init_counters(void);
88 extern void mem_dbg_initialise(void);
89
90 /*----------------------------------------------------------------------------
91  * Constants / Enums
92  *--------------------------------------------------------------------------*/
93 enum {
94   BOOT_DEBUG = 1,  /**< Enable debug output. */
95   BOOT_TTY   = 2,  /**< Stay connected to TTY. */
96   BOOT_CHKCONF = 4 /**< Exit after reading configuration file. */
97 };
98
99
100 /*----------------------------------------------------------------------------
101  * Global data (YUCK!)
102  *--------------------------------------------------------------------------*/
103 struct Client  me;                      /**< That's me */
104 struct Connection me_con;               /**< That's me too */
105 struct Client *GlobalClientList  = &me; /**< Pointer to beginning of
106                                            Client list */
107 time_t         TSoffset          = 0;   /**< Offset of timestamps to system clock */
108 int            GlobalRehashFlag  = 0;   /**< do a rehash if set */
109 int            GlobalRestartFlag = 0;   /**< do a restart if set */
110 time_t         CurrentTime;             /**< Updated every time we leave select() */
111
112 char          *configfile        = CPATH; /**< Server configuration file */
113 int            debuglevel        = -1;    /**< Server debug level  */
114 char          *debugmode         = "";    /**< Server debug level */
115 char          *dpath             = DPATH; /**< Working directory for daemon */
116 static char   *dbg_client;                /**< Client specifier for chkconf */
117
118 static struct Timer connect_timer; /**< timer structure for try_connections() */
119 static struct Timer ping_timer; /**< timer structure for check_pings() */
120 static struct Timer destruct_event_timer; /**< timer structure for exec_expired_destruct_events() */
121
122 /** Daemon information. */
123 static struct Daemon thisServer  = { 0, 0, 0, 0, 0, 0, -1 };
124
125 /** Non-zero until we want to exit. */
126 int running = 1;
127
128
129 /*----------------------------------------------------------------------------
130  * API: server_die
131  *--------------------------------------------------------------------------*/
132 /** Terminate the server with a message.
133  * @param[in] message Message to log and send to operators.
134  */
135 void server_die(const char *message)
136 {
137   /* log_write will send out message to both log file and as server notice */
138   log_write(LS_SYSTEM, L_CRIT, 0, "Server terminating: %s", message);
139   flush_connections(0);
140   close_connections(1);
141   running = 0;
142 }
143
144 /*----------------------------------------------------------------------------
145  * API: server_panic
146  *--------------------------------------------------------------------------*/
147 /** Immediately terminate the server with a message.
148  * @param[in] message Message to log, but not send to operators.
149  */
150 void server_panic(const char *message)
151 {
152   /* inhibit sending server notice--we may be panicking due to low memory */
153   log_write(LS_SYSTEM, L_CRIT, LOG_NOSNOTICE, "Server panic: %s", message);
154   flush_connections(0);
155   log_close();
156   close_connections(1);
157   exit(1);
158 }
159
160 /*----------------------------------------------------------------------------
161  * API: server_restart
162  *--------------------------------------------------------------------------*/
163 /** Restart the server with a message.
164  * @param[in] message Message to log and send to operators.
165  */
166 void server_restart(const char *message)
167 {
168   static int restarting = 0;
169
170   /* inhibit sending any server notices; we may be in a loop */
171   log_write(LS_SYSTEM, L_WARNING, LOG_NOSNOTICE, "Restarting Server: %s",
172             message);
173   if (restarting++) /* increment restarting to prevent looping */
174     return;
175
176   sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
177   Debug((DEBUG_NOTICE, "Restarting server..."));
178   flush_connections(0);
179
180   log_close();
181
182   close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG | BOOT_CHKCONF)));
183
184   reap_children();
185
186   execv(SPATH, thisServer.argv);
187
188   /* Have to reopen since it has been closed above */
189   log_reopen();
190
191   log_write(LS_SYSTEM, L_CRIT, 0, "execv(%s,%s) failed: %m", SPATH,
192             *thisServer.argv);
193
194   Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
195          SPATH, (strerror(errno)) ? strerror(errno) : ""));
196   exit(8);
197 }
198
199
200 /*----------------------------------------------------------------------------
201  * outofmemory:  Handler for out of memory conditions...
202  *--------------------------------------------------------------------------*/
203 /** Handle out-of-memory condition. */
204 static void outofmemory(void) {
205   Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
206   server_restart("Out of Memory");
207 }
208
209
210 /*----------------------------------------------------------------------------
211  * write_pidfile
212  *--------------------------------------------------------------------------*/
213 /** Write process ID to PID file. */
214 static void write_pidfile(void) {
215   char buff[20];
216
217   if (thisServer.pid_fd >= 0) {
218     memset(buff, 0, sizeof(buff));
219     sprintf(buff, "%5d\n", (int)getpid());
220     if (write(thisServer.pid_fd, buff, strlen(buff)) == -1)
221       Debug((DEBUG_NOTICE, "Error writing to pid file %s: %m",
222              feature_str(FEAT_PPATH)));
223     return;
224   }
225   Debug((DEBUG_NOTICE, "Error opening pid file %s: %m",
226          feature_str(FEAT_PPATH)));
227 }
228
229 /** Try to create the PID file.
230  * @return Zero on success; non-zero on any error.
231  */
232 static int check_pid(void)
233 {
234   struct flock lock;
235
236   lock.l_type = F_WRLCK;
237   lock.l_start = 0;
238   lock.l_whence = SEEK_SET;
239   lock.l_len = 0;
240
241   if ((thisServer.pid_fd = open(feature_str(FEAT_PPATH), O_CREAT | O_RDWR,
242                                 0600)) >= 0)
243     return fcntl(thisServer.pid_fd, F_SETLK, &lock) == -1;
244
245   return 1;
246 }
247
248
249 /** Look for any connections that we should try to initiate.
250  * Reschedules itself to run again at the appropriate time.
251  * @param[in] ev Timer event (ignored).
252  */
253 static void try_connections(struct Event* ev) {
254   struct ConfItem*  aconf;
255   struct ConfItem** pconf;
256   time_t            next;
257   struct Jupe*      ajupe;
258   int               hold;
259   int               done;
260
261   assert(ET_EXPIRE == ev_type(ev));
262   assert(0 != ev_timer(ev));
263
264   Debug((DEBUG_NOTICE, "Connection check at   : %s", myctime(CurrentTime)));
265   next = CurrentTime + feature_int(FEAT_CONNECTFREQUENCY);
266   done = 0;
267
268   for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
269     /* Only consider server items with non-zero port and non-zero
270      * connect times that are not actively juped.
271      */
272     if (!(aconf->status & CONF_SERVER)
273         || aconf->address.port == 0
274         || !(aconf->flags & CONF_AUTOCONNECT)
275         || ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe)))
276       continue;
277
278     /* Do we need to postpone this connection further? */
279     hold = aconf->hold > CurrentTime;
280
281     /* Update next possible connection check time. */
282     if (hold && next > aconf->hold)
283         next = aconf->hold;
284
285     /* Do not try to connect if its use is still on hold until future,
286      * we have already initiated a connection this try_connections(),
287      * too many links in its connection class, it is already linked,
288      * or if connect rules forbid a link now.
289      */
290     if (hold || done
291         || (ConfLinks(aconf) > ConfMaxLinks(aconf))
292         || FindServer(aconf->name)
293         || conf_eval_crule(aconf->name, CRULE_MASK))
294       continue;
295
296     /* Ensure it is at the end of the list for future checks. */
297     if (aconf->next) {
298       /* Find aconf's location in the list and splice it out. */
299       for (pconf = &GlobalConfList; *pconf; pconf = &(*pconf)->next)
300         if (*pconf == aconf)
301           *pconf = aconf->next;
302       /* Reinsert it at the end of the list (where pconf is now). */
303       *pconf = aconf;
304       aconf->next = 0;
305     }
306
307     /* Activate the connection itself. */
308     if (connect_server(aconf, 0))
309       sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
310                            aconf->name);
311
312     /* And stop looking for further candidates. */
313     done = 1;
314   }
315
316   Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
317   timer_add(&connect_timer, try_connections, 0, TT_ABSOLUTE, next);
318 }
319
320
321 /** Check for clients that have not sent a ping response recently.
322  * Reschedules itself to run again at the appropriate time.
323  * @param[in] ev Timer event (ignored).
324  */
325 static void check_pings(struct Event* ev) {
326   int expire     = 0;
327   int next_check = CurrentTime;
328   int max_ping   = 0;
329   int i;
330
331   assert(ET_EXPIRE == ev_type(ev));
332   assert(0 != ev_timer(ev));
333
334   next_check += feature_int(FEAT_PINGFREQUENCY);
335   
336   /* Scan through the client table */
337   for (i=0; i <= HighestFd; i++) {
338     struct Client *cptr = LocalClientArray[i];
339    
340     if (!cptr)
341       continue;
342      
343     assert(&me != cptr);  /* I should never be in the local client array! */
344    
345
346     /* Remove dead clients. */
347     if (IsDead(cptr)) {
348       exit_client(cptr, cptr, &me, cli_info(cptr));
349       continue;
350     }
351
352     max_ping = IsRegistered(cptr) ? client_get_ping(cptr) :
353       feature_int(FEAT_CONNECTTIMEOUT);
354    
355     Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
356            cli_name(cptr),
357            IsPingSent(cptr) ? "[Ping Sent]" : "[]", 
358            max_ping, (int)(CurrentTime - cli_lasttime(cptr))));
359
360     /* If it's a server and we have not sent an AsLL lately, do so. */
361     if (IsServer(cptr)) {
362       if (CurrentTime - cli_serv(cptr)->asll_last >= max_ping) {
363         char *asll_ts;
364
365         SetPingSent(cptr);
366         cli_serv(cptr)->asll_last = CurrentTime;
367         expire = cli_serv(cptr)->asll_last + max_ping;
368         asll_ts = militime_float(NULL);
369         sendcmdto_prio_one(&me, CMD_PING, cptr, "!%s %s %s", asll_ts,
370                            cli_name(cptr), asll_ts);
371       }
372
373       expire = cli_serv(cptr)->asll_last + max_ping;
374       if (expire < next_check)
375         next_check = expire;
376     }
377
378     /* Ok, the thing that will happen most frequently, is that someone will
379      * have sent something recently.  Cover this first for speed.
380      * -- 
381      * If it's an unregistered client and hasn't managed to register within
382      * max_ping then it's obviously having problems (broken client) or it's
383      * just up to no good, so we won't skip it, even if its been sending
384      * data to us. 
385      * -- hikari
386      */
387     if ((CurrentTime-cli_lasttime(cptr) < max_ping) && IsRegistered(cptr)) {
388       expire = cli_lasttime(cptr) + max_ping;
389       if (expire < next_check) 
390         next_check = expire;
391       continue;
392     }
393
394     /* Unregistered clients pingout after max_ping seconds, they don't
395      * get given a second chance - if they were then people could not quite
396      * finish registration and hold resources without being subject to k/g
397      * lines
398      */
399     if (!IsRegistered(cptr)) {
400       assert(!IsServer(cptr));
401       /* If client authorization time has expired, ask auth whether they
402        * should be checked again later. */
403       if ((CurrentTime-cli_firsttime(cptr) >= max_ping)
404           && auth_ping_timeout(cptr))
405         continue;
406       /* OK, they still have enough time left, so we'll just skip to the
407        * next client.  Set the next check to be when their time is up, if
408        * that's before the currently scheduled next check -- hikari */
409       expire = cli_firsttime(cptr) + max_ping;
410       if (expire < next_check)
411         next_check = expire;
412       continue;
413     }
414
415     /* Quit the client after max_ping*2 - they should have answered by now */
416     if (CurrentTime-cli_lasttime(cptr) >= (max_ping*2) )
417     {
418       /* If it was a server, then tell ops about it. */
419       if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
420         sendto_opmask_butone(0, SNO_OLDSNO,
421                              "No response from %s, closing link",
422                              cli_name(cptr));
423       exit_client_msg(cptr, cptr, &me, "Ping timeout");
424       continue;
425     }
426     
427     if (!IsPingSent(cptr))
428     {
429       /* If we haven't PINGed the connection and we haven't heard from it in a
430        * while, PING it to make sure it is still alive.
431        */
432       SetPingSent(cptr);
433
434       /* If we're late in noticing don't hold it against them :) */
435       cli_lasttime(cptr) = CurrentTime - max_ping;
436       
437       if (IsUser(cptr))
438         sendrawto_one(cptr, MSG_PING " :%s", cli_name(&me));
439       else
440         sendcmdto_prio_one(&me, CMD_PING, cptr, ":%s", cli_name(&me));
441     }
442     
443     expire = cli_lasttime(cptr) + max_ping * 2;
444     if (expire < next_check)
445       next_check=expire;
446   }
447   
448   assert(next_check >= CurrentTime);
449   
450   Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
451          CurrentTime, next_check-CurrentTime));
452   
453   timer_add(&ping_timer, check_pings, 0, TT_ABSOLUTE, next_check);
454 }
455
456
457 /** Parse command line arguments.
458  * Global variables are updated to reflect the arguments.
459  * As a side effect, makes sure the process's effective user id is the
460  * same as the real user id.
461  * @param[in] argc Number of arguments on command line.
462  * @param[in,out] argv Command-lne arguments.
463  */
464 static void parse_command_line(int argc, char** argv) {
465   const char *options = "d:f:h:nktvx:c:";
466   int opt;
467
468   if (thisServer.euid != thisServer.uid)
469     setuid(thisServer.uid);
470
471   /* Do we really need to sanity check the non-NULLness of optarg?  That's
472    * getopt()'s job...  Removing those... -zs
473    */
474   while ((opt = getopt(argc, argv, options)) != EOF)
475     switch (opt) {
476     case 'k':  thisServer.bootopt |= BOOT_CHKCONF | BOOT_TTY; break;
477     case 'c':  dbg_client = optarg;                    break;
478     case 'n':
479     case 't':  thisServer.bootopt |= BOOT_TTY;         break;
480     case 'd':  dpath      = optarg;                    break;
481     case 'f':  configfile = optarg;                    break;
482     case 'h':  ircd_strncpy(cli_name(&me), optarg, HOSTLEN); break;
483     case 'v':
484       printf("ircd %s\n", version);
485       printf("Event engines: ");
486 #ifdef USE_KQUEUE
487       printf("kqueue() ");
488 #endif
489 #ifdef USE_DEVPOLL
490       printf("/dev/poll ");
491 #endif
492 #ifdef USE_EPOLL
493       printf("epoll_*() ");
494 #endif
495 #ifdef USE_POLL
496       printf("poll()");
497 #else
498       printf("select()");
499 #endif
500       printf("\nCompiled for a maximum of %d connections.\n", MAXCONNECTIONS);
501
502
503       exit(0);
504       break;
505
506     case 'x':
507       debuglevel = atoi(optarg);
508       if (debuglevel < 0)
509         debuglevel = 0;
510       debugmode = optarg;
511       thisServer.bootopt |= BOOT_DEBUG;
512 #ifndef DEBUGMODE
513       printf("WARNING: DEBUGMODE disabled; -x has no effect.\n");
514 #endif
515       break;
516
517     default:
518       printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv] [-k [-c clispec]]\n"
519              "\n -f config\t specify explicit configuration file"
520              "\n -x loglevel\t set debug logging verbosity"
521              "\n -n or -t\t don't detach"
522              "\n -v\t\t display version"
523              "\n -k\t\t exit after checking config"
524              "\n -c clispec\t search for client/kill blocks matching client"
525              "\n\t\t clispec is comma-separated list of user@host,"
526              "\n\t\t user@ip, $Rrealname, and port number"
527              "\n\nServer not started.\n");
528       exit(1);
529     }
530 }
531
532
533 /** Become a daemon.
534  * @param[in] no_fork If non-zero, do not fork into the background.
535  */
536 static void daemon_init(int no_fork) {
537   if (no_fork)
538     return;
539
540   if (fork())
541     exit(0);
542
543 #ifdef TIOCNOTTY
544   {
545     int fd;
546     if ((fd = open("/dev/tty", O_RDWR)) > -1) {
547       ioctl(fd, TIOCNOTTY, 0);
548       close(fd);
549     }
550   }
551 #endif
552
553   setsid();
554 }
555
556 /** Check that we have access to a particular file.
557  * If we do not have access to the file, complain on stderr.
558  * @param[in] path File name to check for access.
559  * @param[in] which Configuration character associated with file.
560  * @param[in] mode Bitwise combination of R_OK, W_OK, X_OK and/or F_OK.
561  * @return Non-zero if we have the necessary access, zero if not.
562  */
563 static char check_file_access(const char *path, char which, int mode) {
564   if (!access(path, mode))
565     return 1;
566
567   fprintf(stderr, 
568           "Check on %cPATH (%s) failed: %s\n"
569           "Please create this file and/or rerun `configure' "
570           "using --with-%cpath and recompile to correct this.\n",
571           which, path, strerror(errno), which);
572
573   return 0;
574 }
575
576
577 /*----------------------------------------------------------------------------
578  * set_core_limit
579  *--------------------------------------------------------------------------*/
580 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
581 /** Set the core size soft limit to the same as the hard limit. */
582 static void set_core_limit(void) {
583   struct rlimit corelim;
584
585   if (getrlimit(RLIMIT_CORE, &corelim)) {
586     fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
587     corelim.rlim_max = RLIM_INFINITY;   /* Try to recover */
588   }
589
590   corelim.rlim_cur = corelim.rlim_max;
591   if (setrlimit(RLIMIT_CORE, &corelim))
592     fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
593 }
594 #endif
595
596
597
598 /** Complain to stderr if any user or group ID belongs to the superuser.
599  * @return Non-zero if all IDs are okay, zero if some are 0.
600  */
601 static int set_userid_if_needed(void) {
602   if (getuid() == 0 || geteuid() == 0 ||
603       getgid() == 0 || getegid() == 0) {
604     fprintf(stderr, "ERROR:  This server will not run as superuser.\n");
605     return 0;
606   }
607
608   return 1;
609 }
610
611
612 /*----------------------------------------------------------------------------
613  * main - entrypoint
614  *
615  * TODO:  This should set the basic environment up and start the main loop.
616  *        we're doing waaaaaaaaay too much server initialization here.  I hate
617  *        long and ugly control paths...  -smd
618  *--------------------------------------------------------------------------*/
619 /** Run the daemon.
620  * @param[in] argc Number of arguments in \a argv.
621  * @param[in] argv Arguments to program execution.
622  */
623 int main(int argc, char **argv) {
624   CurrentTime = time(NULL);
625   printf("Starting IRCu 2.10.12.10 by pk910.\n");
626   printf("you are not allowed to use this version without my permission\n");
627   thisServer.argc = argc;
628   thisServer.argv = argv;
629   thisServer.uid  = getuid();
630   thisServer.euid = geteuid();
631
632 #ifdef MDEBUG
633   mem_dbg_initialise();
634 #endif
635
636 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
637   set_core_limit();
638 #endif
639
640   umask(077);                   /* better safe than sorry --SRB */
641   memset(&me, 0, sizeof(me));
642   memset(&me_con, 0, sizeof(me_con));
643   cli_connect(&me) = &me_con;
644   cli_fd(&me) = -1;
645
646   parse_command_line(argc, argv);
647
648   if (chdir(dpath)) {
649     fprintf(stderr, "Fail: Cannot chdir(%s): %s, check DPATH\n", dpath, strerror(errno));
650     return 2;
651   }
652
653   if (!set_userid_if_needed())
654     return 3;
655
656   /* Check paths for accessibility */
657   if (!check_file_access(SPATH, 'S', X_OK) ||
658       !check_file_access(configfile, 'C', R_OK))
659     return 4;
660
661   if (!init_connection_limits())
662     return 9;
663
664   close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY | BOOT_CHKCONF)));
665
666   /* daemon_init() must be before event_init() because kqueue() FDs
667    * are, perversely, not inherited across fork().
668    */
669   daemon_init(thisServer.bootopt & BOOT_TTY);
670
671 #ifdef DEBUGMODE
672   /* Must reserve fd 2... */
673   if (debuglevel >= 0 && !(thisServer.bootopt & BOOT_TTY)) {
674     int fd;
675     if ((fd = open("/dev/null", O_WRONLY)) < 0) {
676       fprintf(stderr, "Unable to open /dev/null (to reserve fd 2): %s\n",
677               strerror(errno));
678       return 8;
679     }
680     if (fd != 2 && dup2(fd, 2) < 0) {
681       fprintf(stderr, "Unable to reserve fd 2; dup2 said: %s\n",
682               strerror(errno));
683       return 8;
684     }
685   }
686 #endif
687
688   event_init(MAXCONNECTIONS);
689
690   setup_signals();
691   feature_init(); /* initialize features... */
692   log_init(*argv);
693   set_nomem_handler(outofmemory);
694
695   initload();
696   init_list();
697   init_hash();
698   init_class();
699   initwhowas();
700   initmsgtree();
701   initstats();
702
703   /* we need this for now, when we're modular this 
704      should be removed -- hikari */
705   ircd_crypt_init();
706
707   motd_init();
708
709   if (!init_conf()) {
710     log_write(LS_SYSTEM, L_CRIT, 0, "Failed to read configuration file %s",
711               configfile);
712     return 7;
713   }
714
715   if (thisServer.bootopt & BOOT_CHKCONF) {
716     if (dbg_client)
717       conf_debug_iline(dbg_client);
718     fprintf(stderr, "Configuration file %s checked okay.\n", configfile);
719     return 0;
720   }
721
722   debug_init(thisServer.bootopt & BOOT_TTY);
723   if (check_pid()) {
724     Debug((DEBUG_FATAL, "Failed to acquire PID file lock after fork"));
725     exit(2);
726   }
727
728   init_server_identity();
729
730   uping_init();
731   ssl_init();
732   stats_init();
733
734   IPcheck_init();
735   timer_add(timer_init(&connect_timer), try_connections, 0, TT_RELATIVE, 1);
736   timer_add(timer_init(&ping_timer), check_pings, 0, TT_RELATIVE, 1);
737   timer_add(timer_init(&destruct_event_timer), exec_expired_destruct_events, 0, TT_PERIODIC, 60);
738
739   CurrentTime = time(NULL);
740
741   SetMe(&me);
742   cli_magic(&me) = CLIENT_MAGIC;
743   cli_from(&me) = &me;
744   make_server(&me);
745
746   cli_serv(&me)->timestamp = TStime();  /* Abuse own link timestamp as start TS */
747   cli_serv(&me)->prot      = atoi(MAJOR_PROTOCOL);
748   cli_serv(&me)->up        = &me;
749   cli_serv(&me)->down      = NULL;
750   cli_handler(&me)         = SERVER_HANDLER;
751
752   SetYXXCapacity(&me, MAXCLIENTS);
753
754   cli_lasttime(&me) = cli_since(&me) = cli_firsttime(&me) = CurrentTime;
755
756   hAddClient(&me);
757   SetIPv6(&me);
758
759   write_pidfile();
760   init_counters();
761
762   Debug((DEBUG_NOTICE, "Server ready..."));
763   log_write(LS_SYSTEM, L_NOTICE, 0, "Server Ready");
764
765   event_loop();
766
767   return 0;
768 }
769
770