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