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