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