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(@joinchan @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
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*';
82 use POSIX qw(strftime);
83 $bot_release = strftime("cvs (%Y%m%d)", gmtime( (stat("CVS"))[9] ) );
85 $bot_release = "1.0.10 (2001xxxx)";
87 $bot_version = "blootbot $bot_release -- $^O";
97 if (defined $flag_quit) {
98 &WARN("doExit: quit already called.");
103 if (!defined $bot_pid) { # independent.
105 } elsif ($bot_pid == $$) { # parent.
106 &status("parent caught SIG$sig (pid $$).") if (defined $sig);
108 &status("--- Start of quit.");
109 $ident ||= "blootbot"; # lame hack.
111 &status("Memory Usage: $memusage KiB");
115 # shutdown IRC and related components.
116 if (&whatInterface() =~ /IRC/) {
119 &quit($param{'quitMsg'});
123 &uptimeWriteFile() if (&IsChanConf("uptime"));
126 &dumpallvars() if (&IsParam("dumpvarsAtExit"));
127 &symdumpAll() if (&IsParam("symdumpAtExit"));
129 &closeSQLDebug() if (&IsParam("SQLDebug"));
131 &status("--- QUIT.");
133 &status("child caught SIG$sig (pid $$).");
140 $SIG{__WARN__} = sub { warn $_[0]; };
146 $SIG{__WARN__} = 'doWarn'; # ???
149 # Usage: &IsParam($param);
150 # blootbot.config specific.
154 return 0 unless (defined $param);
155 return 0 unless (exists $param{$param});
156 return 0 unless ($param{$param});
157 return 0 if $param{$param} =~ /^false$/i;
162 # Usage: &ChanConfList($param)
163 # About: gets channels with 'param' enabled. (!!!)
164 # Return: array of channels
167 return unless (defined $param);
168 my %chan = &getChanConfList($param);
170 if (exists $chan{_default}) {
171 return keys %chanconf;
178 # Usage: &getChanConfList($param)
179 # About: gets channels with 'param' enabled, internal use only.
180 # Return: hash of channels
181 sub getChanConfList {
185 return unless (defined $param);
187 foreach (keys %chanconf) {
189 # &DEBUG("chan => $chan");
190 my @array = grep /^$param$/, keys %{ $chanconf{$chan} };
192 next unless (scalar @array);
194 if (scalar @array > 1) {
195 &WARN("multiple items found?");
198 if ($array[0] eq "0") {
209 # Usage: &IsChanConf($param);
210 # About: Check for 'param' on the basis of channel config.
211 # Return: 1 for enabled, 0 for passive disable, -1 for active disable.
214 my $debug = 0; # knocked tons of bugs with this! :)
216 if (!defined $param) {
217 &WARN("IsChanConf: param == NULL.");
221 # should we use IsParam() externally where needed or hack it in
222 # here just in case? fix it later.
223 if (&IsParam($param)) {
224 &DEBUG("ICC: found '$param' option in main config file.");
228 $chan ||= "_default";
231 if ($chan =~ tr/A-Z/a-z/) {
232 &WARN("IsChanConf: lowercased chan. ($old)");
235 ### TODO: VERBOSITY on how chanconf returned 1 or 0 or -1.
236 my %chan = &getChanConfList($param);
238 if (!defined $msgType) {
241 $nomatch++ if ($msgType eq "");
242 $nomatch++ unless ($msgType =~ /^(public|private)$/i);
245 ### debug purposes only.
246 # &DEBUG("param => $param, msgType => $msgType.");
247 # foreach (keys %chan) {
248 # &DEBUG(" $_ => $chan{$_}");
253 &DEBUG("ICC: other: $chan{$chan} (_default/$param)") if ($debug);
254 } elsif ($chan{_default}) {
255 &DEBUG("ICC: other: $chan{_default} (_default/$param)") if ($debug);
257 &DEBUG("ICC: other: 0 ($param)") if ($debug);
260 return $chan{$chan} || $chan{_default} || 0;
263 if ($msgType eq "public") {
265 &DEBUG("ICC: public: $chan{$chan} ($chan/$param)") if ($debug);
266 } elsif ($chan{_default}) {
267 &DEBUG("ICC: public: $chan{_default} (_default/$param)") if ($debug);
269 &DEBUG("ICC: public: 0 ($param)") if ($debug);
272 return $chan{$chan} || $chan{_default} || 0;
275 if ($msgType eq "private") {
276 if ($chan{_default}) {
277 &DEBUG("ICC: private: $chan{_default} (_default/$param)") if ($debug);
278 } elsif ($chan{$chan}) {
279 &DEBUG("ICC: private: $chan{$chan} ($chan/$param) (hack)") if ($debug);
281 &DEBUG("ICC: private: 0 ($param)") if ($debug);
284 return $chan{$chan} || $chan{_default} || 0;
287 &DEBUG("ICC: no-match: 0/$param (msgType = $msgType)");
293 # Usage: &getChanConf($param);
294 # About: Retrieve value for 'param' value in current/default chan.
295 # Return: scalar for success, undef for failure.
299 if (!defined $param) {
300 &WARN("gCC: param == NULL.");
305 if (0 and !defined $chan) {
306 &DEBUG("gCC: ok !chan... doing _default instead.");
311 $c = "_default" if ($c eq "*"); # fix!
312 my @c = grep /^\Q$c\E$/i, keys %chanconf;
315 if (0 and $c[0] ne $c) {
316 &WARN("c ne chan ($c[0] ne $chan)");
318 return $chanconf{$c[0]}{$param};
321 # &DEBUG("gCC: returning _default... ");
322 return $chanconf{"_default"}{$param};
325 sub getChanConfDefault {
326 my($what, $default, $chan) = @_;
328 $chan ||= "_default";
330 if (exists $param{$what}) {
331 if (!exists $cache{config}{$what}) {
332 &status("config ($chan): backward-compatible option: found param{$what} ($param{$what}) instead");
333 $cache{config}{$what} = 1;
336 return $param{$what};
338 my $val = &getChanConf($what, $chan);
339 return $val if (defined $val);
341 $param{$what} = $default;
342 &status("config ($chan): auto-setting param{$what} = $default");
343 $cache{config}{$what} = 1;
349 # Usage: &findChanConf($param);
350 # About: Retrieve value for 'param' value from any chan.
351 # Return: scalar for success, undef for failure.
355 if (!defined $param) {
356 &WARN("param == NULL.");
361 foreach $c (keys %chanconf) {
362 foreach (keys %{ $chanconf{$c} }) {
363 next unless (/^$param$/);
365 return $chanconf{$c}{$_};
373 my ($prefix) = $_[0] || "";
375 if ($^O eq "linux") {
376 if (!open(IN, "/proc/$$/status")) {
377 &ERROR("cannot open '/proc/$$/status'.");
382 $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
386 } elsif ($^O eq "netbsd") {
387 $memusage = int( (stat "/proc/$$/mem")[7]/1024 );
389 } elsif ($^O =~ /^(free|open)bsd$/) {
390 my @info = split /\s+/, `/bin/ps -l -p $$`;
391 $memusage = $info[20];
394 $memusage = "UNKNOWN";
398 if (defined $memusageOld and &IsParam("DEBUG")) {
399 # it's always going to be increase.
400 my $delta = $memusage - $memusageOld;
404 } elsif ($delta > 500) {
405 $str = "MEM:$prefix increased by $delta KiB. (total: $memusage KiB)";
406 } elsif ($delta > 0) {
407 $str = "MEM:$prefix increased by $delta KiB";
408 } else { # delta < 0.
410 # never knew RSS could decrease, probably Size can't?
411 $str = "MEM:$prefix decreased by $delta KiB.";
416 $memusageOld = $memusage;
424 &showProc(" (\&openLog before)");
425 &openLog(); # write, append.
426 &status("--- Started logging.");
429 &loadLang($bot_data_dir. "/blootbot.lang");
433 &loadMyModulesNow(); # must be after chan file.
436 &openSQLDebug() if (&IsParam("SQLDebug"));
437 &sqlOpenDB($param{'DBName'}, $param{'DBType'}, $param{'SQLUser'},
441 &status("Setup: ". &countKeys("factoids") ." factoids.");
442 &getChanConfDefault("sendPrivateLimitLines", 3);
443 &getChanConfDefault("sendPrivateLimitBytes", 1000);
444 &getChanConfDefault("sendPublicLimitLines", 3);
445 &getChanConfDefault("sendPublicLimitBytes", 1000);
446 &getChanConfDefault("sendNoticeLimitLines", 3);
447 &getChanConfDefault("sendNoticeLimitBytes", 1000);
449 $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
451 &status("Initial memory usage: $memusage KiB");
452 &status("-------------------------------------------------------");
456 $param{'VERBOSITY'} = 1;
457 &loadConfig($bot_config_dir."/blootbot.config");
459 foreach ( qw(ircNick ircUser ircName DBType tempDir) ) {
460 next if &IsParam($_);
461 &ERROR("Parameter $_ has not been defined.");
465 if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
466 &VERB("Fixing up tempDir.",2);
469 if ($param{tempDir} =~ /~/) {
470 &ERROR("parameter tempDir still contains tilde.");
474 if (! -d $param{tempDir}) {
475 &status("making $param{tempDir}...");
476 mkdir $param{tempDir}, 0755;
479 # static scalar variables.
480 $file{utm} = "$bot_state_dir/$param{'ircUser'}.uptime";
481 $file{PID} = "$bot_run_dir/$param{'ircUser'}.pid";
485 if (&IsParam("DEBUG")) {
486 &status("enabling debug diagnostics.");
487 ### I thought disabling this reduced memory usage by 1000 KiB.
491 $count{'Question'} = 0;
492 $count{'Update'} = 0;
499 # reverse order of &setup().
500 &status("--- shutdown called.");
502 $ident ||= "blootbot"; # hack.
504 if (!&isFileUpdated("$bot_state_dir/blootbot.users", $wtime_userfile)) {
508 if (!&isFileUpdated("$bot_state_dir/blootbot.chan", $wtime_chanfile)) {
513 &closeSHM($shm); # aswell. TODO: use this in &doExit?
520 if ($$ == $bot_pid) {
521 &status("--- $sig called.");
523 ### crappy bug in Net::IRC?
524 my $delta = time() - $msgtime;
525 &DEBUG("restart: dtime = $delta");
526 if (!$conn->connected or time() - $msgtime > 900) {
527 &status("reconnecting because of uncaught disconnect \@ ".scalar(gmtime) );
534 &ircCheck(); # heh, evil!
536 &DCCBroadcast("-HUP called.","m");
538 &loadConfig($bot_config_dir."/blootbot.config");
539 &reloadAllModules() if (&IsParam("DEBUG"));
542 &status("--- End of $sig.");
544 &status("$sig called; ignoring restart.");
548 # File: Configuration.
552 if (!open(FILE, $file)) {
553 &ERROR("Failed to read configuration file ($file): $!");
554 &status("Please read the INSTALL file on how to install and setup this file.");
563 my ($set,$key,$val) = split(/\s+/, $_, 3);
566 &status("loadConfig: invalid line '$_'.");
570 # perform variable interpolation
571 $val =~ s/(\$(\w+))/$param{$2}/g;
580 &status("Loaded config $file ($count items)");