/[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.174 - (show annotations) (download) (as text)
Tue Jun 22 10:54:42 2004 UTC (15 years, 2 months ago) by wingman
Branch: MAIN
Changes since 1.173: +28 -17 lines
File MIME type: text/x-chdr
* Fixed -DDEBUG (wasn't supplied in lib/eggdrop and modules)

* Reformatted help and xml to match our coding rules

* Added simple memory tracking functions

* Added a debugging switch (-d, --debug) which isn't very usefull for
  anyone but me since it's a normal eggdrop run w/o the main loop ;-). It
  helps me finding mem leaks by doing

	./eggdrop -d && cat memory.log

  Yeah, will be removed, but not yet currently coz there are still ~270
  memory blocks allocated when eggdrop is shut down.

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

webmaster@eggheads.org
ViewVC Help
Powered by ViewVC 1.1.23