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 $bot_release = "1.3.3";
83 use POSIX qw(strftime);
84 $bot_release .= strftime(" cvs (%Y%m%d)", gmtime( (stat("CVS"))[9] ) );
86 $bot_version = "blootbot $bot_release -- $^O";
94 if (!&IsParam("Interface") or $param{'Interface'} =~ /IRC/) {
104 if (defined $flag_quit) {
105 &WARN("doExit: quit already called.");
110 if (!defined $bot_pid) { # independent.
112 } elsif ($bot_pid == $$) { # parent.
113 &status("parent caught SIG$sig (pid $$).") if (defined $sig);
115 &status("--- Start of quit.");
116 $ident ||= "blootbot"; # lame hack.
118 &status("Memory Usage: $memusage KiB");
122 # shutdown IRC and related components.
123 if (&whatInterface() =~ /IRC/) {
126 &quit($param{'quitMsg'});
130 &uptimeWriteFile() if (&IsParam('Uptime'));
134 if (&IsParam("dumpvarsAtExit")) {
135 &loadMyModule('DumpVars');
138 &symdumpAll() if (&IsParam("symdumpAtExit"));
140 &closeSQLDebug() if (&IsParam("SQLDebug"));
142 &status("--- QUIT.");
144 &status("child caught SIG$sig (pid $$).");
151 $SIG{__WARN__} = sub { warn $_[0]; };
157 $SIG{__WARN__} = 'doWarn'; # ???
160 # Usage: &IsParam($param);
161 # blootbot.config specific.
165 return 0 unless (defined $param);
166 return 0 unless (exists $param{$param});
167 return 0 unless ($param{$param});
168 return 0 if $param{$param} =~ /^false$/i;
173 # Usage: &ChanConfList($param)
174 # About: gets channels with 'param' enabled. (!!!)
175 # Return: array of channels
178 return unless (defined $param);
179 my %chan = &getChanConfList($param);
181 if (exists $chan{_default}) {
182 return keys %chanconf;
189 # Usage: &getChanConfList($param)
190 # About: gets channels with 'param' enabled, internal use only.
191 # Return: hash of channels
192 sub getChanConfList {
196 return unless (defined $param);
198 foreach (keys %chanconf) {
200 my @array = grep /^$param$/, keys %{ $chanconf{$chan} };
201 #&DEBUG("gCCL param => $param, chan => $chan, keys => " . join(':',keys %{ $chanconf{$chan} }) . " array => " . join(':', @array)) if ($param eq 'whatever');
203 next unless (scalar @array);
205 if (scalar @array > 1) {
206 &WARN("multiple items found?");
209 if ($chanconf{$chan}{$param} eq "0") {
220 # Usage: &IsChanConf($param);
221 # About: Check for 'param' on the basis of channel config.
222 # Return: 1 for enabled, 0 for passive disable, -1 for active disable.
226 # knocked tons of bugs with this! :)
227 my $debug = 0; # 1 if ($param eq "whatever");
229 if (!defined $param) {
230 &WARN("IsChanConf: param == NULL.");
234 # these should get moved to your .chan file instead of the .config
235 # .config items overide any .chan entries
236 if (&IsParam($param)) {
237 &WARN("ICC: found '$param' option in main config file.");
241 $chan ||= "_default";
244 if ($chan =~ tr/A-Z/a-z/) {
245 &WARN("IsChanConf: lowercased chan. ($old)");
248 ### TODO: VERBOSITY on how chanconf returned 1 or 0 or -1.
249 my %chan = &getChanConfList($param);
251 if (!defined $msgType) {
254 $nomatch++ if ($msgType eq "");
255 $nomatch++ unless ($msgType =~ /^(public|private)$/i);
258 ### debug purposes only.
260 # &DEBUG("param => $param, msgType => $msgType.");
261 # foreach (keys %chan) {
262 # &DEBUG(" $_ => $chan{$_}");
268 &DEBUG("ICC: other: $chan{$chan} (_default/$param)") if ($debug);
269 } elsif ($chan{_default}) {
270 &DEBUG("ICC: other: $chan{_default} (_default/$param)") if ($debug);
272 &DEBUG("ICC: other: 0 ($param)") if ($debug);
274 return $chan{$chan} || $chan{_default} || 0;
275 } elsif ($msgType =~ /^(public|private)$/i) {
277 &DEBUG("ICC: $msgType: $chan{$chan} ($chan/$param)") if ($debug);
278 } elsif ($chan{_default}) {
279 &DEBUG("ICC: $msgType: $chan{_default} (_default/$param)") if ($debug);
281 &DEBUG("ICC: $msgType: 0 ($param)") if ($debug);
283 return $chan{$chan} || $chan{_default} || 0;
286 &DEBUG("ICC: no-match: 0/$param (msgType = $msgType)");
292 # Usage: &getChanConf($param);
293 # About: Retrieve value for 'param' value in current/default chan.
294 # Return: scalar for success, undef for failure.
298 if (!defined $param) {
299 &WARN("gCC: param == NULL.");
304 if (0 and !defined $chan) {
305 &DEBUG("gCC: ok !chan... doing _default instead.");
310 $c = "_default" if ($c eq "*"); # FIXME
311 my @c = grep /^\Q$c\E$/i, keys %chanconf;
314 if (0 and $c[0] ne $c) {
315 &WARN("c ne chan ($c[0] ne $chan)");
317 if (!defined $chanconf{$c[0]}{$param} and ($c ne '_default')) {
318 return &getChanConf($param, '_default');
320 #&DEBUG("gCC: $param,$c \"" . $chanconf{$c[0]}{$param} . '"');
321 return $chanconf{$c[0]}{$param};
324 #&DEBUG("gCC: returning _default... " . $chanconf{"_default"}{$param});
325 return $chanconf{"_default"}{$param};
328 sub getChanConfDefault {
329 my($what, $default, $chan) = @_;
330 $chan ||= "_default";
332 if (exists $param{$what}) {
333 if (!exists $cache{config}{$what}) {
334 &status("config ($chan): backward-compatible option: found param{$what} ($param{$what}) instead of chan option");
335 $cache{config}{$what} = 1;
338 return $param{$what};
340 my $val = &getChanConf($what, $chan);
341 return $val if (defined $val);
343 $param{$what} = $default;
344 &status("config ($chan): auto-setting param{$what} = $default");
345 $cache{config}{$what} = 1;
351 # Usage: &findChanConf($param);
352 # About: Retrieve value for 'param' value from any chan.
353 # Return: scalar for success, undef for failure.
357 if (!defined $param) {
358 &WARN("param == NULL.");
363 foreach $c (keys %chanconf) {
364 foreach (keys %{ $chanconf{$c} }) {
365 next unless (/^$param$/);
367 return $chanconf{$c}{$_};
375 my ($prefix) = $_[0] || "";
377 if ($^O eq "linux") {
378 if (!open(IN, "/proc/$$/status")) {
379 &ERROR("cannot open '/proc/$$/status'.");
384 $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
388 } elsif ($^O eq "netbsd") {
389 $memusage = int( (stat "/proc/$$/mem")[7]/1024 );
391 } elsif ($^O =~ /^(free|open)bsd$/) {
392 my @info = split /\s+/, `/bin/ps -l -p $$`;
393 $memusage = $info[20];
396 $memusage = "UNKNOWN";
400 if (defined $memusageOld and &IsParam("DEBUG")) {
401 # it's always going to be increase.
402 my $delta = $memusage - $memusageOld;
406 } elsif ($delta > 500) {
407 $str = "MEM:$prefix increased by $delta KiB. (total: $memusage KiB)";
408 } elsif ($delta > 0) {
409 $str = "MEM:$prefix increased by $delta KiB";
410 } else { # delta < 0.
412 # never knew RSS could decrease, probably Size can't?
413 $str = "MEM:$prefix decreased by $delta KiB.";
418 $memusageOld = $memusage;
426 &showProc(" (\&openLog before)");
427 &openLog(); # write, append.
428 &status("--- Started logging.");
431 &loadLang($bot_data_dir. "/blootbot.lang");
435 &loadMyModulesNow(); # must be after chan file.
438 &openSQLDebug() if (&IsParam("SQLDebug"));
439 &sqlOpenDB($param{'DBName'}, $param{'DBType'}, $param{'SQLUser'},
443 &status("Setup: ". &countKeys("factoids") ." factoids.");
444 &getChanConfDefault("sendPrivateLimitLines", 3, $chan);
445 &getChanConfDefault("sendPrivateLimitBytes", 1000, $chan);
446 &getChanConfDefault("sendPublicLimitLines", 3, $chan);
447 &getChanConfDefault("sendPublicLimitBytes", 1000, $chan);
448 &getChanConfDefault("sendNoticeLimitLines", 3, $chan);
449 &getChanConfDefault("sendNoticeLimitBytes", 1000, $chan);
451 $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
453 &status("Initial memory usage: $memusage KiB");
454 &status("-------------------------------------------------------");
458 $param{'VERBOSITY'} = 1;
459 &loadConfig($bot_config_dir."/blootbot.config");
461 foreach ( qw(ircNick ircUser ircName DBType tempDir) ) {
462 next if &IsParam($_);
463 &ERROR("Parameter $_ has not been defined.");
467 if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
468 &VERB("Fixing up tempDir.",2);
471 if ($param{tempDir} =~ /~/) {
472 &ERROR("parameter tempDir still contains tilde.");
476 if (! -d $param{tempDir}) {
477 &status("making $param{tempDir}...");
478 mkdir $param{tempDir}, 0755;
481 # static scalar variables.
482 $file{utm} = "$bot_state_dir/$param{'ircUser'}.uptime";
483 $file{PID} = "$bot_run_dir/$param{'ircUser'}.pid";
487 if (&IsParam("DEBUG")) {
488 &status("enabling debug diagnostics.");
489 # I thought disabling this reduced memory usage by 1000 KiB.
493 $count{'Question'} = 0;
494 $count{'Update'} = 0;
501 # reverse order of &setup().
502 &status("--- shutdown called.");
505 $ident ||= "blootbot";
507 if (!&isFileUpdated("$bot_state_dir/blootbot.users", $wtime_userfile)) {
511 if (!&isFileUpdated("$bot_state_dir/blootbot.chan", $wtime_chanfile)) {
516 # aswell. TODO: use this in &doExit?
524 if ($$ == $bot_pid) {
525 &status("--- $sig called.");
527 ### crappy bug in Net::IRC?
528 my $delta = time() - $msgtime;
529 &DEBUG("restart: dtime = $delta");
530 if (!$conn->connected or time() - $msgtime > 900) {
531 &status("reconnecting because of uncaught disconnect \@ ".scalar(gmtime) );
538 &ircCheck(); # heh, evil!
540 &DCCBroadcast("-HUP called.","m");
542 &loadConfig($bot_config_dir."/blootbot.config");
543 &reloadAllModules() if (&IsParam("DEBUG"));
546 &status("--- End of $sig.");
548 &status("$sig called; ignoring restart.");
552 # File: Configuration.
556 if (!open(FILE, $file)) {
557 &ERROR("Failed to read configuration file ($file): $!");
558 &status("Please read the INSTALL file on how to install and setup this file.");
567 my ($set,$key,$val) = split(/\s+/, $_, 3);
570 &status("loadConfig: invalid line '$_'.");
574 # perform variable interpolation
575 $val =~ s/(\$(\w+))/$param{$2}/g;
584 &status("Loaded config $file ($count items)");