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