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.1";
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"));
133 &dumpallvars() if (&IsParam("dumpvarsAtExit"));
134 &symdumpAll() if (&IsParam("symdumpAtExit"));
136 &closeSQLDebug() if (&IsParam("SQLDebug"));
138 &status("--- QUIT.");
140 &status("child caught SIG$sig (pid $$).");
147 $SIG{__WARN__} = sub { warn $_[0]; };
153 $SIG{__WARN__} = 'doWarn'; # ???
156 # Usage: &IsParam($param);
157 # blootbot.config specific.
161 return 0 unless (defined $param);
162 return 0 unless (exists $param{$param});
163 return 0 unless ($param{$param});
164 return 0 if $param{$param} =~ /^false$/i;
169 # Usage: &ChanConfList($param)
170 # About: gets channels with 'param' enabled. (!!!)
171 # Return: array of channels
174 return unless (defined $param);
175 my %chan = &getChanConfList($param);
177 if (exists $chan{_default}) {
178 return keys %chanconf;
185 # Usage: &getChanConfList($param)
186 # About: gets channels with 'param' enabled, internal use only.
187 # Return: hash of channels
188 sub getChanConfList {
192 return unless (defined $param);
194 foreach (keys %chanconf) {
196 # &DEBUG("chan => $chan");
197 my @array = grep /^$param$/, keys %{ $chanconf{$chan} };
199 next unless (scalar @array);
201 if (scalar @array > 1) {
202 &WARN("multiple items found?");
205 if ($array[0] eq "0") {
216 # Usage: &IsChanConf($param);
217 # About: Check for 'param' on the basis of channel config.
218 # Return: 1 for enabled, 0 for passive disable, -1 for active disable.
221 my $debug = 0; # knocked tons of bugs with this! :)
223 if (!defined $param) {
224 &WARN("IsChanConf: param == NULL.");
228 # should we use IsParam() externally where needed or hack it in
229 # here just in case? fix it later.
230 if (&IsParam($param)) {
231 &DEBUG("ICC: found '$param' option in main config file.");
235 $chan ||= "_default";
238 if ($chan =~ tr/A-Z/a-z/) {
239 &WARN("IsChanConf: lowercased chan. ($old)");
242 ### TODO: VERBOSITY on how chanconf returned 1 or 0 or -1.
243 my %chan = &getChanConfList($param);
245 if (!defined $msgType) {
248 $nomatch++ if ($msgType eq "");
249 $nomatch++ unless ($msgType =~ /^(public|private)$/i);
252 ### debug purposes only.
253 # &DEBUG("param => $param, msgType => $msgType.");
254 # foreach (keys %chan) {
255 # &DEBUG(" $_ => $chan{$_}");
260 &DEBUG("ICC: other: $chan{$chan} (_default/$param)") if ($debug);
261 } elsif ($chan{_default}) {
262 &DEBUG("ICC: other: $chan{_default} (_default/$param)") if ($debug);
264 &DEBUG("ICC: other: 0 ($param)") if ($debug);
267 return $chan{$chan} || $chan{_default} || 0;
270 if ($msgType eq "public") {
272 &DEBUG("ICC: public: $chan{$chan} ($chan/$param)") if ($debug);
273 } elsif ($chan{_default}) {
274 &DEBUG("ICC: public: $chan{_default} (_default/$param)") if ($debug);
276 &DEBUG("ICC: public: 0 ($param)") if ($debug);
279 return $chan{$chan} || $chan{_default} || 0;
282 if ($msgType eq "private") {
283 if ($chan{_default}) {
284 &DEBUG("ICC: private: $chan{_default} (_default/$param)") if ($debug);
285 } elsif ($chan{$chan}) {
286 &DEBUG("ICC: private: $chan{$chan} ($chan/$param) (hack)") if ($debug);
288 &DEBUG("ICC: private: 0 ($param)") if ($debug);
291 return $chan{$chan} || $chan{_default} || 0;
294 &DEBUG("ICC: no-match: 0/$param (msgType = $msgType)");
300 # Usage: &getChanConf($param);
301 # About: Retrieve value for 'param' value in current/default chan.
302 # Return: scalar for success, undef for failure.
306 if (!defined $param) {
307 &WARN("gCC: param == NULL.");
312 if (0 and !defined $chan) {
313 &DEBUG("gCC: ok !chan... doing _default instead.");
318 $c = "_default" if ($c eq "*"); # FIXME
319 my @c = grep /^\Q$c\E$/i, keys %chanconf;
322 if (0 and $c[0] ne $c) {
323 &WARN("c ne chan ($c[0] ne $chan)");
325 return $chanconf{$c[0]}{$param};
328 # &DEBUG("gCC: returning _default... ");
329 return $chanconf{"_default"}{$param};
332 sub getChanConfDefault {
333 my($what, $default, $chan) = @_;
335 $chan ||= "_default";
337 if (exists $param{$what}) {
338 if (!exists $cache{config}{$what}) {
339 &status("config ($chan): backward-compatible option: found param{$what} ($param{$what}) instead of chan option");
340 $cache{config}{$what} = 1;
343 return $param{$what};
345 my $val = &getChanConf($what, $chan);
346 return $val if (defined $val);
348 $param{$what} = $default;
349 &status("config ($chan): auto-setting param{$what} = $default");
350 $cache{config}{$what} = 1;
356 # Usage: &findChanConf($param);
357 # About: Retrieve value for 'param' value from any chan.
358 # Return: scalar for success, undef for failure.
362 if (!defined $param) {
363 &WARN("param == NULL.");
368 foreach $c (keys %chanconf) {
369 foreach (keys %{ $chanconf{$c} }) {
370 next unless (/^$param$/);
372 return $chanconf{$c}{$_};
380 my ($prefix) = $_[0] || "";
382 if ($^O eq "linux") {
383 if (!open(IN, "/proc/$$/status")) {
384 &ERROR("cannot open '/proc/$$/status'.");
389 $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
393 } elsif ($^O eq "netbsd") {
394 $memusage = int( (stat "/proc/$$/mem")[7]/1024 );
396 } elsif ($^O =~ /^(free|open)bsd$/) {
397 my @info = split /\s+/, `/bin/ps -l -p $$`;
398 $memusage = $info[20];
401 $memusage = "UNKNOWN";
405 if (defined $memusageOld and &IsParam("DEBUG")) {
406 # it's always going to be increase.
407 my $delta = $memusage - $memusageOld;
411 } elsif ($delta > 500) {
412 $str = "MEM:$prefix increased by $delta KiB. (total: $memusage KiB)";
413 } elsif ($delta > 0) {
414 $str = "MEM:$prefix increased by $delta KiB";
415 } else { # delta < 0.
417 # never knew RSS could decrease, probably Size can't?
418 $str = "MEM:$prefix decreased by $delta KiB.";
423 $memusageOld = $memusage;
431 &showProc(" (\&openLog before)");
432 &openLog(); # write, append.
433 &status("--- Started logging.");
436 &loadLang($bot_data_dir. "/blootbot.lang");
440 &loadMyModulesNow(); # must be after chan file.
443 &openSQLDebug() if (&IsParam("SQLDebug"));
444 &sqlOpenDB($param{'DBName'}, $param{'DBType'}, $param{'SQLUser'},
448 &status("Setup: ". &countKeys("factoids") ." factoids.");
449 &getChanConfDefault("sendPrivateLimitLines", 3);
450 &getChanConfDefault("sendPrivateLimitBytes", 1000);
451 &getChanConfDefault("sendPublicLimitLines", 3);
452 &getChanConfDefault("sendPublicLimitBytes", 1000);
453 &getChanConfDefault("sendNoticeLimitLines", 3);
454 &getChanConfDefault("sendNoticeLimitBytes", 1000);
456 $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
458 &status("Initial memory usage: $memusage KiB");
459 &status("-------------------------------------------------------");
463 $param{'VERBOSITY'} = 1;
464 &loadConfig($bot_config_dir."/blootbot.config");
466 foreach ( qw(ircNick ircUser ircName DBType tempDir) ) {
467 next if &IsParam($_);
468 &ERROR("Parameter $_ has not been defined.");
472 if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
473 &VERB("Fixing up tempDir.",2);
476 if ($param{tempDir} =~ /~/) {
477 &ERROR("parameter tempDir still contains tilde.");
481 if (! -d $param{tempDir}) {
482 &status("making $param{tempDir}...");
483 mkdir $param{tempDir}, 0755;
486 # static scalar variables.
487 $file{utm} = "$bot_state_dir/$param{'ircUser'}.uptime";
488 $file{PID} = "$bot_run_dir/$param{'ircUser'}.pid";
492 if (&IsParam("DEBUG")) {
493 &status("enabling debug diagnostics.");
494 # I thought disabling this reduced memory usage by 1000 KiB.
498 $count{'Question'} = 0;
499 $count{'Update'} = 0;
506 # reverse order of &setup().
507 &status("--- shutdown called.");
510 $ident ||= "blootbot";
512 if (!&isFileUpdated("$bot_state_dir/blootbot.users", $wtime_userfile)) {
516 if (!&isFileUpdated("$bot_state_dir/blootbot.chan", $wtime_chanfile)) {
521 # aswell. TODO: use this in &doExit?
529 if ($$ == $bot_pid) {
530 &status("--- $sig called.");
532 ### crappy bug in Net::IRC?
533 my $delta = time() - $msgtime;
534 &DEBUG("restart: dtime = $delta");
535 if (!$conn->connected or time() - $msgtime > 900) {
536 &status("reconnecting because of uncaught disconnect \@ ".scalar(gmtime) );
543 &ircCheck(); # heh, evil!
545 &DCCBroadcast("-HUP called.","m");
547 &loadConfig($bot_config_dir."/blootbot.config");
548 &reloadAllModules() if (&IsParam("DEBUG"));
551 &status("--- End of $sig.");
553 &status("$sig called; ignoring restart.");
557 # File: Configuration.
561 if (!open(FILE, $file)) {
562 &ERROR("Failed to read configuration file ($file): $!");
563 &status("Please read the INSTALL file on how to install and setup this file.");
572 my ($set,$key,$val) = split(/\s+/, $_, 3);
575 &status("loadConfig: invalid line '$_'.");
579 # perform variable interpolation
580 $val =~ s/(\$(\w+))/$param{$2}/g;
589 &status("Loaded config $file ($count items)");