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