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 (&IsChanConf('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 # &DEBUG("chan => $chan");
201 my @array = grep /^$param$/, keys %{ $chanconf{$chan} };
203 next unless (scalar @array);
205 if (scalar @array > 1) {
206 &WARN("multiple items found?");
209 if ($array[0] 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.
225 my $debug = 0; # knocked tons of bugs with this! :)
227 if (!defined $param) {
228 &WARN("IsChanConf: param == NULL.");
232 # should we use IsParam() externally where needed or hack it in
233 # here just in case? fix it later.
234 if (&IsParam($param)) {
235 &DEBUG("ICC: found '$param' option in main config file.");
239 $chan ||= "_default";
242 if ($chan =~ tr/A-Z/a-z/) {
243 &WARN("IsChanConf: lowercased chan. ($old)");
246 ### TODO: VERBOSITY on how chanconf returned 1 or 0 or -1.
247 my %chan = &getChanConfList($param);
249 if (!defined $msgType) {
252 $nomatch++ if ($msgType eq "");
253 $nomatch++ unless ($msgType =~ /^(public|private)$/i);
256 ### debug purposes only.
257 # &DEBUG("param => $param, msgType => $msgType.");
258 # foreach (keys %chan) {
259 # &DEBUG(" $_ => $chan{$_}");
264 &DEBUG("ICC: other: $chan{$chan} (_default/$param)") if ($debug);
265 } elsif ($chan{_default}) {
266 &DEBUG("ICC: other: $chan{_default} (_default/$param)") if ($debug);
268 &DEBUG("ICC: other: 0 ($param)") if ($debug);
271 return $chan{$chan} || $chan{_default} || 0;
274 if ($msgType eq "public") {
276 &DEBUG("ICC: public: $chan{$chan} ($chan/$param)") if ($debug);
277 } elsif ($chan{_default}) {
278 &DEBUG("ICC: public: $chan{_default} (_default/$param)") if ($debug);
280 &DEBUG("ICC: public: 0 ($param)") if ($debug);
283 return $chan{$chan} || $chan{_default} || 0;
286 if ($msgType eq "private") {
287 if ($chan{_default}) {
288 &DEBUG("ICC: private: $chan{_default} (_default/$param)") if ($debug);
289 } elsif ($chan{$chan}) {
290 &DEBUG("ICC: private: $chan{$chan} ($chan/$param) (hack)") if ($debug);
292 &DEBUG("ICC: private: 0 ($param)") if ($debug);
295 return $chan{$chan} || $chan{_default} || 0;
298 &DEBUG("ICC: no-match: 0/$param (msgType = $msgType)");
304 # Usage: &getChanConf($param);
305 # About: Retrieve value for 'param' value in current/default chan.
306 # Return: scalar for success, undef for failure.
310 if (!defined $param) {
311 &WARN("gCC: param == NULL.");
316 if (0 and !defined $chan) {
317 &DEBUG("gCC: ok !chan... doing _default instead.");
322 $c = "_default" if ($c eq "*"); # FIXME
323 my @c = grep /^\Q$c\E$/i, keys %chanconf;
326 if (0 and $c[0] ne $c) {
327 &WARN("c ne chan ($c[0] ne $chan)");
329 if (!defined $chanconf{$c[0]}{$param} and ($c ne '_default')) {
330 return &getChanConf($param, '_default');
332 #&DEBUG("gCC: $param,$c \"" . $chanconf{$c[0]}{$param} . '"');
333 return $chanconf{$c[0]}{$param};
336 #&DEBUG("gCC: returning _default... " . $chanconf{"_default"}{$param});
337 return $chanconf{"_default"}{$param};
340 sub getChanConfDefault {
341 my($what, $default, $chan) = @_;
343 $chan ||= "_default";
345 if (exists $param{$what}) {
346 if (!exists $cache{config}{$what}) {
347 &status("config ($chan): backward-compatible option: found param{$what} ($param{$what}) instead of chan option");
348 $cache{config}{$what} = 1;
351 return $param{$what};
353 my $val = &getChanConf($what, $chan);
354 return $val if (defined $val);
356 $param{$what} = $default;
357 &status("config ($chan): auto-setting param{$what} = $default");
358 $cache{config}{$what} = 1;
364 # Usage: &findChanConf($param);
365 # About: Retrieve value for 'param' value from any chan.
366 # Return: scalar for success, undef for failure.
370 if (!defined $param) {
371 &WARN("param == NULL.");
376 foreach $c (keys %chanconf) {
377 foreach (keys %{ $chanconf{$c} }) {
378 next unless (/^$param$/);
380 return $chanconf{$c}{$_};
388 my ($prefix) = $_[0] || "";
390 if ($^O eq "linux") {
391 if (!open(IN, "/proc/$$/status")) {
392 &ERROR("cannot open '/proc/$$/status'.");
397 $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
401 } elsif ($^O eq "netbsd") {
402 $memusage = int( (stat "/proc/$$/mem")[7]/1024 );
404 } elsif ($^O =~ /^(free|open)bsd$/) {
405 my @info = split /\s+/, `/bin/ps -l -p $$`;
406 $memusage = $info[20];
409 $memusage = "UNKNOWN";
413 if (defined $memusageOld and &IsParam("DEBUG")) {
414 # it's always going to be increase.
415 my $delta = $memusage - $memusageOld;
419 } elsif ($delta > 500) {
420 $str = "MEM:$prefix increased by $delta KiB. (total: $memusage KiB)";
421 } elsif ($delta > 0) {
422 $str = "MEM:$prefix increased by $delta KiB";
423 } else { # delta < 0.
425 # never knew RSS could decrease, probably Size can't?
426 $str = "MEM:$prefix decreased by $delta KiB.";
431 $memusageOld = $memusage;
439 &showProc(" (\&openLog before)");
440 &openLog(); # write, append.
441 &status("--- Started logging.");
444 &loadLang($bot_data_dir. "/blootbot.lang");
448 &loadMyModulesNow(); # must be after chan file.
451 &openSQLDebug() if (&IsParam("SQLDebug"));
452 &sqlOpenDB($param{'DBName'}, $param{'DBType'}, $param{'SQLUser'},
456 &status("Setup: ". &countKeys("factoids") ." factoids.");
457 &getChanConfDefault("sendPrivateLimitLines", 3);
458 &getChanConfDefault("sendPrivateLimitBytes", 1000);
459 &getChanConfDefault("sendPublicLimitLines", 3);
460 &getChanConfDefault("sendPublicLimitBytes", 1000);
461 &getChanConfDefault("sendNoticeLimitLines", 3);
462 &getChanConfDefault("sendNoticeLimitBytes", 1000);
464 $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
466 &status("Initial memory usage: $memusage KiB");
467 &status("-------------------------------------------------------");
471 $param{'VERBOSITY'} = 1;
472 &loadConfig($bot_config_dir."/blootbot.config");
474 foreach ( qw(ircNick ircUser ircName DBType tempDir) ) {
475 next if &IsParam($_);
476 &ERROR("Parameter $_ has not been defined.");
480 if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
481 &VERB("Fixing up tempDir.",2);
484 if ($param{tempDir} =~ /~/) {
485 &ERROR("parameter tempDir still contains tilde.");
489 if (! -d $param{tempDir}) {
490 &status("making $param{tempDir}...");
491 mkdir $param{tempDir}, 0755;
494 # static scalar variables.
495 $file{utm} = "$bot_state_dir/$param{'ircUser'}.uptime";
496 $file{PID} = "$bot_run_dir/$param{'ircUser'}.pid";
500 if (&IsParam("DEBUG")) {
501 &status("enabling debug diagnostics.");
502 # I thought disabling this reduced memory usage by 1000 KiB.
506 $count{'Question'} = 0;
507 $count{'Update'} = 0;
514 # reverse order of &setup().
515 &status("--- shutdown called.");
518 $ident ||= "blootbot";
520 if (!&isFileUpdated("$bot_state_dir/blootbot.users", $wtime_userfile)) {
524 if (!&isFileUpdated("$bot_state_dir/blootbot.chan", $wtime_chanfile)) {
529 # aswell. TODO: use this in &doExit?
537 if ($$ == $bot_pid) {
538 &status("--- $sig called.");
540 ### crappy bug in Net::IRC?
541 my $delta = time() - $msgtime;
542 &DEBUG("restart: dtime = $delta");
543 if (!$conn->connected or time() - $msgtime > 900) {
544 &status("reconnecting because of uncaught disconnect \@ ".scalar(gmtime) );
551 &ircCheck(); # heh, evil!
553 &DCCBroadcast("-HUP called.","m");
555 &loadConfig($bot_config_dir."/blootbot.config");
556 &reloadAllModules() if (&IsParam("DEBUG"));
559 &status("--- End of $sig.");
561 &status("$sig called; ignoring restart.");
565 # File: Configuration.
569 if (!open(FILE, $file)) {
570 &ERROR("Failed to read configuration file ($file): $!");
571 &status("Please read the INSTALL file on how to install and setup this file.");
580 my ($set,$key,$val) = split(/\s+/, $_, 3);
583 &status("loadConfig: invalid line '$_'.");
587 # perform variable interpolation
588 $val =~ s/(\$(\w+))/$param{$2}/g;
597 &status("Loaded config $file ($count items)");