]> jfr.im git - irc/rqf/shadowircd.git/blob - src/ircd.c
Automated merge with ssh://hg.atheme.org//hg/charybdis
[irc/rqf/shadowircd.git] / src / ircd.c
1 /*
2 * ircd-ratbox: A slightly useful ircd.
3 * ircd.c: Starts up and runs the ircd.
4 *
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
8 *
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.
13 *
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.
18 *
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
23 *
24 * $Id: ircd.c 3380 2007-04-03 22:25:11Z jilles $
25 */
26
27 #include "stdinc.h"
28 #include "setup.h"
29 #include "config.h"
30
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 "s_gline.h"
43 #include "msg.h" /* msgtab */
44 #include "hostmask.h"
45 #include "numeric.h"
46 #include "parse.h"
47 #include "res.h"
48 #include "restart.h"
49 #include "s_auth.h"
50 #include "commio.h"
51 #include "s_conf.h"
52 #include "s_log.h"
53 #include "s_serv.h" /* try_connections */
54 #include "s_user.h"
55 #include "s_stats.h"
56 #include "scache.h"
57 #include "send.h"
58 #include "supported.h"
59 #include "whowas.h"
60 #include "modules.h"
61 #include "memory.h"
62 #include "hook.h"
63 #include "ircd_getopt.h"
64 #include "balloc.h"
65 #include "newconf.h"
66 #include "patricia.h"
67 #include "reject.h"
68 #include "s_conf.h"
69 #include "s_newconf.h"
70 #include "cache.h"
71 #include "monitor.h"
72 #include "libcharybdis.h"
73 #include "patchlevel.h"
74 #include "serno.h"
75
76 /*
77 * Try and find the correct name to use with getrlimit() for setting the max.
78 * number of files allowed to be open by this process.
79 */
80 int _charybdis_data_version = CHARYBDIS_DV;
81
82 extern int ServerRunning;
83 extern struct LocalUser meLocalUser;
84 extern char **myargv;
85
86 /*
87 * print_startup - print startup information
88 */
89 static void
90 print_startup(int pid)
91 {
92 inotice("now running in %s mode from %s as pid %d ...",
93 !server_state_foreground ? "background" : "foreground",
94 ConfigFileEntry.dpath, pid);
95
96 /* let the parent process know the initialization was successful
97 * -- jilles */
98 if (!server_state_foreground)
99 write(0, ".", 1);
100 fclose(stdin);
101 fclose(stdout);
102 fclose(stderr);
103 open("/dev/null", O_RDWR);
104 dup2(0, 1);
105 dup2(0, 2);
106 }
107
108 static void
109 ircd_log_cb(const char *str)
110 {
111 ilog(L_MAIN, "%s", str);
112 }
113
114 /*
115 * Why EXIT_FAILURE here?
116 * Because if ircd_die_cb() is called it's because of a fatal
117 * error inside libcharybdis, and we don't know how to handle the
118 * exception, so it is logical to return a FAILURE exit code here.
119 * --nenolod
120 */
121 static void
122 ircd_die_cb(const char *str)
123 {
124 /* Try to get the message out to currently logged in operators. */
125 sendto_realops_snomask(SNO_GENERAL, L_NETWIDE, "Server panic! %s", str);
126 inotice("server panic: %s", str);
127
128 unlink(pidFileName);
129 exit(EXIT_FAILURE);
130 }
131
132 /*
133 * init_sys
134 *
135 * inputs - boot_daemon flag
136 * output - none
137 * side effects - if boot_daemon flag is not set, don't daemonize
138 */
139 static void
140 init_sys(void)
141 {
142 #if defined(RLIMIT_NOFILE) && defined(HAVE_SYS_RESOURCE_H)
143 struct rlimit limit;
144
145 if(!getrlimit(RLIMIT_NOFILE, &limit))
146 {
147 limit.rlim_cur = limit.rlim_max; /* make soft limit the max */
148 if(setrlimit(RLIMIT_NOFILE, &limit) == -1)
149 {
150 fprintf(stderr, "error setting max fd's to %ld\n", (long) limit.rlim_cur);
151 exit(EXIT_FAILURE);
152 }
153 }
154 #endif /* RLIMIT_NOFILE */
155 }
156
157 static int
158 make_daemon(void)
159 {
160 int pid;
161 int pip[2];
162 char c;
163
164 if (pipe(pip) < 0)
165 {
166 perror("pipe");
167 exit(EXIT_FAILURE);
168 }
169 dup2(pip[1], 0);
170 close(pip[1]);
171 if((pid = fork()) < 0)
172 {
173 perror("fork");
174 exit(EXIT_FAILURE);
175 }
176 else if(pid > 0)
177 {
178 close(0);
179 /* Wait for initialization to finish, successfully or
180 * unsuccessfully. Until this point the child may still
181 * write to stdout/stderr.
182 * -- jilles */
183 if (read(pip[0], &c, 1) > 0)
184 exit(EXIT_SUCCESS);
185 else
186 exit(EXIT_FAILURE);
187 }
188
189 close(pip[0]);
190 setsid();
191 /* fclose(stdin);
192 fclose(stdout);
193 fclose(stderr); */
194
195 return 0;
196 }
197
198 static int printVersion = 0;
199
200 struct lgetopt myopts[] = {
201 {"dlinefile", &ConfigFileEntry.dlinefile,
202 STRING, "File to use for dlines.conf"},
203 {"configfile", &ConfigFileEntry.configfile,
204 STRING, "File to use for ircd.conf"},
205 {"klinefile", &ConfigFileEntry.klinefile,
206 STRING, "File to use for kline.conf"},
207 {"xlinefile", &ConfigFileEntry.xlinefile,
208 STRING, "File to use for xline.conf"},
209 {"resvfile", &ConfigFileEntry.resvfile,
210 STRING, "File to use for resv.conf"},
211 {"logfile", &logFileName,
212 STRING, "File to use for ircd.log"},
213 {"pidfile", &pidFileName,
214 STRING, "File to use for process ID"},
215 {"foreground", &server_state_foreground,
216 YESNO, "Run in foreground (don't detach)"},
217 {"version", &printVersion,
218 YESNO, "Print version and exit"},
219 {"conftest", &testing_conf,
220 YESNO, "Test the configuration files and exit"},
221 {"help", NULL, USAGE, "Print this text"},
222 {NULL, NULL, STRING, NULL},
223 };
224
225 void
226 set_time(void)
227 {
228 struct timeval newtime;
229 newtime.tv_sec = 0;
230 newtime.tv_usec = 0;
231 #ifdef HAVE_GETTIMEOFDAY
232 if(gettimeofday(&newtime, NULL) == -1)
233 {
234 ilog(L_MAIN, "Clock Failure (%d)", errno);
235 sendto_realops_snomask(SNO_GENERAL, L_ALL,
236 "Clock Failure (%d), TS can be corrupted", errno);
237
238 restart("Clock Failure");
239 }
240 #else
241 newtime.tv_sec = time(NULL);
242
243 #endif
244 if(newtime.tv_sec < CurrentTime)
245 set_back_events(CurrentTime - newtime.tv_sec);
246
247 SystemTime.tv_sec = newtime.tv_sec;
248 SystemTime.tv_usec = newtime.tv_usec;
249 }
250
251 static void
252 check_rehash(void *unused)
253 {
254 /*
255 * Check to see whether we have to rehash the configuration ..
256 */
257 if(dorehash)
258 {
259 rehash(1);
260 dorehash = 0;
261 }
262
263 if(dorehashbans)
264 {
265 rehash_bans(1);
266 dorehashbans = 0;
267 }
268
269 if(doremotd)
270 {
271 sendto_realops_snomask(SNO_GENERAL, L_ALL,
272 "Got signal SIGUSR1, reloading ircd motd file");
273 free_cachefile(user_motd);
274 user_motd = cache_file(MPATH, "ircd.motd", 0);
275 doremotd = 0;
276 }
277 }
278
279 void
280 charybdis_io_loop(void)
281 {
282 time_t delay;
283
284 while (ServerRunning)
285 {
286 /* Run pending events, then get the number of seconds to the next
287 * event
288 */
289
290 delay = eventNextTime();
291 if(delay <= CurrentTime)
292 eventRun();
293
294
295 comm_select(250);
296 }
297 }
298
299 /*
300 * initalialize_global_set_options
301 *
302 * inputs - none
303 * output - none
304 * side effects - This sets all global set options needed
305 */
306 static void
307 initialize_global_set_options(void)
308 {
309 memset(&GlobalSetOptions, 0, sizeof(GlobalSetOptions));
310 /* memset( &ConfigFileEntry, 0, sizeof(ConfigFileEntry)); */
311
312 GlobalSetOptions.maxclients = ServerInfo.max_clients;
313 GlobalSetOptions.autoconn = 1;
314
315 GlobalSetOptions.spam_time = MIN_JOIN_LEAVE_TIME;
316 GlobalSetOptions.spam_num = MAX_JOIN_LEAVE_COUNT;
317
318 if(ConfigFileEntry.default_floodcount)
319 GlobalSetOptions.floodcount = ConfigFileEntry.default_floodcount;
320 else
321 GlobalSetOptions.floodcount = 10;
322
323 split_servers = ConfigChannel.default_split_server_count;
324 split_users = ConfigChannel.default_split_user_count;
325
326 if(split_users && split_servers
327 && (ConfigChannel.no_create_on_split || ConfigChannel.no_join_on_split))
328 {
329 splitmode = 1;
330 splitchecking = 1;
331 }
332
333 GlobalSetOptions.ident_timeout = IDENT_TIMEOUT;
334
335 strlcpy(GlobalSetOptions.operstring,
336 ConfigFileEntry.default_operstring,
337 sizeof(GlobalSetOptions.operstring));
338 strlcpy(GlobalSetOptions.adminstring,
339 ConfigFileEntry.default_adminstring,
340 sizeof(GlobalSetOptions.adminstring));
341
342 /* memset( &ConfigChannel, 0, sizeof(ConfigChannel)); */
343
344 /* End of global set options */
345
346 }
347
348 /*
349 * initialize_server_capabs
350 *
351 * inputs - none
352 * output - none
353 */
354 static void
355 initialize_server_capabs(void)
356 {
357 default_server_capabs &= ~CAP_ZIP;
358 }
359
360
361 /*
362 * write_pidfile
363 *
364 * inputs - filename+path of pid file
365 * output - none
366 * side effects - write the pid of the ircd to filename
367 */
368 static void
369 write_pidfile(const char *filename)
370 {
371 FILE *fb;
372 char buff[32];
373 if((fb = fopen(filename, "w")))
374 {
375 unsigned int pid = (unsigned int) getpid();
376
377 ircsnprintf(buff, sizeof(buff), "%u\n", pid);
378 if((fputs(buff, fb) == -1))
379 {
380 ilog(L_MAIN, "Error writing %u to pid file %s (%s)",
381 pid, filename, strerror(errno));
382 }
383 fclose(fb);
384 return;
385 }
386 else
387 {
388 ilog(L_MAIN, "Error opening pid file %s", filename);
389 }
390 }
391
392 /*
393 * check_pidfile
394 *
395 * inputs - filename+path of pid file
396 * output - none
397 * side effects - reads pid from pidfile and checks if ircd is in process
398 * list. if it is, gracefully exits
399 * -kre
400 */
401 static void
402 check_pidfile(const char *filename)
403 {
404 FILE *fb;
405 char buff[32];
406 pid_t pidfromfile;
407
408 /* Don't do logging here, since we don't have log() initialised */
409 if((fb = fopen(filename, "r")))
410 {
411 if(fgets(buff, 20, fb) != NULL)
412 {
413 pidfromfile = atoi(buff);
414 if(!kill(pidfromfile, 0))
415 {
416 printf("ircd: daemon is already running\n");
417 exit(-1);
418 }
419 }
420 fclose(fb);
421 }
422 }
423
424 /*
425 * setup_corefile
426 *
427 * inputs - nothing
428 * output - nothing
429 * side effects - setups corefile to system limits.
430 * -kre
431 */
432 static void
433 setup_corefile(void)
434 {
435 #ifdef HAVE_SYS_RESOURCE_H
436 struct rlimit rlim; /* resource limits */
437
438 /* Set corefilesize to maximum */
439 if(!getrlimit(RLIMIT_CORE, &rlim))
440 {
441 rlim.rlim_cur = rlim.rlim_max;
442 setrlimit(RLIMIT_CORE, &rlim);
443 }
444 #endif
445 }
446
447 /*
448 * main
449 *
450 * Initializes the IRCd.
451 *
452 * Inputs - number of commandline args, args themselves
453 * Outputs - none
454 * Side Effects - this is where the ircd gets going right now
455 */
456 int
457 main(int argc, char *argv[])
458 {
459 int fd;
460
461 /* Check to see if the user is running us as root, which is a nono */
462 if(geteuid() == 0)
463 {
464 fprintf(stderr, "Don't run ircd as root!!!\n");
465 return -1;
466 }
467
468 /*
469 * save server boot time right away, so getrusage works correctly
470 */
471 set_time();
472 /*
473 * Setup corefile size immediately after boot -kre
474 */
475 setup_corefile();
476
477 ServerRunning = 0;
478 /* It ain't random, but it ought to be a little harder to guess */
479 srand(SystemTime.tv_sec ^ (SystemTime.tv_usec | (getpid() << 20)));
480 memset(&me, 0, sizeof(me));
481 memset(&meLocalUser, 0, sizeof(meLocalUser));
482 me.localClient = &meLocalUser;
483
484 /* Make sure all lists are zeroed */
485 memset(&unknown_list, 0, sizeof(unknown_list));
486 memset(&lclient_list, 0, sizeof(lclient_list));
487 memset(&serv_list, 0, sizeof(serv_list));
488 memset(&global_serv_list, 0, sizeof(global_serv_list));
489 memset(&local_oper_list, 0, sizeof(local_oper_list));
490 memset(&oper_list, 0, sizeof(oper_list));
491
492 dlinkAddTail(&me, &me.node, &global_client_list);
493
494 memset((void *) &Count, 0, sizeof(Count));
495 memset((void *) &ServerInfo, 0, sizeof(ServerInfo));
496 memset((void *) &AdminInfo, 0, sizeof(AdminInfo));
497
498 /* Initialise the channel capability usage counts... */
499 init_chcap_usage_counts();
500
501 ConfigFileEntry.dpath = DPATH;
502 ConfigFileEntry.configfile = CPATH; /* Server configuration file */
503 ConfigFileEntry.klinefile = KPATH; /* Server kline file */
504 ConfigFileEntry.dlinefile = DLPATH; /* dline file */
505 ConfigFileEntry.xlinefile = XPATH;
506 ConfigFileEntry.resvfile = RESVPATH;
507 ConfigFileEntry.connect_timeout = 30; /* Default to 30 */
508 myargv = argv;
509 umask(077); /* better safe than sorry --SRB */
510
511 parseargs(&argc, &argv, myopts);
512
513 if(printVersion)
514 {
515 printf("ircd: version %s\n", ircd_version);
516 exit(EXIT_SUCCESS);
517 }
518
519 if(chdir(ConfigFileEntry.dpath))
520 {
521 fprintf(stderr, "Unable to chdir to %s: %s\n", ConfigFileEntry.dpath, strerror(errno));
522 exit(EXIT_FAILURE);
523 }
524
525 setup_signals();
526
527 #ifdef __CYGWIN__
528 server_state_foreground = 1;
529 #endif
530
531 if (testing_conf)
532 server_state_foreground = 1;
533
534 /* Make sure fd 0, 1 and 2 are in use -- jilles */
535 do
536 {
537 fd = open("/dev/null", O_RDWR);
538 } while (fd < 2 && fd != -1);
539 if (fd > 2)
540 close(fd);
541 else if (fd == -1)
542 exit(1);
543
544 /* Check if there is pidfile and daemon already running */
545 if(!testing_conf)
546 {
547 check_pidfile(pidFileName);
548
549 if(!server_state_foreground)
550 make_daemon();
551 inotice("starting %s ...", ircd_version);
552 }
553
554 /* Init the event subsystem */
555 init_sys();
556 libcharybdis_init(ircd_log_cb, restart, ircd_die_cb);
557
558 fdlist_init();
559 if(!server_state_foreground)
560 {
561 comm_close_all();
562 }
563
564 init_main_logfile();
565 init_patricia();
566 newconf_init();
567 init_s_conf();
568 init_s_newconf();
569 init_hash();
570 clear_scache_hash_table(); /* server cache name table */
571 init_host_hash();
572 clear_hash_parse();
573 init_client();
574 initUser();
575 init_hook();
576 init_channels();
577 initclass();
578 initwhowas();
579 init_stats();
580 init_reject();
581 init_cache();
582 init_monitor();
583 init_isupport();
584 load_all_modules(1);
585 #ifndef STATIC_MODULES
586 load_core_modules(1);
587 #endif
588 init_auth(); /* Initialise the auth code */
589 init_resolver(); /* Needs to be setup before the io loop */
590
591 if (testing_conf)
592 fprintf(stderr, "\nBeginning config test\n");
593 read_conf_files(YES); /* cold start init conf files */
594 rehash_bans(0);
595 #ifndef STATIC_MODULES
596
597 mod_add_path(MODULE_DIR);
598 mod_add_path(MODULE_DIR "/autoload");
599 #endif
600
601 initialize_server_capabs(); /* Set up default_server_capabs */
602 initialize_global_set_options();
603
604 if(ServerInfo.name == NULL)
605 {
606 ierror("no server name specified in serverinfo block.");
607 return -1;
608 }
609 strlcpy(me.name, ServerInfo.name, sizeof(me.name));
610
611 if(ServerInfo.sid[0] == '\0')
612 {
613 ierror("no server sid specified in serverinfo block.");
614 return -2;
615 }
616 strcpy(me.id, ServerInfo.sid);
617 init_uid();
618
619 /* serverinfo{} description must exist. If not, error out. */
620 if(ServerInfo.description == NULL)
621 {
622 ierror("no server description specified in serverinfo block.");
623 return -3;
624 }
625 strlcpy(me.info, ServerInfo.description, sizeof(me.info));
626
627 if (testing_conf)
628 {
629 fprintf(stderr, "\nConfig testing complete.\n");
630 fflush(stderr);
631 return 0; /* Why? We want the launcher to exit out. */
632 }
633
634 me.from = &me;
635 me.servptr = &me;
636 SetMe(&me);
637 make_server(&me);
638 startup_time = CurrentTime;
639 add_to_client_hash(me.name, &me);
640 add_to_id_hash(me.id, &me);
641 me.serv->nameinfo = scache_connect(me.name, me.info, 0);
642
643 dlinkAddAlloc(&me, &global_serv_list);
644
645 construct_umodebuf();
646
647 check_class();
648 write_pidfile(pidFileName);
649 load_help();
650 open_logfiles();
651
652 ilog(L_MAIN, "Server Ready");
653
654 eventAddIsh("cleanup_glines", cleanup_glines, NULL, CLEANUP_GLINES_TIME);
655
656 /* We want try_connections to be called as soon as possible now! -- adrian */
657 /* No, 'cause after a restart it would cause all sorts of nick collides */
658 /* um. by waiting even longer, that just means we have even *more*
659 * nick collisions. what a stupid idea. set an event for the IO loop --fl
660 */
661 eventAddIsh("try_connections", try_connections, NULL, STARTUP_CONNECTIONS_TIME);
662 eventAddOnce("try_connections_startup", try_connections, NULL, 0);
663
664 eventAddIsh("collect_zipstats", collect_zipstats, NULL, ZIPSTATS_TIME);
665
666 /* Setup the timeout check. I'll shift it later :) -- adrian */
667 eventAddIsh("comm_checktimeouts", comm_checktimeouts, NULL, 1);
668
669 eventAdd("check_rehash", check_rehash, NULL, 1);
670
671 if(splitmode)
672 eventAdd("check_splitmode", check_splitmode, NULL, 2);
673
674 ServerRunning = 1;
675
676 print_startup(getpid());
677
678 charybdis_io_loop();
679
680 return 0;
681 }