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