Restore stats_spy hook that was removed in commit 401f2454671ca233e35b0e6e4f3fa4c43cd...
[seven-1.x.git] / src / ircd.c
blob4c0a8a04cb1333a7a7e9842d11c3d76a8ce81d8d
1 /*
2 * ircd-ratbox: A slightly useful ircd.
3 * ircd.c: Starts up and runs the ircd.
5 * Copyright (C) 1990 Jarkko Oikarinen and University of Oulu, Co Center
6 * Copyright (C) 1996-2002 Hybrid Development Team
7 * Copyright (C) 2002-2005 ircd-ratbox development team
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
22 * USA
25 #include "stdinc.h"
26 #include "setup.h"
27 #include "config.h"
29 #include "tools.h"
30 #include "ircd.h"
31 #include "channel.h"
32 #include "class.h"
33 #include "client.h"
34 #include "common.h"
35 #include "event.h"
36 #include "hash.h"
37 #include "irc_string.h"
38 #include "ircd_signal.h"
39 #include "sprintf_irc.h"
40 #include "msg.h" /* msgtab */
41 #include "hostmask.h"
42 #include "numeric.h"
43 #include "parse.h"
44 #include "res.h"
45 #include "restart.h"
46 #include "s_auth.h"
47 #include "commio.h"
48 #include "s_conf.h"
49 #include "s_log.h"
50 #include "s_serv.h" /* try_connections */
51 #include "s_user.h"
52 #include "s_stats.h"
53 #include "scache.h"
54 #include "send.h"
55 #include "supported.h"
56 #include "whowas.h"
57 #include "modules.h"
58 #include "memory.h"
59 #include "hook.h"
60 #include "ircd_getopt.h"
61 #include "balloc.h"
62 #include "newconf.h"
63 #include "patricia.h"
64 #include "reject.h"
65 #include "s_conf.h"
66 #include "s_newconf.h"
67 #include "cache.h"
68 #include "monitor.h"
69 #include "libseven.h"
70 #include "patchlevel.h"
71 #include "serno.h"
74 * Try and find the correct name to use with getrlimit() for setting the max.
75 * number of files allowed to be open by this process.
77 int _seven_data_version = SEVEN_DV;
79 extern int ServerRunning, initialVMTop;
80 extern struct LocalUser meLocalUser;
81 extern char **myargv;
84 * get_vm_top - get the operating systems notion of the resident set size
86 static unsigned long
87 get_vm_top(void)
90 * NOTE: sbrk is not part of the ANSI C library or the POSIX.1 standard
91 * however it seems that everyone defines it. Calling sbrk with a 0
92 * argument will return a pointer to the top of the process virtual
93 * memory without changing the process size, so this call should be
94 * reasonably safe (sbrk returns the new value for the top of memory).
95 * This code relies on the notion that the address returned will be an
96 * offset from 0 (NULL), so the result of sbrk is cast to a size_t and
97 * returned. We really shouldn't be using it here but...
99 void *vptr = sbrk(0);
100 return (unsigned long) vptr;
104 * get_maxrss - get the operating systems notion of the resident set size
106 unsigned long
107 get_maxrss(void)
109 return get_vm_top() - initialVMTop;
113 * print_startup - print startup information
115 static void
116 print_startup(int pid)
118 inotice("now running in %s mode from %s as pid %d ...",
119 !server_state_foreground ? "background" : "foreground",
120 ConfigFileEntry.dpath, pid);
122 /* let the parent process know the initialization was successful
123 * -- jilles */
124 if (!server_state_foreground)
125 write(0, ".", 1);
126 fclose(stdin);
127 fclose(stdout);
128 fclose(stderr);
129 open("/dev/null", O_RDWR);
130 dup2(0, 1);
131 dup2(0, 2);
134 static void
135 ircd_log_cb(const char *str)
137 ilog(L_MAIN, "%s", str);
141 * Why EXIT_FAILURE here?
142 * Because if ircd_die_cb() is called it's because of a fatal
143 * error inside libseven, and we don't know how to handle the
144 * exception, so it is logical to return a FAILURE exit code here.
145 * --nenolod
147 static void
148 ircd_die_cb(const char *str)
150 /* Try to get the message out to currently logged in operators. */
151 sendto_realops_snomask(SNO_GENERAL, L_NETWIDE, "Server panic! %s", str);
152 inotice("server panic: %s", str);
154 unlink(pidFileName);
155 exit(EXIT_FAILURE);
159 * init_sys
161 * inputs - boot_daemon flag
162 * output - none
163 * side effects - if boot_daemon flag is not set, don't daemonize
165 static void
166 init_sys(void)
168 #if defined(RLIMIT_FD_MAX) && defined(HAVE_SYS_RLIMIT_H)
169 struct rlimit limit;
171 if(!getrlimit(RLIMIT_FD_MAX, &limit))
174 if(limit.rlim_max < MAXCONNECTIONS)
176 fprintf(stderr, "ircd fd table too big\n");
177 fprintf(stderr, "Hard Limit: %ld IRC max: %d\n",
178 (long) limit.rlim_max, MAXCONNECTIONS);
179 fprintf(stderr, "Fix MAXCONNECTIONS\n");
180 exit(-1);
183 limit.rlim_cur = limit.rlim_max; /* make soft limit the max */
184 if(setrlimit(RLIMIT_FD_MAX, &limit) == -1)
186 fprintf(stderr, "error setting max fd's to %ld\n", (long) limit.rlim_cur);
187 exit(EXIT_FAILURE);
190 #endif /* RLIMIT_FD_MAX */
193 static int
194 make_daemon(void)
196 int pid;
197 int pip[2];
198 char c;
200 if (pipe(pip) < 0)
202 perror("pipe");
203 exit(EXIT_FAILURE);
205 dup2(pip[1], 0);
206 close(pip[1]);
207 if((pid = fork()) < 0)
209 perror("fork");
210 exit(EXIT_FAILURE);
212 else if(pid > 0)
214 close(0);
215 /* Wait for initialization to finish, successfully or
216 * unsuccessfully. Until this point the child may still
217 * write to stdout/stderr.
218 * -- jilles */
219 if (read(pip[0], &c, 1) > 0)
220 exit(EXIT_SUCCESS);
221 else
222 exit(EXIT_FAILURE);
225 close(pip[0]);
226 setsid();
227 /* fclose(stdin);
228 fclose(stdout);
229 fclose(stderr); */
231 return 0;
234 static int printVersion = 0;
236 struct lgetopt myopts[] = {
237 {"dlinefile", &ConfigFileEntry.dlinefile,
238 STRING, "File to use for dlines.conf"},
239 {"configfile", &ConfigFileEntry.configfile,
240 STRING, "File to use for ircd.conf"},
241 {"klinefile", &ConfigFileEntry.klinefile,
242 STRING, "File to use for klines.conf"},
243 {"xlinefile", &ConfigFileEntry.xlinefile,
244 STRING, "File to use for xlines.conf"},
245 {"resvfile", &ConfigFileEntry.resvfile,
246 STRING, "File to use for resv.conf"},
247 {"logfile", &logFileName,
248 STRING, "File to use for ircd.log"},
249 {"pidfile", &pidFileName,
250 STRING, "File to use for process ID"},
251 {"foreground", &server_state_foreground,
252 YESNO, "Run in foreground (don't detach)"},
253 {"version", &printVersion,
254 YESNO, "Print version and exit"},
255 {"conftest", &testing_conf,
256 YESNO, "Test the configuration files and exit"},
257 {"help", NULL, USAGE, "Print this text"},
258 {NULL, NULL, STRING, NULL},
261 void
262 set_time(void)
264 struct timeval newtime;
265 newtime.tv_sec = 0;
266 newtime.tv_usec = 0;
267 #ifdef HAVE_GETTIMEOFDAY
268 if(gettimeofday(&newtime, NULL) == -1)
270 ilog(L_MAIN, "Clock Failure (%d)", errno);
271 sendto_realops_snomask(SNO_GENERAL, L_NETWIDE,
272 "Clock Failure (%d), TS can be corrupted", errno);
274 restart("Clock Failure");
276 #else
277 newtime.tv_sec = time(NULL);
279 #endif
280 if(newtime.tv_sec < CurrentTime)
281 set_back_events(CurrentTime - newtime.tv_sec);
283 SystemTime.tv_sec = newtime.tv_sec;
284 SystemTime.tv_usec = newtime.tv_usec;
287 static void
288 check_rehash(void *unused)
291 * Check to see whether we have to rehash the configuration ..
293 if(dorehash)
295 rehash(1);
296 dorehash = 0;
299 if(dorehashbans)
301 rehash_bans(1);
302 dorehashbans = 0;
305 if(doremotd)
307 sendto_realops_snomask(SNO_GENERAL, L_NETWIDE,
308 "Got signal SIGUSR1, reloading ircd motd file");
309 free_cachefile(user_motd);
310 user_motd = cache_file(MPATH, "ircd.motd", 0);
311 doremotd = 0;
315 void
316 seven_io_loop(void)
318 time_t delay;
320 while (ServerRunning)
322 /* Run pending events, then get the number of seconds to the next
323 * event
326 delay = eventNextTime();
327 if(delay <= CurrentTime)
328 eventRun();
331 comm_select(250);
336 * initalialize_global_set_options
338 * inputs - none
339 * output - none
340 * side effects - This sets all global set options needed
342 static void
343 initialize_global_set_options(void)
345 memset(&GlobalSetOptions, 0, sizeof(GlobalSetOptions));
346 /* memset( &ConfigFileEntry, 0, sizeof(ConfigFileEntry)); */
348 GlobalSetOptions.maxclients = MAX_CLIENTS;
349 GlobalSetOptions.autoconn = 1;
351 GlobalSetOptions.spam_time = MIN_JOIN_LEAVE_TIME;
352 GlobalSetOptions.spam_num = MAX_JOIN_LEAVE_COUNT;
354 if(ConfigFileEntry.default_floodcount)
355 GlobalSetOptions.floodcount = ConfigFileEntry.default_floodcount;
356 else
357 GlobalSetOptions.floodcount = 10;
359 split_servers = ConfigChannel.default_split_server_count;
360 split_users = ConfigChannel.default_split_user_count;
362 if(split_users && split_servers
363 && (ConfigChannel.no_create_on_split || ConfigChannel.no_join_on_split))
365 splitmode = 1;
366 splitchecking = 1;
369 GlobalSetOptions.ident_timeout = IDENT_TIMEOUT;
371 strlcpy(GlobalSetOptions.operstring,
372 ConfigFileEntry.default_operstring,
373 sizeof(GlobalSetOptions.operstring));
374 strlcpy(GlobalSetOptions.adminstring,
375 ConfigFileEntry.default_adminstring,
376 sizeof(GlobalSetOptions.adminstring));
378 /* memset( &ConfigChannel, 0, sizeof(ConfigChannel)); */
380 /* End of global set options */
385 * initialize_server_capabs
387 * inputs - none
388 * output - none
390 static void
391 initialize_server_capabs(void)
393 default_server_capabs &= ~CAP_ZIP;
398 * write_pidfile
400 * inputs - filename+path of pid file
401 * output - none
402 * side effects - write the pid of the ircd to filename
404 static void
405 write_pidfile(const char *filename)
407 FILE *fb;
408 char buff[32];
409 if((fb = fopen(filename, "w")))
411 unsigned int pid = (unsigned int) getpid();
413 ircsnprintf(buff, sizeof(buff), "%u\n", pid);
414 if((fputs(buff, fb) == -1))
416 ilog(L_MAIN, "Error writing %u to pid file %s (%s)",
417 pid, filename, strerror(errno));
419 fclose(fb);
420 return;
422 else
424 ilog(L_MAIN, "Error opening pid file %s", filename);
429 * check_pidfile
431 * inputs - filename+path of pid file
432 * output - none
433 * side effects - reads pid from pidfile and checks if ircd is in process
434 * list. if it is, gracefully exits
435 * -kre
437 static void
438 check_pidfile(const char *filename)
440 FILE *fb;
441 char buff[32];
442 pid_t pidfromfile;
444 /* Don't do logging here, since we don't have log() initialised */
445 if((fb = fopen(filename, "r")))
447 if(fgets(buff, 20, fb) != NULL)
449 pidfromfile = atoi(buff);
450 if(!kill(pidfromfile, 0))
452 printf("ircd: daemon is already running\n");
453 exit(-1);
456 fclose(fb);
461 * setup_corefile
463 * inputs - nothing
464 * output - nothing
465 * side effects - setups corefile to system limits.
466 * -kre
468 static void
469 setup_corefile(void)
471 #ifdef HAVE_SYS_RESOURCE_H
472 struct rlimit rlim; /* resource limits */
474 /* Set corefilesize to maximum */
475 if(!getrlimit(RLIMIT_CORE, &rlim))
477 rlim.rlim_cur = rlim.rlim_max;
478 setrlimit(RLIMIT_CORE, &rlim);
480 #endif
484 * main
486 * Initializes the IRCd.
488 * Inputs - number of commandline args, args themselves
489 * Outputs - none
490 * Side Effects - this is where the ircd gets going right now
493 main(int argc, char *argv[])
495 int fd;
497 /* Check to see if the user is running us as root, which is a nono */
498 if(geteuid() == 0)
500 fprintf(stderr, "Don't run ircd as root!!!\n");
501 return -1;
505 * save server boot time right away, so getrusage works correctly
507 set_time();
509 * Setup corefile size immediately after boot -kre
511 setup_corefile();
514 * set initialVMTop before we allocate any memory
516 initialVMTop = get_vm_top();
518 ServerRunning = 0;
519 /* It ain't random, but it ought to be a little harder to guess */
520 srand(SystemTime.tv_sec ^ (SystemTime.tv_usec | (getpid() << 20)));
521 memset(&me, 0, sizeof(me));
522 memset(&meLocalUser, 0, sizeof(meLocalUser));
523 me.localClient = &meLocalUser;
525 /* Make sure all lists are zeroed */
526 memset(&unknown_list, 0, sizeof(unknown_list));
527 memset(&lclient_list, 0, sizeof(lclient_list));
528 memset(&serv_list, 0, sizeof(serv_list));
529 memset(&global_serv_list, 0, sizeof(global_serv_list));
530 memset(&local_oper_list, 0, sizeof(local_oper_list));
531 memset(&oper_list, 0, sizeof(oper_list));
533 dlinkAddTail(&me, &me.node, &global_client_list);
535 memset((void *) &Count, 0, sizeof(Count));
536 memset((void *) &ServerInfo, 0, sizeof(ServerInfo));
537 memset((void *) &AdminInfo, 0, sizeof(AdminInfo));
539 /* Initialise the channel capability usage counts... */
540 init_chcap_usage_counts();
542 ConfigFileEntry.dpath = DPATH;
543 ConfigFileEntry.configfile = CPATH; /* Server configuration file */
544 ConfigFileEntry.klinefile = KPATH; /* Server kline file */
545 ConfigFileEntry.dlinefile = DLPATH; /* dline file */
546 ConfigFileEntry.xlinefile = XPATH;
547 ConfigFileEntry.resvfile = RESVPATH;
548 ConfigFileEntry.connect_timeout = 30; /* Default to 30 */
549 myargv = argv;
550 umask(077); /* better safe than sorry --SRB */
552 parseargs(&argc, &argv, myopts);
554 if(printVersion)
556 printf("ircd: version %s\n", ircd_version);
557 exit(EXIT_SUCCESS);
560 if(chdir(ConfigFileEntry.dpath))
562 fprintf(stderr, "Unable to chdir to %s: %s\n", ConfigFileEntry.dpath, strerror(errno));
563 exit(EXIT_FAILURE);
566 setup_signals();
568 #ifdef __CYGWIN__
569 server_state_foreground = 1;
570 #endif
572 if (testing_conf)
573 server_state_foreground = 1;
575 /* Make sure fd 0, 1 and 2 are in use -- jilles */
578 fd = open("/dev/null", O_RDWR);
579 } while (fd < 2 && fd != -1);
580 if (fd > 2)
581 close(fd);
582 else if (fd == -1)
583 exit(1);
585 /* Check if there is pidfile and daemon already running */
586 if(!testing_conf)
588 check_pidfile(pidFileName);
590 if(!server_state_foreground)
591 make_daemon();
592 inotice("starting %s ...", ircd_version);
595 /* Init the event subsystem */
596 libseven_init(ircd_log_cb, restart, ircd_die_cb);
597 init_sys();
599 fdlist_init();
600 if(!server_state_foreground)
602 comm_close_all();
605 init_main_logfile();
606 init_patricia();
607 newconf_init();
608 init_s_conf();
609 init_s_newconf();
610 init_hash();
611 clear_scache_hash_table(); /* server cache name table */
612 init_host_hash();
613 clear_hash_parse();
614 init_client();
615 initUser();
616 init_hook();
617 init_channels();
618 initclass();
619 initwhowas();
620 init_stats();
621 init_reject();
622 init_cache();
623 init_monitor();
624 init_isupport();
625 load_all_modules(1);
626 #ifndef STATIC_MODULES
627 load_core_modules(1);
628 #endif
629 init_auth(); /* Initialise the auth code */
630 init_resolver(); /* Needs to be setup before the io loop */
632 if (testing_conf)
633 fprintf(stderr, "\nBeginning config test\n");
634 read_conf_files(YES); /* cold start init conf files */
635 rehash_bans(0);
636 #ifndef STATIC_MODULES
638 mod_add_path(MODULE_DIR);
639 mod_add_path(MODULE_DIR "/autoload");
640 #endif
642 initialize_server_capabs(); /* Set up default_server_capabs */
643 initialize_global_set_options();
645 if(ServerInfo.name == NULL)
647 ierror("no server name specified in serverinfo block.");
648 return -1;
650 strlcpy(me.name, ServerInfo.name, sizeof(me.name));
652 if(ServerInfo.sid[0] == '\0')
654 ierror("no server sid specified in serverinfo block.");
655 return -2;
657 strcpy(me.id, ServerInfo.sid);
658 init_uid();
660 /* serverinfo{} description must exist. If not, error out. */
661 if(ServerInfo.description == NULL)
663 ierror("no server description specified in serverinfo block.");
664 return -3;
666 strlcpy(me.info, ServerInfo.description, sizeof(me.info));
668 if (testing_conf)
670 fprintf(stderr, "\nConfig testing complete.\n");
671 fflush(stderr);
672 return 0; /* Why? We want the launcher to exit out. */
675 me.from = &me;
676 me.servptr = &me;
677 SetMe(&me);
678 make_server(&me);
679 me.serv->up = me.name;
680 startup_time = CurrentTime;
681 add_to_client_hash(me.name, &me);
682 add_to_id_hash(me.id, &me);
684 dlinkAddAlloc(&me, &global_serv_list);
686 construct_umodebuf();
688 check_class();
689 write_pidfile(pidFileName);
690 load_help();
691 open_logfiles();
693 ilog(L_MAIN, "Server Ready");
695 /* We want try_connections to be called as soon as possible now! -- adrian */
696 /* No, 'cause after a restart it would cause all sorts of nick collides */
697 /* um. by waiting even longer, that just means we have even *more*
698 * nick collisions. what a stupid idea. set an event for the IO loop --fl
700 eventAddIsh("try_connections", try_connections, NULL, STARTUP_CONNECTIONS_TIME);
701 eventAddOnce("try_connections_startup", try_connections, NULL, 0);
703 eventAddIsh("collect_zipstats", collect_zipstats, NULL, ZIPSTATS_TIME);
705 /* Setup the timeout check. I'll shift it later :) -- adrian */
706 eventAddIsh("comm_checktimeouts", comm_checktimeouts, NULL, 1);
708 eventAdd("check_rehash", check_rehash, NULL, 1);
710 if(ConfigServerHide.links_delay > 0)
711 eventAdd("cache_links", cache_links, NULL,
712 ConfigServerHide.links_delay);
713 else
714 ConfigServerHide.links_disabled = 1;
716 if(splitmode)
717 eventAdd("check_splitmode", check_splitmode, NULL, 2);
719 ServerRunning = 1;
721 print_startup(getpid());
723 seven_io_loop();
725 return 0;