Author: Jeekay <jeekay@irc.planetarion.com>
[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 "config.h"
23
24 #include "ircd.h"
25 #include "IPcheck.h"
26 #include "class.h"
27 #include "client.h"
28 #include "crule.h"
29 #include "destruct_event.h"
30 #include "hash.h"
31 #include "ircd_alloc.h"
32 #include "ircd_events.h"
33 #include "ircd_features.h"
34 #include "ircd_log.h"
35 #include "ircd_reply.h"
36 #include "ircd_signal.h"
37 #include "ircd_string.h"
38 #include "jupe.h"
39 #include "list.h"
40 #include "match.h"
41 #include "motd.h"
42 #include "msg.h"
43 #include "numeric.h"
44 #include "numnicks.h"
45 #include "parse.h"
46 #include "res.h"
47 #include "s_auth.h"
48 #include "s_bsd.h"
49 #include "s_conf.h"
50 #include "s_debug.h"
51 #include "s_misc.h"
52 #include "send.h"
53 #include "sys.h"
54 #include "uping.h"
55 #include "userload.h"
56 #include "version.h"
57 #include "whowas.h"
58
59 #include <assert.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <netdb.h>
63 #include <pwd.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <sys/socket.h>
68 #include <sys/stat.h>
69 #include <sys/types.h>
70 #include <unistd.h>
71
72
73
74 /*----------------------------------------------------------------------------
75  * External stuff
76  *--------------------------------------------------------------------------*/
77 extern void init_counters(void);
78
79 /*----------------------------------------------------------------------------
80  * Constants / Enums
81  *--------------------------------------------------------------------------*/
82 enum {
83   BOOT_DEBUG = 1,
84   BOOT_TTY   = 2
85 };
86
87
88 /*----------------------------------------------------------------------------
89  * Global data (YUCK!)
90  *--------------------------------------------------------------------------*/
91 struct Client  me;                      /* That's me */
92 struct Connection me_con;               /* That's me too */
93 struct Client *GlobalClientList  = &me; /* Pointer to beginning of
94                                            Client list */
95 time_t         TSoffset          = 0;/* Offset of timestamps to system clock */
96 int            GlobalRehashFlag  = 0;   /* do a rehash if set */
97 int            GlobalRestartFlag = 0;   /* do a restart if set */
98 time_t         CurrentTime;          /* Updated every time we leave select() */
99
100 char          *configfile        = CPATH; /* Server configuration file */
101 int            debuglevel        = -1;    /* Server debug level  */
102 char          *debugmode         = "";    /* Server debug level */
103 static char   *dpath             = DPATH;
104
105 static struct Timer connect_timer; /* timer structure for try_connections() */
106 static struct Timer ping_timer; /* timer structure for check_pings() */
107 static struct Timer destruct_event_timer; /* timer structure for exec_expired_destruct_events() */
108
109 static struct Daemon thisServer  = { 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0 };
110
111 int running = 1;
112
113
114 /*----------------------------------------------------------------------------
115  * API: server_die
116  *--------------------------------------------------------------------------*/
117 void server_die(const char* message) {
118   /* log_write will send out message to both log file and as server notice */
119   log_write(LS_SYSTEM, L_CRIT, 0, "Server terminating: %s", message);
120   flush_connections(0);
121   close_connections(1);
122   running = 0;
123 }
124
125
126 /*----------------------------------------------------------------------------
127  * API: server_restart
128  *--------------------------------------------------------------------------*/
129 void server_restart(const char* message) {
130   static int restarting = 0;
131
132   /* inhibit sending any server notices; we may be in a loop */
133   log_write(LS_SYSTEM, L_WARNING, LOG_NOSNOTICE, "Restarting Server: %s",
134             message);
135   if (restarting++) /* increment restarting to prevent looping */
136     return;
137
138   sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
139   Debug((DEBUG_NOTICE, "Restarting server..."));
140   flush_connections(0);
141
142   log_close();
143
144   close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG)));
145
146   execv(SPATH, thisServer.argv);
147
148   /* Have to reopen since it has been closed above */
149   log_reopen();
150
151   log_write(LS_SYSTEM, L_CRIT, 0, "execv(%s,%s) failed: %m", SPATH,
152             *thisServer.argv);
153
154   Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
155          SPATH, (strerror(errno)) ? strerror(errno) : ""));
156   exit(8);
157 }
158
159
160 /*----------------------------------------------------------------------------
161  * outofmemory:  Handler for out of memory conditions...
162  *--------------------------------------------------------------------------*/
163 static void outofmemory(void) {
164   Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
165   server_restart("Out of Memory");
166
167
168
169 /*----------------------------------------------------------------------------
170  * write_pidfile
171  *--------------------------------------------------------------------------*/
172 static void write_pidfile(void) {
173   char buff[20];
174
175   if (thisServer.pid_fd >= 0) {
176     memset(buff, 0, sizeof(buff));
177     sprintf(buff, "%5d\n", (int)getpid());
178     if (write(thisServer.pid_fd, buff, strlen(buff)) == -1)
179       Debug((DEBUG_NOTICE, "Error writing to pid file %s: %m",
180              feature_str(FEAT_PPATH)));
181     return;
182   }
183   Debug((DEBUG_NOTICE, "Error opening pid file %s: %m",
184          feature_str(FEAT_PPATH)));
185 }
186
187 /* check_pid
188  * 
189  * inputs: 
190  *   none
191  * returns:
192  *   true - if the pid file exists (and is readable), and the pid refered
193  *          to in the file is still running.
194  *   false - otherwise.
195  */
196 static int check_pid(void)
197 {
198   struct flock lock;
199
200   lock.l_type = F_WRLCK;
201   lock.l_start = 0;
202   lock.l_whence = SEEK_SET;
203   lock.l_len = 0;
204
205   if ((thisServer.pid_fd = open(feature_str(FEAT_PPATH), O_CREAT | O_RDWR,
206                                 0600)) >= 0)
207     return fcntl(thisServer.pid_fd, F_SETLK, &lock);
208
209   return 0;
210 }
211   
212
213 /*----------------------------------------------------------------------------
214  * try_connections
215  *
216  * Scan through configuration and try new connections.
217  *
218  * Returns the calendar time when the next call to this
219  * function should be made latest. (No harm done if this
220  * is called earlier or later...)
221  *--------------------------------------------------------------------------*/
222 static void try_connections(struct Event* ev) {
223   struct ConfItem*  aconf;
224   struct Client*    cptr;
225   struct ConfItem** pconf;
226   int               connecting;
227   int               confrq;
228   time_t            next        = 0;
229   struct ConnectionClass* cltmp;
230   struct ConfItem*  con_conf    = 0;
231   struct Jupe*      ajupe;
232   const char*       con_class   = NULL;
233
234   assert(ET_EXPIRE == ev_type(ev));
235   assert(0 != ev_timer(ev));
236
237   connecting = FALSE;
238   Debug((DEBUG_NOTICE, "Connection check at   : %s", myctime(CurrentTime)));
239   for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
240     /* Also when already connecting! (update holdtimes) --SRB */
241     if (!(aconf->status & CONF_SERVER) || aconf->port == 0 || aconf->hold == 0)
242       continue;
243
244     /* Also skip juped servers */
245     if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
246       continue;
247
248     /* Skip this entry if the use of it is still on hold until
249      * future. Otherwise handle this entry (and set it on hold until next
250      * time). Will reset only hold times, if already made one successfull
251      * connection... [this algorithm is a bit fuzzy... -- msa >;) ]
252      */
253     if (aconf->hold > CurrentTime && (next > aconf->hold || next == 0)) {
254       next = aconf->hold;
255       continue;
256     }
257
258     cltmp = aconf->conn_class;
259     confrq = get_con_freq(cltmp);
260     if(confrq == 0)
261       aconf->hold = next = 0;
262     else
263       aconf->hold = CurrentTime + confrq;
264
265     /* Found a CONNECT config with port specified, scan clients and see if
266      * this server is already connected?
267      */
268     cptr = FindServer(aconf->name);
269
270     if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
271         (!connecting /*|| (ConClass(cltmp) > con_class)*/)) {
272       /*
273        * Check connect rules to see if we're allowed to try
274        */
275       if (0 == conf_eval_crule(aconf->name, CRULE_MASK)) {
276         con_class = ConClass(cltmp);
277         con_conf = aconf;
278         /* We connect only one at time... */
279         connecting = TRUE;
280       }
281     }
282     if ((next > aconf->hold) || (next == 0))
283       next = aconf->hold;
284   }
285   if (connecting) {
286     if (con_conf->next) { /* are we already last? */
287       /* Put the current one at the end and make sure we try all connections */
288       for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
289         if (aconf == con_conf)
290           *pconf = aconf->next;
291       (*pconf = con_conf)->next = 0;
292     }
293
294     if (connect_server(con_conf, 0, 0))
295       sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
296                            con_conf->name);
297   }
298
299   if (next == 0)
300     next = CurrentTime + feature_int(FEAT_CONNECTFREQUENCY);
301
302   Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
303
304   timer_add(&connect_timer, try_connections, 0, TT_ABSOLUTE, next);
305 }
306
307
308 /*----------------------------------------------------------------------------
309  * check_pings
310  *
311  * TODO: This should be moved out of ircd.c.  It's protocol-specific when you
312  *       get right down to it.  Can't really be done until the server is more
313  *       modular, however...
314  *--------------------------------------------------------------------------*/
315 static void check_pings(struct Event* ev) {
316   int expire     = 0;
317   int next_check = CurrentTime;
318   int max_ping   = 0;
319   int i;
320
321   assert(ET_EXPIRE == ev_type(ev));
322   assert(0 != ev_timer(ev));
323
324   next_check += feature_int(FEAT_PINGFREQUENCY);
325   
326   /* Scan through the client table */
327   for (i=0; i <= HighestFd; i++) {
328     struct Client *cptr = LocalClientArray[i];
329    
330     if (!cptr)
331       continue;
332      
333     assert(&me != cptr);  /* I should never be in the local client array! */
334    
335
336     /* Remove dead clients. */
337     if (IsDead(cptr)) {
338       exit_client(cptr, cptr, &me, cli_info(cptr));
339       continue;
340     }
341
342     max_ping = IsRegistered(cptr) ? client_get_ping(cptr) :
343       feature_int(FEAT_CONNECTTIMEOUT);
344    
345     Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
346            cli_name(cptr),
347            (cli_flags(cptr) & FLAGS_PINGSENT) ? "[Ping Sent]" : "[]", 
348            max_ping, (int)(CurrentTime - cli_lasttime(cptr))));
349           
350
351     /* Ok, the thing that will happen most frequently, is that someone will
352      * have sent something recently.  Cover this first for speed.
353      */
354     if (CurrentTime-cli_lasttime(cptr) < max_ping) {
355       expire = cli_lasttime(cptr) + max_ping;
356       if (expire < next_check) 
357         next_check = expire;
358       continue;
359     }
360
361     /* Unregistered clients pingout after max_ping seconds, they don't
362      * get given a second chance - if they were then people could not quite
363      * finish registration and hold resources without being subject to k/g
364      * lines
365      */
366     if (!IsRegistered(cptr)) {
367       /* Display message if they have sent a NICK and a USER but no
368        * nospoof PONG.
369        */
370       if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
371         send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
372                    ":Your client may not be compatible with this server.");
373         send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
374                    ":Compatible clients are available at "
375                    URL_CLIENTS);
376       }    
377       exit_client_msg(cptr,cptr,&me, "Ping Timeout");
378       continue;
379     }
380     
381     if (!(cli_flags(cptr) & FLAGS_PINGSENT)) {
382       /* If we havent PINGed the connection and we havent heard from it in a
383        * while, PING it to make sure it is still alive.
384        */
385       cli_flags(cptr) |= FLAGS_PINGSENT;
386
387       /* If we're late in noticing don't hold it against them :) */
388       cli_lasttime(cptr) = CurrentTime - max_ping;
389       
390       if (IsUser(cptr))
391         sendrawto_one(cptr, MSG_PING " :%s", cli_name(&me));
392       else
393         sendcmdto_one(&me, CMD_PING, cptr, ":%s", cli_name(&me));
394     }
395     
396     /* Quit the client after max_ping*2 - they should have answered by now */
397     if (CurrentTime-cli_lasttime(cptr) >= (max_ping*2) ) {
398       /* If it was a server, then tell ops about it. */
399       if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
400         sendto_opmask_butone(0, SNO_OLDSNO,
401                              "No response from %s, closing link",
402                              cli_name(cptr));
403       exit_client_msg(cptr, cptr, &me, "Ping timeout");
404       continue;
405     }
406     
407     expire = cli_lasttime(cptr) + max_ping * 2;
408     if (expire < next_check)
409       next_check=expire;
410   }
411   
412   assert(next_check >= CurrentTime);
413   
414   Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
415          CurrentTime, next_check-CurrentTime));
416   
417   timer_add(&ping_timer, check_pings, 0, TT_ABSOLUTE, next_check);
418 }
419
420
421 /*----------------------------------------------------------------------------
422  * parse_command_line
423  * Side Effects: changes GLOBALS me, thisServer, dpath, configfile, debuglevel
424  * debugmode
425  *--------------------------------------------------------------------------*/
426 static void parse_command_line(int argc, char** argv) {
427   const char *options = "d:f:h:ntvx:";
428   int opt;
429
430   if (thisServer.euid != thisServer.uid)
431     setuid(thisServer.uid);
432
433   /* Do we really need to santiy check the non-NULLness of optarg?  That's
434    * getopt()'s job...  Removing those... -zs
435    */
436   while ((opt = getopt(argc, argv, options)) != EOF)
437     switch (opt) {
438     case 'n':
439     case 't':  thisServer.bootopt |= BOOT_TTY;         break;
440     case 'd':  dpath      = optarg;                    break;
441     case 'f':  configfile = optarg;                    break;
442     case 'h':  ircd_strncpy(cli_name(&me), optarg, HOSTLEN); break;
443     case 'v':
444       printf("ircd %s\n", version);
445       printf("Event engines: ");
446 #ifdef USE_KQUEUE
447       printf("kqueue() ");
448 #endif
449 #ifdef USE_DEVPOLL
450       printf("/dev/poll ");
451 #endif
452 #ifdef USE_POLL
453       printf("poll()");
454 #else
455       printf("select()");
456 #endif
457       printf("\nCompiled for a maximum of %d connections.\n", MAXCONNECTIONS);
458
459
460       exit(0);
461       break;
462       
463     case 'x':
464       debuglevel = atoi(optarg);
465       if (debuglevel < 0)
466         debuglevel = 0;
467       debugmode = optarg;
468       thisServer.bootopt |= BOOT_DEBUG;
469       break;
470       
471     default:
472       printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
473       printf("\n -n -t\t Don't detach\n -v\t display version\n\n");
474       printf("Server not started.\n");
475       exit(1);
476     }
477 }
478
479
480 /*----------------------------------------------------------------------------
481  * daemon_init
482  *--------------------------------------------------------------------------*/
483 static void daemon_init(int no_fork) {
484   if (!init_connection_limits())
485     exit(9);
486
487   close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
488
489   if (no_fork)
490     return;
491
492   if (fork())
493     exit(0);
494
495 #ifdef TIOCNOTTY
496   {
497     int fd;
498     if ((fd = open("/dev/tty", O_RDWR)) > -1) {
499       ioctl(fd, TIOCNOTTY, 0);
500       close(fd);
501     }
502   }
503 #endif
504
505   setsid();
506 }
507
508 /*----------------------------------------------------------------------------
509  * check_file_access:  random helper function to make sure that a file is
510  *                     accessible in a certain way, and complain if not.
511  *--------------------------------------------------------------------------*/
512 static char check_file_access(const char *path, char which, int mode) {
513   if (!access(path, mode))
514     return 1;
515
516   fprintf(stderr, 
517           "Check on %cPATH (%s) failed: %s\n"
518           "Please create this file and/or rerun `configure' "
519           "using --with-%cpath and recompile to correct this.\n",
520           which, path, strerror(errno), which);
521
522   return 0;
523 }
524
525
526 /*----------------------------------------------------------------------------
527  * set_core_limit
528  *--------------------------------------------------------------------------*/
529 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
530 static void set_core_limit(void) {
531   struct rlimit corelim;
532
533   if (getrlimit(RLIMIT_CORE, &corelim)) {
534     fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
535     corelim.rlim_max = RLIM_INFINITY;   /* Try to recover */
536   }
537
538   corelim.rlim_cur = corelim.rlim_max;
539   if (setrlimit(RLIMIT_CORE, &corelim))
540     fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
541 }
542 #endif
543
544
545
546 /*----------------------------------------------------------------------------
547  * set_userid_if_needed()
548  *--------------------------------------------------------------------------*/
549 static int set_userid_if_needed(void) {
550   if (getuid() == 0 || geteuid() == 0 ||
551       getgid() == 0 || getegid() == 0) {
552     fprintf(stderr, "ERROR:  This server will not run as superuser.\n");
553     return 0;
554   }
555
556   return 1;
557 }
558
559
560 /*----------------------------------------------------------------------------
561  * main - entrypoint
562  *
563  * TODO:  This should set the basic environment up and start the main loop.
564  *        we're doing waaaaaaaaay too much server initialization here.  I hate
565  *        long and ugly control paths...  -smd
566  *--------------------------------------------------------------------------*/
567 int main(int argc, char **argv) {
568   CurrentTime = time(NULL);
569
570   thisServer.argc = argc;
571   thisServer.argv = argv;
572   thisServer.uid  = getuid();
573   thisServer.euid = geteuid();
574
575 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
576   set_core_limit();
577 #endif
578
579   umask(077);                   /* better safe than sorry --SRB */
580   memset(&me, 0, sizeof(me));
581   memset(&me_con, 0, sizeof(me_con));
582   cli_connect(&me) = &me_con;
583   cli_fd(&me) = -1;
584
585   parse_command_line(argc, argv);
586
587   if (chdir(dpath)) {
588     fprintf(stderr, "Fail: Cannot chdir(%s): %s, check DPATH\n", dpath, strerror(errno));
589     return 2;
590   }
591
592   if (!set_userid_if_needed())
593     return 3;
594
595   /* Check paths for accessibility */
596   if (!check_file_access(SPATH, 'S', X_OK) ||
597       !check_file_access(configfile, 'C', R_OK))
598     return 4;
599
600   debug_init(thisServer.bootopt & BOOT_TTY);
601   daemon_init(thisServer.bootopt & BOOT_TTY);
602   event_init(MAXCONNECTIONS);
603
604   setup_signals();
605   feature_init(); /* initialize features... */
606   log_init(*argv);
607   if (check_pid()) {
608     Debug((DEBUG_FATAL, "Failed to acquire PID file lock after fork"));
609     exit(2);
610   }
611   set_nomem_handler(outofmemory);
612   
613   if (!init_string()) {
614     log_write(LS_SYSTEM, L_CRIT, 0, "Failed to initialize string module");
615     return 6;
616   }
617
618   initload();
619   init_list();
620   init_hash();
621   init_class();
622   initwhowas();
623   initmsgtree();
624   initstats();
625
626   init_resolver();
627
628   motd_init();
629
630   if (!init_conf()) {
631     log_write(LS_SYSTEM, L_CRIT, 0, "Failed to read configuration file %s",
632               configfile);
633     return 7;
634   }
635
636   init_server_identity();
637
638   uping_init();
639
640   IPcheck_init();
641   timer_add(timer_init(&connect_timer), try_connections, 0, TT_RELATIVE, 1);
642   timer_add(timer_init(&ping_timer), check_pings, 0, TT_RELATIVE, 1);
643   timer_add(timer_init(&destruct_event_timer), exec_expired_destruct_events, 0, TT_PERIODIC, 60);
644
645   CurrentTime = time(NULL);
646
647   SetMe(&me);
648   cli_magic(&me) = CLIENT_MAGIC;
649   cli_from(&me) = &me;
650   make_server(&me);
651
652   cli_serv(&me)->timestamp = TStime();  /* Abuse own link timestamp as start TS */
653   cli_serv(&me)->prot      = atoi(MAJOR_PROTOCOL);
654   cli_serv(&me)->up        = &me;
655   cli_serv(&me)->down      = NULL;
656   cli_handler(&me)         = SERVER_HANDLER;
657
658   SetYXXCapacity(&me, MAXCLIENTS);
659
660   cli_lasttime(&me) = cli_since(&me) = cli_firsttime(&me) = CurrentTime;
661
662   hAddClient(&me);
663
664   write_pidfile();
665   init_counters();
666
667   Debug((DEBUG_NOTICE, "Server ready..."));
668   log_write(LS_SYSTEM, L_NOTICE, 0, "Server Ready");
669
670   event_loop();
671
672   return 0;
673 }
674
675