2 # core.pl: Important functions stuff...
4 # Version: v0.4 (20000718)
10 # scalar. MUST BE REDUCED IN SIZE!!!
13 $bot_misc_dir $bot_pid $bot_base_dir $bot_src_dir
14 $bot_data_dir $bot_config_dir $bot_state_dir $bot_run_dir
15 $answer $correction_plausible $talkchannel $bot_release
16 $statcount $memusage $user $memusageOld $bot_version $dbh
17 $shm $host $msg $noreply $conn $irc $learnok $nick $ident
18 $force_public_reply $addrchar $userHandle $addressedother
19 $floodwho $chan $msgtime $server $firsttime $wingaterun
20 $flag_quit $msgType $no_syscall
21 $utime_userfile $wtime_userfile $ucount_userfile
22 $utime_chanfile $wtime_chanfile $ucount_chanfile
23 $pubsize $pubcount $pubtime
24 $msgsize $msgcount $msgtime
25 $notsize $notcount $nottime
30 use vars qw(@ircServers @wingateBad @wingateNow @wingateCache
33 ### hash. MUST BE REDUCED IN SIZE!!!
35 use vars qw(%count %netsplit %netsplitservers %flood %dcc %orig
36 %nuh %talkWho %seen %floodwarn %param %dbh %ircPort
37 %topic %moduleAge %last %time %mask %file
38 %forked %chanconf %channels %cache
42 $SIG{'HUP'} = 'restart'; # 1.
43 $SIG{'INT'} = 'doExit'; # 2.
44 $SIG{'KILL'} = 'doExit'; # 9. DOES NOT WORK. 'man perlipc' for details.
45 $SIG{'TERM'} = 'doExit'; # 15.
46 $SIG{'__WARN__'} = 'doWarn';
48 # initialize variables.
52 $userHandle = "_default";
63 # static scalar variables.
64 $mask{ip} = '(\d+)\.(\d+)\.(\d+)\.(\d+)';
65 $mask{host} = '[\d\w\_\-\/]+\.[\.\d\w\_\-\/]+';
66 $mask{chan} = '[\#\&]\S*|_default';
67 my $isnick1 = 'a-zA-Z\[\]\{\}\_\`\^\|\\\\';
68 my $isnick2 = '0-9\-';
69 $mask{nick} = "[$isnick1]{1}[$isnick1$isnick2]*";
70 $mask{nuh} = '\S*!\S*\@\S*';
81 open(VERSION, '<VERSION');
82 $bot_release = <VERSION> || "(unknown version)";
85 $bot_version = "infobot $bot_release -- $^O";
93 if (!&IsParam('Interface') or $param{'Interface'} =~ /IRC/) {
103 if (defined $flag_quit) {
104 &WARN("doExit: quit already called.");
109 if (!defined $bot_pid) { # independent.
111 } elsif ($bot_pid == $$) { # parent.
112 &status("parent caught SIG$sig (pid $$).") if (defined $sig);
114 &status("--- Start of quit.");
115 $ident ||= 'infobot'; # lame hack.
117 &status("Memory Usage: $memusage KiB");
121 # shutdown IRC and related components.
122 if (&whatInterface() =~ /IRC/) {
125 &quit($param{'quitMsg'});
129 &uptimeWriteFile() if (&IsParam('Uptime'));
133 if (&IsParam('dumpvarsAtExit')) {
134 &loadMyModule('DumpVars');
137 &symdumpAll() if (&IsParam('symdumpAtExit'));
139 &closeSQLDebug() if (&IsParam('SQLDebug'));
141 &status("--- QUIT.");
143 &status("child caught SIG$sig (pid $$).");
150 $SIG{__WARN__} = sub { warn $_[0]; };
156 $SIG{__WARN__} = 'doWarn'; # ???
159 # Usage: &IsParam($param);
160 # infobot.config specific.
164 return 0 unless (defined $param);
165 return 0 unless (exists $param{$param});
166 return 0 unless ($param{$param});
167 return 0 if $param{$param} =~ /^false$/i;
172 # Usage: &ChanConfList($param)
173 # About: gets channels with 'param' enabled. (!!!)
174 # Return: array of channels
177 return unless (defined $param);
178 my %chan = &getChanConfList($param);
180 if (exists $chan{_default}) {
181 return keys %chanconf;
188 # Usage: &getChanConfList($param)
189 # About: gets channels with 'param' enabled, internal use only.
190 # Return: hash of channels
191 sub getChanConfList {
195 return unless (defined $param);
197 foreach (keys %chanconf) {
199 my @array = grep /^$param$/, keys %{ $chanconf{$chan} };
200 #&DEBUG("gCCL param => $param, chan => $chan, keys => " . join(':',keys %{ $chanconf{$chan} }) . " array => " . join(':', @array)) if ($param eq 'whatever');
202 next unless (scalar @array);
204 if (scalar @array > 1) {
205 &WARN("multiple items found?");
208 if ($chanconf{$chan}{$param} eq '0') {
219 # Usage: &IsChanConf($param);
220 # About: Check for 'param' on the basis of channel config.
221 # Return: 1 for enabled, 0 for passive disable, -1 for active disable.
225 # knocked tons of bugs with this! :)
226 my $debug = 0; # 1 if ($param eq 'whatever');
228 if (!defined $param) {
229 &WARN("IsChanConf: param == NULL.");
233 # these should get moved to your .chan file instead of the .config
234 # .config items overide any .chan entries
235 if (&IsParam($param)) {
236 &WARN("ICC: found '$param' option in main config file.");
240 $chan ||= "_default";
243 if ($chan =~ tr/A-Z/a-z/) {
244 &WARN("IsChanConf: lowercased chan. ($old)");
247 ### TODO: VERBOSITY on how chanconf returned 1 or 0 or -1.
248 my %chan = &getChanConfList($param);
250 if (!defined $msgType) {
253 $nomatch++ if ($msgType eq '');
254 $nomatch++ unless ($msgType =~ /^(public|private)$/i);
257 ### debug purposes only.
259 # &DEBUG("param => $param, msgType => $msgType.");
260 # foreach (keys %chan) {
261 # &DEBUG(" $_ => $chan{$_}");
267 &DEBUG("ICC: other: $chan{$chan} (_default/$param)") if ($debug);
268 } elsif ($chan{_default}) {
269 &DEBUG("ICC: other: $chan{_default} (_default/$param)") if ($debug);
271 &DEBUG("ICC: other: 0 ($param)") if ($debug);
273 return $chan{$chan} || $chan{_default} || 0;
274 } elsif ($msgType =~ /^(public|private)$/i) {
276 &DEBUG("ICC: $msgType: $chan{$chan} ($chan/$param)") if ($debug);
277 } elsif ($chan{_default}) {
278 &DEBUG("ICC: $msgType: $chan{_default} (_default/$param)") if ($debug);
280 &DEBUG("ICC: $msgType: 0 ($param)") if ($debug);
282 return $chan{$chan} || $chan{_default} || 0;
285 &DEBUG("ICC: no-match: 0/$param (msgType = $msgType)");
291 # Usage: &getChanConf($param);
292 # About: Retrieve value for 'param' value in current/default chan.
293 # Return: scalar for success, undef for failure.
297 if (!defined $param) {
298 &WARN("gCC: param == NULL.");
303 if (0 and !defined $chan) {
304 &DEBUG("gCC: ok !chan... doing _default instead.");
309 $c = "_default" if ($c eq "*"); # FIXME
310 my @c = grep /^\Q$c\E$/i, keys %chanconf;
313 if (0 and $c[0] ne $c) {
314 &WARN("c ne chan ($c[0] ne $chan)");
316 if (!defined $chanconf{$c[0]}{$param} and ($c ne '_default')) {
317 return &getChanConf($param, '_default');
319 &DEBUG("gCC: $param,$c \"" . $chanconf{$c[0]}{$param} . '"');
320 return $chanconf{$c[0]}{$param};
323 #&DEBUG("gCC: returning _default... " . $chanconf{"_default"}{$param});
324 return $chanconf{"_default"}{$param};
327 sub getChanConfDefault {
328 my($what, $default, $chan) = @_;
329 $chan ||= "_default";
331 if (exists $param{$what}) {
332 if (!exists $cache{config}{$what}) {
333 &status("config ($chan): backward-compatible option: found param{$what} ($param{$what}) instead of chan option");
334 $cache{config}{$what} = 1;
337 return $param{$what};
339 my $val = &getChanConf($what, $chan);
340 return $val if (defined $val);
342 $param{$what} = $default;
343 &status("config ($chan): auto-setting param{$what} = $default");
344 $cache{config}{$what} = 1;
350 # Usage: &findChanConf($param);
351 # About: Retrieve value for 'param' value from any chan.
352 # Return: scalar for success, undef for failure.
356 if (!defined $param) {
357 &WARN("param == NULL.");
362 foreach $c (keys %chanconf) {
363 foreach (keys %{ $chanconf{$c} }) {
364 next unless (/^$param$/);
366 return $chanconf{$c}{$_};
374 my ($prefix) = $_[0] || '';
376 if ($^O eq 'linux') {
377 if (!open(IN, "/proc/$$/status")) {
378 &ERROR("cannot open '/proc/$$/status'.");
383 $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
387 } elsif ($^O eq 'netbsd') {
388 $memusage = int( (stat "/proc/$$/mem")[7]/1024 );
390 } elsif ($^O =~ /^(free|open)bsd$/) {
391 my @info = split /\s+/, `/bin/ps -l -p $$`;
392 $memusage = $info[20];
395 $memusage = 'UNKNOWN';
399 if (defined $memusageOld and &IsParam('DEBUG')) {
400 # it's always going to be increase.
401 my $delta = $memusage - $memusageOld;
405 } elsif ($delta > 500) {
406 $str = "MEM:$prefix increased by $delta KiB. (total: $memusage KiB)";
407 } elsif ($delta > 0) {
408 $str = "MEM:$prefix increased by $delta KiB";
409 } else { # delta < 0.
411 # never knew RSS could decrease, probably Size can't?
412 $str = "MEM:$prefix decreased by $delta KiB.";
417 $memusageOld = $memusage;
425 &showProc(" (\&openLog before)");
426 &openLog(); # write, append.
427 &status("--- Started logging.");
430 &loadLang($bot_data_dir. "/infobot.lang");
434 &loadMyModulesNow(); # must be after chan file.
437 &openSQLDebug() if (&IsParam('SQLDebug'));
438 &sqlOpenDB($param{'DBName'}, $param{'DBType'}, $param{'SQLUser'},
442 &status("Setup: ". &countKeys('factoids') ." factoids.");
443 &getChanConfDefault('sendPrivateLimitLines', 3, $chan);
444 &getChanConfDefault('sendPrivateLimitBytes', 1000, $chan);
445 &getChanConfDefault('sendPublicLimitLines', 3, $chan);
446 &getChanConfDefault('sendPublicLimitBytes', 1000, $chan);
447 &getChanConfDefault('sendNoticeLimitLines', 3, $chan);
448 &getChanConfDefault('sendNoticeLimitBytes', 1000, $chan);
450 $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
452 &status("Initial memory usage: $memusage KiB");
453 &status("-------------------------------------------------------");
457 $param{'VERBOSITY'} = 1;
458 &loadConfig($bot_config_dir."/infobot.config");
460 foreach ( qw(ircNick ircUser ircName DBType tempDir) ) {
461 next if &IsParam($_);
462 &ERROR("Parameter $_ has not been defined.");
466 if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
467 &VERB("Fixing up tempDir.",2);
470 if ($param{tempDir} =~ /~/) {
471 &ERROR("parameter tempDir still contains tilde.");
475 if (! -d $param{tempDir}) {
476 &status("making $param{tempDir}...");
477 mkdir $param{tempDir}, 0755;
480 # static scalar variables.
481 $file{utm} = "$bot_state_dir/$param{'ircUser'}.uptime";
482 $file{PID} = "$bot_run_dir/$param{'ircUser'}.pid";
486 if (&IsParam('DEBUG')) {
487 &status("enabling debug diagnostics.");
488 # I thought disabling this reduced memory usage by 1000 KiB.
492 $count{'Question'} = 0;
493 $count{'Update'} = 0;
500 # reverse order of &setup().
501 &status("--- shutdown called.");
504 $ident ||= 'infobot';
506 if (!&isFileUpdated("$bot_state_dir/infobot.users", $wtime_userfile)) {
510 if (!&isFileUpdated("$bot_state_dir/infobot.chan", $wtime_chanfile)) {
515 # aswell. TODO: use this in &doExit?
523 if ($$ == $bot_pid) {
524 &status("--- $sig called.");
526 ### crappy bug in Net::IRC?
527 my $delta = time() - $msgtime;
528 &DEBUG("restart: dtime = $delta");
529 if (!$conn->connected or time() - $msgtime > 900) {
530 &status("reconnecting because of uncaught disconnect \@ ".scalar(gmtime) );
537 &ircCheck(); # heh, evil!
539 &DCCBroadcast("-HUP called.",'m');
541 &loadConfig($bot_config_dir."/infobot.config");
542 &reloadAllModules() if (&IsParam('DEBUG'));
545 &status("--- End of $sig.");
547 &status("$sig called; ignoring restart.");
551 # File: Configuration.
555 if (!open(FILE, $file)) {
556 &ERROR("Failed to read configuration file ($file): $!");
557 &status("Please read the INSTALL file on how to install and setup this file.");
566 my ($set,$key,$val) = split(/\s+/, $_, 3);
569 &status("loadConfig: invalid line '$_'.");
573 # perform variable interpolation
574 $val =~ s/(\$(\w+))/$param{$2}/g;
583 &status("Loaded config $file ($count items)");
588 # vim:ts=4:sw=4:expandtab:tw=80