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