/[cvs]/eggdrop1.9/src/main.c
ViewVC logotype

Contents of /eggdrop1.9/src/main.c

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.173 - (show annotations) (download) (as text)
Mon Jun 21 19:04:51 2004 UTC (15 years, 4 months ago) by stdarg
Branch: MAIN
Changes since 1.172: +48 -135 lines
File MIME type: text/x-chdr
* Trying a simpler method of forking into the background.
* Trying a lockfile approach -- seems to work well so far.

1 /* main.c
2 *
3 * Copyright (C) 1997 Robey Pointer
4 * Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004 Eggheads Development Team
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 */
20
21 #ifndef lint
22 static const char rcsid[] = "$Id: main.c,v 1.172 2004/06/21 14:26:02 stdarg Exp $";
23 #endif
24
25 #if HAVE_CONFIG_H
26 # include <config.h>
27 #endif
28
29 #include <eggdrop/eggdrop.h>
30 #include <ctype.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <string.h>
34 #include <stdlib.h>
35 #include <sys/stat.h>
36 #include <errno.h>
37 #include <signal.h>
38 #include <netdb.h>
39 #include <setjmp.h>
40 #include <locale.h>
41 #include <ctype.h>
42 #include <ltdl.h>
43
44 #include <eggdrop/stat.h>
45
46 #ifdef TIME_WITH_SYS_TIME
47 # include <sys/time.h>
48 # include <time.h>
49 #else
50 # ifdef HAVE_SYS_TIME_H
51 # include <sys/time.h>
52 # else
53 # include <time.h>
54 # endif
55 #endif
56
57 #include "lib/compat/compat.h"
58 #include "debug.h"
59 #include "core_config.h"
60 #include "core_party.h"
61 #include "core_binds.h"
62 #include "logfile.h"
63 #include "terminal.h"
64 #include "bg.h"
65 #include "main.h"
66
67 #ifdef STOP_UAC /* OSF/1 complains a lot */
68 # include <sys/sysinfo.h>
69 # define UAC_NOPRINT 0x00000001 /* Don't report unaligned fixups */
70 #endif
71
72 #ifdef CYGWIN_HACKS
73 # include <windows.h>
74 #endif
75
76 #ifndef _POSIX_SOURCE
77 # define _POSIX_SOURCE 1 /* Solaris needs this */
78 #endif
79
80 #define RUNMODE_NORMAL 1
81 #define RUNMODE_SHUTDOWN 2
82 #define RUNMODE_RESTART 3
83
84 int runmode = 1; /* The most important variable ever! */
85 int backgrd = 1; /* Run in the background? */
86 int make_userfile = 0; /* Start bot in make-userfile mode? */
87 int terminal_mode = 0; /* Terminal mode */
88
89 const char *configfile = NULL; /* Name of the config file */
90 char pid_file[512]; /* Name of Eggdrop's pid file */
91
92 time_t online_since; /* Time the bot was started */
93 time_t now; /* Current time */
94 egg_timeval_t egg_timeval_now; /* Current time in seconds and microseconds. */
95
96 int use_stderr = 1; /* Send stuff to stderr instead of logfiles? */
97
98 char version[81];
99
100 static int lastmin = 99;
101 static struct tm nowtm;
102
103 void core_config_init();
104
105 void fatal(const char *errmsg)
106 {
107 putlog(LOG_MISC, "*", "Fatal: %s", errmsg);
108 flushlogs();
109 exit(1);
110 }
111
112 static void got_bus(int z)
113 {
114 fatal("BUS ERROR.");
115 }
116
117 static void got_segv(int z)
118 {
119 fatal("SEGMENT VIOLATION.");
120 }
121
122 static void got_fpe(int z)
123 {
124 fatal("FLOATING POINT ERROR.");
125 }
126
127 static void got_term(int z)
128 {
129 eggdrop_event("sigterm");
130 if (core_config.die_on_sigterm) core_shutdown(SHUTDOWN_SIGTERM, NULL, NULL);
131 else putlog(LOG_MISC, "*", _("Received TERM signal (ignoring)."));
132 }
133
134 static void got_quit(int z)
135 {
136 eggdrop_event("sigquit");
137 putlog(LOG_MISC, "*", _("Received QUIT signal (ignoring)."));
138 return;
139 }
140
141 static void got_hup(int z)
142 {
143 eggdrop_event("sighup");
144 putlog(LOG_MISC, "*", _("Received HUP signal (ignoring)."));
145 return;
146 }
147
148 static void print_version(void)
149 {
150 printf("%s\n", version);
151 }
152
153 static void print_help(char *const *argv)
154 {
155 print_version();
156 printf(_("\nUsage: %s [OPTIONS]... [FILE]\n"), argv[0]);
157 printf(_("\n\
158 -h, --help Print help and exit\n\
159 -v, --version Print version and exit\n\
160 -n, --foreground Don't go into the background (default=off)\n\
161 -c --channel-stats (with -n) Display channel stats every 10 seconds\n\
162 -t --terminal (with -n) Use terminal to simulate dcc-chat\n\
163 -m --make-userfile Userfile creation mode\n\
164 FILE optional config filename (default 'config.xml')\n"));
165 printf("\n");
166 }
167
168 static void do_args(int argc, char *const *argv)
169 {
170 int c;
171
172 optarg = 0;
173 optind = 1;
174 opterr = 1;
175 optopt = '?';
176
177 while (1) {
178 int option_index = 0;
179
180 static struct option long_options[] = {
181 {"help", 0, NULL, 'h'},
182 {"version", 0, NULL, 'v'},
183 {"load-module", 1, NULL, 'p'},
184 {"foreground", 0, NULL, 'n'},
185 {"terminal", 0, NULL, 't'},
186 {"make-userfile", 0, NULL, 'm'},
187 {NULL, 0, NULL, 0}
188 };
189
190 c = getopt_long(argc, argv, "hvp:nctm", long_options, &option_index);
191 if (c == -1) break;
192 switch (c) {
193 case 'n':
194 backgrd = 0;
195 break;
196 case 't':
197 terminal_mode = 1;
198 break;
199 case 'm':
200 make_userfile = 1;
201 break;
202 case 'v':
203 print_version();
204 exit(0);
205 break; /* this should never be reached */
206 case 'h':
207 print_help(argv);
208 exit(0);
209 break; /* this should never be reached */
210 case 0: /* Long option with no short option */
211 case '?': /* Invalid option. */
212 /* getopt_long() already printed an error message. */
213 exit(1);
214 default: /* bug: option not considered. */
215 fprintf(stderr, _("%s: option unknown: %c\n"), argv[0], c);
216 exit(1);
217 break; /* this should never be reached */
218 }
219 }
220 if (optind < argc) configfile = argv[optind];
221 else configfile = "config.xml";
222 }
223
224 /* Called once a second.
225 */
226 static int core_secondly()
227 {
228 static int cnt = 0;
229 int miltime;
230
231 check_bind_secondly();
232 cnt++;
233 memcpy(&nowtm, localtime(&now), sizeof(struct tm));
234 if (nowtm.tm_min != lastmin) {
235 int i = 0;
236
237 /* Once a minute */
238 lastmin = (lastmin + 1) % 60;
239 eggdrop_event("minutely");
240 check_bind_time(&nowtm);
241 /* In case for some reason more than 1 min has passed: */
242 while (nowtm.tm_min != lastmin) {
243 /* Timer drift, dammit */
244 putlog(LOG_DEBUG, "*", "timer: drift (lastmin=%d, now=%d)", lastmin, nowtm.tm_min);
245 i++;
246 lastmin = (lastmin + 1) % 60;
247 eggdrop_event("minutely");
248 }
249 if (i > 1) putlog(LOG_MISC, "*", _("Warning: timer drift (%d minutes)."), i);
250
251 miltime = (nowtm.tm_hour * 100) + (nowtm.tm_min);
252 if (nowtm.tm_min % 5 == 0) { /* 5 minutes */
253 eggdrop_event("5minutely");
254 if (!miltime) { /* At midnight */
255 char s[25];
256
257 strlcpy(s, ctime(&now), sizeof s);
258 putlog(LOG_ALL, "*", "--- %.11s%s", s, s + 20);
259 eggdrop_event("backup");
260 eggdrop_event("daily");
261 }
262 }
263 }
264 return(0);
265 }
266
267
268 int file_check(const char *filename)
269 {
270 struct stat sbuf = {0};
271 int r;
272
273 r = stat(filename, &sbuf);
274 if (r) return(-1);
275 errno = 0;
276 if (sbuf.st_mode & (S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)) return(-1);
277 return(0);
278 }
279
280 static int create_userfile(void)
281 {
282 user_t *owner;
283 char handle[512], password[12];
284 int len;
285
286 printf("\n");
287 if (user_count() != 0) {
288 printf("You are trying to create a new userfile, but the old one still exists (%s)!\n", core_config.userfile);
289 printf("Please remove the userfile, or do not pass the -m option.\n\n");
290 return(-1);
291 }
292
293 printf("Hello! I see you are creating a new userfile.\n\n");
294 printf("Let's create the owner account.\n\n");
295 do {
296 printf("Enter the owner handle: ");
297 fflush(stdout);
298 fgets(handle, sizeof(handle), stdin);
299 for (len = 0; handle[len]; len++) {
300 if (!ispunct(handle[len]) && !isalnum(handle[len])) break;
301 }
302 if (len == 0) printf("Come on, enter a real handle.\n\n");
303 } while (len <= 0);
304 handle[len] = 0;
305
306 owner = user_new(handle);
307 if (!owner) {
308 printf("Failed to create user record! Out of memory?\n\n");
309 return(-1);
310 }
311
312 user_rand_pass(password, sizeof(password));
313 user_set_pass(owner, password);
314 user_set_flags_str(owner, NULL, "+n");
315 printf("Your owner handle is '%s' and your password is '%s' (without the quotes).\n\n", handle, password);
316 memset(password, 0, sizeof(password));
317 str_redup(&core_config.owner, handle);
318 core_config_save();
319 user_save(core_config.userfile);
320
321 return(0);
322 }
323
324 static void init_signals(void)
325 {
326 struct sigaction sv;
327
328
329 sv.sa_handler = got_bus;
330 sigemptyset(&sv.sa_mask);
331 #ifdef SA_RESETHAND
332 sv.sa_flags = SA_RESETHAND;
333 #else
334 sv.sa_flags = 0;
335 #endif
336 sigaction(SIGBUS, &sv, NULL);
337
338 sv.sa_handler = got_segv;
339 sigaction(SIGSEGV, &sv, NULL);
340 #ifdef SA_RESETHAND
341 sv.sa_flags = 0;
342 #endif
343
344 sv.sa_handler = got_fpe;
345 sigaction(SIGFPE, &sv, NULL);
346
347 sv.sa_handler = got_term;
348 sigaction(SIGTERM, &sv, NULL);
349
350 sv.sa_handler = got_hup;
351 sigaction(SIGHUP, &sv, NULL);
352
353 sv.sa_handler = got_quit;
354 sigaction(SIGQUIT, &sv, NULL);
355
356 sv.sa_handler = SIG_IGN;
357 sigaction(SIGPIPE, &sv, NULL);
358 }
359
360 static void core_shutdown_or_restart()
361 {
362 /* notifiy shutdown listeners */
363 check_bind_shutdown();
364
365 putlog(LOG_MISC, "*", _("Saving user file..."));
366 user_save(core_config.userfile);
367
368 putlog(LOG_MISC, "*", _("Saving config file..."));
369 core_config_save();
370
371 /* shutdown logging */
372 logfile_shutdown();
373
374 /* shutdown libeggdrop */
375 eggdrop_shutdown();
376
377 /* force a garbage run */
378 garbage_run();
379
380 /* just remove pid file if didn't restart */
381 if (runmode != RUNMODE_RESTART)
382 unlink(pid_file);
383 }
384
385 int main(int argc, char **argv)
386 {
387 int timeout;
388
389 #ifdef DEBUG
390 {
391 # include <sys/resource.h>
392 struct rlimit cdlim;
393
394 cdlim.rlim_cur = RLIM_INFINITY;
395 cdlim.rlim_max = RLIM_INFINITY;
396 setrlimit(RLIMIT_CORE, &cdlim);
397 }
398 #endif
399
400 init_signals();
401
402 #ifdef ENABLE_NLS
403 setlocale(LC_MESSAGES, "");
404 bindtextdomain(PACKAGE, LOCALEDIR);
405 textdomain(PACKAGE);
406 #endif
407
408 /* Initialize ltdl. */
409 LTDL_SET_PRELOADED_SYMBOLS();
410 if (lt_dlinit()) {
411 printf("Fatal error initializing ltdl: %s\n", lt_dlerror());
412 return(-1);
413 }
414
415 snprintf(version, sizeof version, "Eggdrop v%s (C) 1997 Robey Pointer (C) 2004 Eggheads Development Team", VERSION);
416
417 #ifdef STOP_UAC
418 {
419 int nvpair[2];
420
421 nvpair[0] = SSIN_UACPROC;
422 nvpair[1] = UAC_NOPRINT;
423 setsysinfo(SSI_NVPAIRS, (char *) nvpair, 1, NULL, 0);
424 }
425 #endif
426
427 timer_update_now(&egg_timeval_now);
428 now = egg_timeval_now.sec;
429 memcpy(&nowtm, localtime(&now), sizeof(struct tm));
430 lastmin = nowtm.tm_min;
431
432 srandom(now % (getpid() + getppid()));
433
434 do_args(argc, argv);
435 printf("\n%s\n", version);
436 printf("WARNING: Do NOT run this DEVELOPMENT version for any purpose other than testing.\n\n");
437
438 /* we may not run as root */
439 if (((int) getuid() == 0) || ((int) geteuid() == 0)) {
440 fatal("Eggdrop will not run as root!");
441 return -1;
442 }
443
444 /* config file may not be world read/writeable */
445 if (file_check(configfile)) {
446 if (errno) perror(configfile);
447 else {
448 fprintf(stderr, "ERROR\n");
449 fprintf(stderr, "\tCheck file permissions on your config file!");
450 fprintf(stderr, "\tMake sure other groups and users cannot read/write it.\n");
451 return -1;
452 }
453 }
454
455 /* set uptime */
456 online_since = now;
457
458 do {
459 egg_timeval_t howlong;
460
461 /* default select timeout is 1 sec */
462 howlong.sec = 1;
463 howlong.usec = 0;
464
465 timer_create_repeater(&howlong, "main loop", core_secondly);
466
467 /* init core */
468 core_init();
469
470 /* set normal running mode */
471 runmode = RUNMODE_NORMAL;
472
473 putlog(LOG_DEBUG, "*", "Entering main loop.");
474
475 /* main loop */
476 while (runmode == RUNMODE_NORMAL) {
477 /* Update the time. */
478 timer_update_now(&egg_timeval_now);
479 now = egg_timeval_now.sec;
480
481 /* Run any expired timers. */
482 timer_run();
483
484 /* Figure out how long to wait for activity. */
485 if (timer_get_shortest(&howlong)) timeout = 1000;
486 else timeout = howlong.sec * 1000 + howlong.usec / 1000;
487
488 /* Wait and monitor sockets. */
489 sockbuf_update_all(timeout);
490
491 /* Run any scheduled cleanups. */
492 garbage_run();
493 }
494
495 /* Save user file, config file, ... */
496 core_shutdown_or_restart();
497
498 /* the only chance to loop again is that running = 2, meaning
499 we have a restart */
500 } while (runmode == RUNMODE_RESTART);
501
502 return 1;
503 }
504
505 int core_init()
506 {
507 int i;
508 char *name;
509 void *config_root, *entry;
510 char datetime[25];
511 static int lockfd = -1;
512 struct flock lock;
513
514 /* init libeggdrop */
515 eggdrop_init();
516
517 /* load config */
518 core_config_init(configfile);
519
520 /* init logging */
521 logfile_init();
522
523 /* did the user specify -m? */
524 if (make_userfile) {
525 if (create_userfile()) return(-1);
526 make_userfile = 0;
527 }
528
529 /* init background mode and pid file */
530 if (runmode != RUNMODE_RESTART) {
531 if (backgrd) bg_begin_split();
532 }
533
534 /* Check lock file. */
535 if (core_config.lockfile && lockfd == -1) {
536 lockfd = open(core_config.lockfile, O_WRONLY | O_CREAT, S_IWUSR);
537 if (lockfd < 0) {
538 fatal("Could not open lock file!");
539 }
540 memset(&lock, 0, sizeof(lock));
541 lock.l_type = F_WRLCK;
542 if (fcntl(lockfd, F_SETLK, &lock) != 0) {
543 fatal("Lock file is already locked! Is eggdrop already running?");
544 }
545 }
546
547 /* just issue this "Loading Eggdrop" message if we are not
548 * restarting */
549 if (runmode != RUNMODE_RESTART) {
550 strlcpy(datetime, ctime(&now), sizeof(datetime));
551 strcpy(&datetime[11], &datetime[20]);
552 putlog(LOG_ALL, "*", "Loading Eggdrop %s (%s)", VERSION, datetime);
553 }
554
555 /* load userlist */
556 if (core_config.userfile)
557 user_load(core_config.userfile);
558
559 /* init core bindings */
560 core_binds_init();
561
562 /* init core partyline */
563 core_party_init();
564
565 /* Load core help */
566 help_load_by_module ("core");
567
568 /* Put the module directory in the ltdl search path. */
569 if (core_config.module_path)
570 module_add_dir(core_config.module_path);
571
572 /* Scan the autoload section of config. */
573 config_root = config_get_root("eggdrop");
574 for (i = 0; (entry = config_exists(config_root, "eggdrop", 0, "autoload", 0, "module", i, NULL)); i++) {
575 name = NULL;
576 config_get_str(&name, entry, NULL);
577 module_load(name);
578 }
579 for (i = 0; (entry = config_exists(config_root, "eggdrop", 0, "autoload", 0, "script", i, NULL)); i++) {
580 name = NULL;
581 config_get_str(&name, entry, NULL);
582 script_load(name);
583 }
584
585 /* notify init listeners */
586 check_bind_init();
587
588 /* start terminal */
589 if (runmode != RUNMODE_RESTART) {
590 if (backgrd) bg_finish_split();
591 if (terminal_mode) terminal_init();
592 }
593
594 return 1;
595 }
596
597 int core_restart(const char *nick)
598 {
599 putlog(LOG_MISC, "*", "Restarting...");
600 runmode = RUNMODE_RESTART;
601 return 1;
602 }
603
604 int core_shutdown(int how, const char *nick, const char *reason)
605 {
606 if (how == SHUTDOWN_SIGTERM)
607 putlog(LOG_MISC, "*", ("Received TERM signal, shutting down."));
608 else if (how != SHUTDOWN_RESTART)
609 putlog(LOG_MISC, "*", ("Shutdown requested by %s: %s"), nick,
610 (reason) ? reason : _("No reason"));
611
612 /* check how to shut down */
613 switch (how) {
614
615 case (SHUTDOWN_RESTART):
616 runmode = RUNMODE_RESTART;
617 break;
618
619 case (SHUTDOWN_GRACEFULL):
620 runmode = RUNMODE_SHUTDOWN;
621 break;
622
623 /* These two cases are treaded special because something
624 * unusual happened and we're better off if we exit() NOW
625 * than doing a gracefull shutdown with freeing all
626 * memory, closing all sockets, ... */
627 case (SHUTDOWN_HARD):
628 case (SHUTDOWN_SIGTERM):
629 runmode = RUNMODE_SHUTDOWN;
630 core_shutdown_or_restart();
631 exit(0);
632 break;
633
634 }
635
636 return BIND_RET_LOG;
637 }

webmaster@eggheads.org
ViewVC Help
Powered by ViewVC 1.1.23