Import from http://svn.freenode.net/ircd-seven/private/beu/seven (r196).
[seven-1.x.git] / src / ircd.c
blob26d43da73e8ba0cfd7266bada81ff948bf3dfe75
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
24 * $Id: ircd.c 181 2006-12-18 02:56:07Z beu $
27 #include "stdinc.h"
28 #include "setup.h"
29 #include "config.h"
31 #include "tools.h"
32 #include "ircd.h"
33 #include "channel.h"
34 #include "class.h"
35 #include "client.h"
36 #include "common.h"
37 #include "event.h"
38 #include "hash.h"
39 #include "irc_string.h"
40 #include "ircd_signal.h"
41 #include "sprintf_irc.h"
42 #include "msg.h" /* msgtab */
43 #include "hostmask.h"
44 #include "numeric.h"
45 #include "parse.h"
46 #include "res.h"
47 #include "restart.h"
48 #include "s_auth.h"
49 #include "commio.h"
50 #include "s_conf.h"
51 #include "s_log.h"
52 #include "s_serv.h" /* try_connections */
53 #include "s_user.h"
54 #include "s_stats.h"
55 #include "scache.h"
56 #include "send.h"
57 #include "supported.h"
58 #include "whowas.h"
59 #include "modules.h"
60 #include "memory.h"
61 #include "hook.h"
62 #include "ircd_getopt.h"
63 #include "balloc.h"
64 #include "newconf.h"
65 #include "patricia.h"
66 #include "reject.h"
67 #include "s_conf.h"
68 #include "s_newconf.h"
69 #include "cache.h"
70 #include "monitor.h"
71 #include "libseven.h"
72 #include "patchlevel.h"
73 #include "serno.h"
76 * Try and find the correct name to use with getrlimit() for setting the max.
77 * number of files allowed to be open by this process.
79 int _seven_data_version = SEVEN_DV;
81 extern int ServerRunning, initialVMTop;
82 extern struct LocalUser meLocalUser;
83 extern char **myargv;
86 * get_vm_top - get the operating systems notion of the resident set size
88 static unsigned long
89 get_vm_top(void)
92 * NOTE: sbrk is not part of the ANSI C library or the POSIX.1 standard
93 * however it seems that everyone defines it. Calling sbrk with a 0
94 * argument will return a pointer to the top of the process virtual
95 * memory without changing the process size, so this call should be
96 * reasonably safe (sbrk returns the new value for the top of memory).
97 * This code relies on the notion that the address returned will be an
98 * offset from 0 (NULL), so the result of sbrk is cast to a size_t and
99 * returned. We really shouldn't be using it here but...
101 void *vptr = sbrk(0);
102 return (unsigned long) vptr;
106 * get_maxrss - get the operating systems notion of the resident set size
108 unsigned long
109 get_maxrss(void)
111 return get_vm_top() - initialVMTop;
115 * print_startup - print startup information
117 static void
118 print_startup(int pid)
120 inotice("now running in %s mode from %s as pid %d ...",
121 !server_state_foreground ? "background" : "foreground",
122 ConfigFileEntry.dpath, pid);
124 /* let the parent process know the initialization was successful
125 * -- jilles */
126 if (!server_state_foreground)
127 write(0, ".", 1);
128 fclose(stdin);
129 fclose(stdout);
130 fclose(stderr);
131 open("/dev/null", O_RDWR);
132 dup2(0, 1);
133 dup2(0, 2);
136 static void
137 ircd_log_cb(const char *str)
139 ilog(L_MAIN, "%s", str);
143 * Why EXIT_FAILURE here?
144 * Because if ircd_die_cb() is called it's because of a fatal
145 * error inside libseven, and we don't know how to handle the
146 * exception, so it is logical to return a FAILURE exit code here.
147 * --nenolod
149 static void
150 ircd_die_cb(const char *str)
152 /* Try to get the message out to currently logged in operators. */
153 sendto_realops_snomask(SNO_GENERAL, L_NETWIDE, "Server panic! %s", str);
154 inotice("server panic: %s", str);
156 unlink(pidFileName);
157 exit(EXIT_FAILURE);
161 * init_sys
163 * inputs - boot_daemon flag
164 * output - none
165 * side effects - if boot_daemon flag is not set, don't daemonize
167 static void
168 init_sys(void)
170 #if defined(RLIMIT_FD_MAX) && defined(HAVE_SYS_RLIMIT_H)
171 struct rlimit limit;
173 if(!getrlimit(RLIMIT_FD_MAX, &limit))
176 if(limit.rlim_max < MAXCONNECTIONS)
178 fprintf(stderr, "ircd fd table too big\n");
179 fprintf(stderr, "Hard Limit: %ld IRC max: %d\n",
180 (long) limit.rlim_max, MAXCONNECTIONS);
181 fprintf(stderr, "Fix MAXCONNECTIONS\n");
182 exit(-1);
185 limit.rlim_cur = limit.rlim_max; /* make soft limit the max */
186 if(setrlimit(RLIMIT_FD_MAX, &limit) == -1)
188 fprintf(stderr, "error setting max fd's to %ld\n", (long) limit.rlim_cur);
189 exit(EXIT_FAILURE);
192 #endif /* RLIMIT_FD_MAX */
195 static int
196 make_daemon(void)
198 int pid;
199 int pip[2];
200 char c;
202 if (pipe(pip) < 0)
204 perror("pipe");
205 exit(EXIT_FAILURE);
207 dup2(pip[1], 0);
208 close(pip[1]);
209 if((pid = fork()) < 0)
211 perror("fork");
212 exit(EXIT_FAILURE);
214 else if(pid > 0)
216 close(0);
217 /* Wait for initialization to finish, successfully or
218 * unsuccessfully. Until this point the child may still
219 * write to stdout/stderr.
220 * -- jilles */
221 if (read(pip[0], &c, 1) > 0)
222 exit(EXIT_SUCCESS);
223 else
224 exit(EXIT_FAILURE);
227 close(pip[0]);
228 setsid();
229 /* fclose(stdin);
230 fclose(stdout);
231 fclose(stderr); */
233 return 0;
236 static int printVersion = 0;
238 struct lgetopt myopts[] = {
239 {"dlinefile", &ConfigFileEntry.dlinefile,
240 STRING, "File to use for dlines.conf"},
241 {"configfile", &ConfigFileEntry.configfile,
242 STRING, "File to use for ircd.conf"},
243 {"klinefile", &ConfigFileEntry.klinefile,
244 STRING, "File to use for klines.conf"},
245 {"xlinefile", &ConfigFileEntry.xlinefile,
246 STRING, "File to use for xlines.conf"},
247 {"resvfile", &ConfigFileEntry.resvfile,
248 STRING, "File to use for resv.conf"},
249 {"logfile", &logFileName,
250 STRING, "File to use for ircd.log"},
251 {"pidfile", &pidFileName,
252 STRING, "File to use for process ID"},
253 {"foreground", &server_state_foreground,
254 YESNO, "Run in foreground (don't detach)"},
255 {"version", &printVersion,
256 YESNO, "Print version and exit"},
257 {"conftest", &testing_conf,
258 YESNO, "Test the configuration files and exit"},
259 {"help", NULL, USAGE, "Print this text"},
260 {NULL, NULL, STRING, NULL},
263 void
264 set_time(void)
266 struct timeval newtime;
267 newtime.tv_sec = 0;
268 newtime.tv_usec = 0;
269 #ifdef HAVE_GETTIMEOFDAY
270 if(gettimeofday(&newtime, NULL) == -1)
272 ilog(L_MAIN, "Clock Failure (%d)", errno);
273 sendto_realops_snomask(SNO_GENERAL, L_NETWIDE,
274 "Clock Failure (%d), TS can be corrupted", errno);
276 restart("Clock Failure");
278 #else
279 newtime.tv_sec = time(NULL);
281 #endif
282 if(newtime.tv_sec < CurrentTime)
283 set_back_events(CurrentTime - newtime.tv_sec);
285 SystemTime.tv_sec = newtime.tv_sec;
286 SystemTime.tv_usec = newtime.tv_usec;
289 static void
290 check_rehash(void *unused)
293 * Check to see whether we have to rehash the configuration ..
295 if(dorehash)
297 rehash(1);
298 dorehash = 0;
301 if(dorehashbans)
303 rehash_bans(1);
304 dorehashbans = 0;
307 if(doremotd)
309 sendto_realops_snomask(SNO_GENERAL, L_NETWIDE,
310 "Got signal SIGUSR1, reloading ircd motd file");
311 free_cachefile(user_motd);
312 user_motd = cache_file(MPATH, "ircd.motd", 0);
313 doremotd = 0;
317 void
318 seven_io_loop(void)
320 time_t delay;
322 while (ServerRunning)
324 /* Run pending events, then get the number of seconds to the next
325 * event
328 delay = eventNextTime();
329 if(delay <= CurrentTime)
330 eventRun();
333 comm_select(250);
338 * initalialize_global_set_options
340 * inputs - none
341 * output - none
342 * side effects - This sets all global set options needed
344 static void
345 initialize_global_set_options(void)
347 memset(&GlobalSetOptions, 0, sizeof(GlobalSetOptions));
348 /* memset( &ConfigFileEntry, 0, sizeof(ConfigFileEntry)); */
350 GlobalSetOptions.maxclients = MAX_CLIENTS;
351 GlobalSetOptions.autoconn = 1;
353 GlobalSetOptions.spam_time = MIN_JOIN_LEAVE_TIME;
354 GlobalSetOptions.spam_num = MAX_JOIN_LEAVE_COUNT;
356 if(ConfigFileEntry.default_floodcount)
357 GlobalSetOptions.floodcount = ConfigFileEntry.default_floodcount;
358 else
359 GlobalSetOptions.floodcount = 10;
361 split_servers = ConfigChannel.default_split_server_count;
362 split_users = ConfigChannel.default_split_user_count;
364 if(split_users && split_servers
365 && (ConfigChannel.no_create_on_split || ConfigChannel.no_join_on_split))
367 splitmode = 1;
368 splitchecking = 1;
371 GlobalSetOptions.ident_timeout = IDENT_TIMEOUT;
373 strlcpy(GlobalSetOptions.operstring,
374 ConfigFileEntry.default_operstring,
375 sizeof(GlobalSetOptions.operstring));
376 strlcpy(GlobalSetOptions.adminstring,
377 ConfigFileEntry.default_adminstring,
378 sizeof(GlobalSetOptions.adminstring));
380 /* memset( &ConfigChannel, 0, sizeof(ConfigChannel)); */
382 /* End of global set options */
387 * initialize_server_capabs
389 * inputs - none
390 * output - none
392 static void
393 initialize_server_capabs(void)
395 default_server_capabs &= ~CAP_ZIP;
400 * write_pidfile
402 * inputs - filename+path of pid file
403 * output - none
404 * side effects - write the pid of the ircd to filename
406 static void
407 write_pidfile(const char *filename)
409 FILE *fb;
410 char buff[32];
411 if((fb = fopen(filename, "w")))
413 unsigned int pid = (unsigned int) getpid();
415 ircsnprintf(buff, sizeof(buff), "%u\n", pid);
416 if((fputs(buff, fb) == -1))
418 ilog(L_MAIN, "Error writing %u to pid file %s (%s)",
419 pid, filename, strerror(errno));
421 fclose(fb);
422 return;
424 else
426 ilog(L_MAIN, "Error opening pid file %s", filename);
431 * check_pidfile
433 * inputs - filename+path of pid file
434 * output - none
435 * side effects - reads pid from pidfile and checks if ircd is in process
436 * list. if it is, gracefully exits
437 * -kre
439 static void
440 check_pidfile(const char *filename)
442 FILE *fb;
443 char buff[32];
444 pid_t pidfromfile;
446 /* Don't do logging here, since we don't have log() initialised */
447 if((fb = fopen(filename, "r")))
449 if(fgets(buff, 20, fb) != NULL)
451 pidfromfile = atoi(buff);
452 if(!kill(pidfromfile, 0))
454 printf("ircd: daemon is already running\n");
455 exit(-1);
458 fclose(fb);
463 * setup_corefile
465 * inputs - nothing
466 * output - nothing
467 * side effects - setups corefile to system limits.
468 * -kre
470 static void
471 setup_corefile(void)
473 #ifdef HAVE_SYS_RESOURCE_H
474 struct rlimit rlim; /* resource limits */
476 /* Set corefilesize to maximum */
477 if(!getrlimit(RLIMIT_CORE, &rlim))
479 rlim.rlim_cur = rlim.rlim_max;
480 setrlimit(RLIMIT_CORE, &rlim);
482 #endif
486 * main
488 * Initializes the IRCd.
490 * Inputs - number of commandline args, args themselves
491 * Outputs - none
492 * Side Effects - this is where the ircd gets going right now
495 main(int argc, char *argv[])
497 int fd;
499 /* Check to see if the user is running us as root, which is a nono */
500 if(geteuid() == 0)
502 fprintf(stderr, "Don't run ircd as root!!!\n");
503 return -1;
507 * save server boot time right away, so getrusage works correctly
509 set_time();
511 * Setup corefile size immediately after boot -kre
513 setup_corefile();
516 * set initialVMTop before we allocate any memory
518 initialVMTop = get_vm_top();
520 ServerRunning = 0;
521 /* It ain't random, but it ought to be a little harder to guess */
522 srand(SystemTime.tv_sec ^ (SystemTime.tv_usec | (getpid() << 20)));
523 memset(&me, 0, sizeof(me));
524 memset(&meLocalUser, 0, sizeof(meLocalUser));
525 me.localClient = &meLocalUser;
527 /* Make sure all lists are zeroed */
528 memset(&unknown_list, 0, sizeof(unknown_list));
529 memset(&lclient_list, 0, sizeof(lclient_list));
530 memset(&serv_list, 0, sizeof(serv_list));
531 memset(&global_serv_list, 0, sizeof(global_serv_list));
532 memset(&local_oper_list, 0, sizeof(local_oper_list));
533 memset(&oper_list, 0, sizeof(oper_list));
535 dlinkAddTail(&me, &me.node, &global_client_list);
537 memset((void *) &Count, 0, sizeof(Count));
538 memset((void *) &ServerInfo, 0, sizeof(ServerInfo));
539 memset((void *) &AdminInfo, 0, sizeof(AdminInfo));
541 /* Initialise the channel capability usage counts... */
542 init_chcap_usage_counts();
544 ConfigFileEntry.dpath = DPATH;
545 ConfigFileEntry.configfile = CPATH; /* Server configuration file */
546 ConfigFileEntry.klinefile = KPATH; /* Server kline file */
547 ConfigFileEntry.dlinefile = DLPATH; /* dline file */
548 ConfigFileEntry.xlinefile = XPATH;
549 ConfigFileEntry.resvfile = RESVPATH;
550 ConfigFileEntry.connect_timeout = 30; /* Default to 30 */
551 myargv = argv;
552 umask(077); /* better safe than sorry --SRB */
554 parseargs(&argc, &argv, myopts);
556 if(printVersion)
558 printf("ircd: version %s\n", ircd_version);
559 exit(EXIT_SUCCESS);
562 if(chdir(ConfigFileEntry.dpath))
564 fprintf(stderr, "Unable to chdir to %s: %s\n", ConfigFileEntry.dpath, strerror(errno));
565 exit(EXIT_FAILURE);
568 setup_signals();
570 #ifdef __CYGWIN__
571 server_state_foreground = 1;
572 #endif
574 if (testing_conf)
575 server_state_foreground = 1;
577 /* Make sure fd 0, 1 and 2 are in use -- jilles */
580 fd = open("/dev/null", O_RDWR);
581 } while (fd < 2 && fd != -1);
582 if (fd > 2)
583 close(fd);
584 else if (fd == -1)
585 exit(1);
587 /* Check if there is pidfile and daemon already running */
588 if(!testing_conf)
590 check_pidfile(pidFileName);
592 if(!server_state_foreground)
593 make_daemon();
594 inotice("starting %s ...", ircd_version);
597 /* Init the event subsystem */
598 libseven_init(ircd_log_cb, restart, ircd_die_cb);
599 init_sys();
601 fdlist_init();
602 if(!server_state_foreground)
604 comm_close_all();
607 init_main_logfile();
608 init_patricia();
609 newconf_init();
610 init_s_conf();
611 init_s_newconf();
612 init_hash();
613 clear_scache_hash_table(); /* server cache name table */
614 init_host_hash();
615 clear_hash_parse();
616 init_client();
617 initUser();
618 init_hook();
619 init_channels();
620 initclass();
621 initwhowas();
622 init_stats();
623 init_reject();
624 init_cache();
625 init_monitor();
626 init_isupport();
627 load_all_modules(1);
628 #ifndef STATIC_MODULES
629 load_core_modules(1);
630 #endif
631 init_auth(); /* Initialise the auth code */
632 init_resolver(); /* Needs to be setup before the io loop */
634 if (testing_conf)
635 fprintf(stderr, "\nBeginning config test\n");
636 read_conf_files(YES); /* cold start init conf files */
637 rehash_bans(0);
638 #ifndef STATIC_MODULES
640 mod_add_path(MODULE_DIR);
641 mod_add_path(MODULE_DIR "/autoload");
642 #endif
644 initialize_server_capabs(); /* Set up default_server_capabs */
645 initialize_global_set_options();
647 if(ServerInfo.name == NULL)
649 ierror("no server name specified in serverinfo block.");
650 return -1;
652 strlcpy(me.name, ServerInfo.name, sizeof(me.name));
654 if(ServerInfo.sid[0] == '\0')
656 ierror("no server sid specified in serverinfo block.");
657 return -2;
659 strcpy(me.id, ServerInfo.sid);
660 init_uid();
662 /* serverinfo{} description must exist. If not, error out. */
663 if(ServerInfo.description == NULL)
665 ierror("no server description specified in serverinfo block.");
666 return -3;
668 strlcpy(me.info, ServerInfo.description, sizeof(me.info));
670 if (testing_conf)
672 fprintf(stderr, "\nConfig testing complete.\n");
673 fflush(stderr);
674 return 0; /* Why? We want the launcher to exit out. */
677 me.from = &me;
678 me.servptr = &me;
679 SetMe(&me);
680 make_server(&me);
681 me.serv->up = me.name;
682 startup_time = CurrentTime;
683 add_to_client_hash(me.name, &me);
684 add_to_id_hash(me.id, &me);
686 dlinkAddAlloc(&me, &global_serv_list);
688 construct_umodebuf();
690 check_class();
691 write_pidfile(pidFileName);
692 load_help();
693 open_logfiles();
695 ilog(L_MAIN, "Server Ready");
697 /* We want try_connections to be called as soon as possible now! -- adrian */
698 /* No, 'cause after a restart it would cause all sorts of nick collides */
699 /* um. by waiting even longer, that just means we have even *more*
700 * nick collisions. what a stupid idea. set an event for the IO loop --fl
702 eventAddIsh("try_connections", try_connections, NULL, STARTUP_CONNECTIONS_TIME);
703 eventAddOnce("try_connections_startup", try_connections, NULL, 0);
705 eventAddIsh("collect_zipstats", collect_zipstats, NULL, ZIPSTATS_TIME);
707 /* Setup the timeout check. I'll shift it later :) -- adrian */
708 eventAddIsh("comm_checktimeouts", comm_checktimeouts, NULL, 1);
710 eventAdd("check_rehash", check_rehash, NULL, 1);
712 if(ConfigServerHide.links_delay > 0)
713 eventAdd("cache_links", cache_links, NULL,
714 ConfigServerHide.links_delay);
715 else
716 ConfigServerHide.links_disabled = 1;
718 if(splitmode)
719 eventAdd("check_splitmode", check_splitmode, NULL, 2);
721 ServerRunning = 1;
723 print_startup(getpid());
725 seven_io_loop();
727 return 0;