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