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";
95 if (!&IsParam("Interface") or $param{'Interface'} =~ /IRC/) {
105 if (defined $flag_quit) {
106 &WARN("doExit: quit already called.");
111 if (!defined $bot_pid) { # independent.
113 } elsif ($bot_pid == $$) { # parent.
114 &status("parent caught SIG$sig (pid $$).") if (defined $sig);
116 &status("--- Start of quit.");
117 $ident ||= "blootbot"; # lame hack.
119 &status("Memory Usage: $memusage KiB");
123 # shutdown IRC and related components.
124 if (&whatInterface() =~ /IRC/) {
127 &quit($param{'quitMsg'});
131 &uptimeWriteFile() if (&IsChanConf("uptime"));
134 &dumpallvars() if (&IsParam("dumpvarsAtExit"));
135 &symdumpAll() if (&IsParam("symdumpAtExit"));
137 &closeSQLDebug() if (&IsParam("SQLDebug"));
139 &status("--- QUIT.");
141 &status("child caught SIG$sig (pid $$).");
148 $SIG{__WARN__} = sub { warn $_[0]; };
154 $SIG{__WARN__} = 'doWarn'; # ???
157 # Usage: &IsParam($param);
158 # blootbot.config specific.
162 return 0 unless (defined $param);
163 return 0 unless (exists $param{$param});
164 return 0 unless ($param{$param});
165 return 0 if $param{$param} =~ /^false$/i;
170 # Usage: &ChanConfList($param)
171 # About: gets channels with 'param' enabled. (!!!)
172 # Return: array of channels
175 return unless (defined $param);
176 my %chan = &getChanConfList($param);
178 if (exists $chan{_default}) {
179 return keys %chanconf;
186 # Usage: &getChanConfList($param)
187 # About: gets channels with 'param' enabled, internal use only.
188 # Return: hash of channels
189 sub getChanConfList {
193 return unless (defined $param);
195 foreach (keys %chanconf) {
197 # &DEBUG("chan => $chan");
198 my @array = grep /^$param$/, keys %{ $chanconf{$chan} };
200 next unless (scalar @array);
202 if (scalar @array > 1) {
203 &WARN("multiple items found?");
206 if ($array[0] eq "0") {
217 # Usage: &IsChanConf($param);
218 # About: Check for 'param' on the basis of channel config.
219 # Return: 1 for enabled, 0 for passive disable, -1 for active disable.
222 my $debug = 0; # knocked tons of bugs with this! :)
224 if (!defined $param) {
225 &WARN("IsChanConf: param == NULL.");
229 # should we use IsParam() externally where needed or hack it in
230 # here just in case? fix it later.
231 if (&IsParam($param)) {
232 &DEBUG("ICC: found '$param' option in main config file.");
236 $chan ||= "_default";
239 if ($chan =~ tr/A-Z/a-z/) {
240 &WARN("IsChanConf: lowercased chan. ($old)");
243 ### TODO: VERBOSITY on how chanconf returned 1 or 0 or -1.
244 my %chan = &getChanConfList($param);
246 if (!defined $msgType) {
249 $nomatch++ if ($msgType eq "");
250 $nomatch++ unless ($msgType =~ /^(public|private)$/i);
253 ### debug purposes only.
254 # &DEBUG("param => $param, msgType => $msgType.");
255 # foreach (keys %chan) {
256 # &DEBUG(" $_ => $chan{$_}");
261 &DEBUG("ICC: other: $chan{$chan} (_default/$param)") if ($debug);
262 } elsif ($chan{_default}) {
263 &DEBUG("ICC: other: $chan{_default} (_default/$param)") if ($debug);
265 &DEBUG("ICC: other: 0 ($param)") if ($debug);
268 return $chan{$chan} || $chan{_default} || 0;
271 if ($msgType eq "public") {
273 &DEBUG("ICC: public: $chan{$chan} ($chan/$param)") if ($debug);
274 } elsif ($chan{_default}) {
275 &DEBUG("ICC: public: $chan{_default} (_default/$param)") if ($debug);
277 &DEBUG("ICC: public: 0 ($param)") if ($debug);
280 return $chan{$chan} || $chan{_default} || 0;
283 if ($msgType eq "private") {
284 if ($chan{_default}) {
285 &DEBUG("ICC: private: $chan{_default} (_default/$param)") if ($debug);
286 } elsif ($chan{$chan}) {
287 &DEBUG("ICC: private: $chan{$chan} ($chan/$param) (hack)") if ($debug);
289 &DEBUG("ICC: private: 0 ($param)") if ($debug);
292 return $chan{$chan} || $chan{_default} || 0;
295 &DEBUG("ICC: no-match: 0/$param (msgType = $msgType)");
301 # Usage: &getChanConf($param);
302 # About: Retrieve value for 'param' value in current/default chan.
303 # Return: scalar for success, undef for failure.
307 if (!defined $param) {
308 &WARN("gCC: param == NULL.");
313 if (0 and !defined $chan) {
314 &DEBUG("gCC: ok !chan... doing _default instead.");
319 $c = "_default" if ($c eq "*"); # fix!
320 my @c = grep /^\Q$c\E$/i, keys %chanconf;
323 if (0 and $c[0] ne $c) {
324 &WARN("c ne chan ($c[0] ne $chan)");
326 return $chanconf{$c[0]}{$param};
329 # &DEBUG("gCC: returning _default... ");
330 return $chanconf{"_default"}{$param};
333 sub getChanConfDefault {
334 my($what, $default, $chan) = @_;
336 $chan ||= "_default";
338 if (exists $param{$what}) {
339 if (!exists $cache{config}{$what}) {
340 &status("config ($chan): backward-compatible option: found param{$what} ($param{$what}) instead of chan option");
341 $cache{config}{$what} = 1;
344 return $param{$what};
346 my $val = &getChanConf($what, $chan);
347 return $val if (defined $val);
349 $param{$what} = $default;
350 &status("config ($chan): auto-setting param{$what} = $default");
351 $cache{config}{$what} = 1;
357 # Usage: &findChanConf($param);
358 # About: Retrieve value for 'param' value from any chan.
359 # Return: scalar for success, undef for failure.
363 if (!defined $param) {
364 &WARN("param == NULL.");
369 foreach $c (keys %chanconf) {
370 foreach (keys %{ $chanconf{$c} }) {
371 next unless (/^$param$/);
373 return $chanconf{$c}{$_};
381 my ($prefix) = $_[0] || "";
383 if ($^O eq "linux") {
384 if (!open(IN, "/proc/$$/status")) {
385 &ERROR("cannot open '/proc/$$/status'.");
390 $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
394 } elsif ($^O eq "netbsd") {
395 $memusage = int( (stat "/proc/$$/mem")[7]/1024 );
397 } elsif ($^O =~ /^(free|open)bsd$/) {
398 my @info = split /\s+/, `/bin/ps -l -p $$`;
399 $memusage = $info[20];
402 $memusage = "UNKNOWN";
406 if (defined $memusageOld and &IsParam("DEBUG")) {
407 # it's always going to be increase.
408 my $delta = $memusage - $memusageOld;
412 } elsif ($delta > 500) {
413 $str = "MEM:$prefix increased by $delta KiB. (total: $memusage KiB)";
414 } elsif ($delta > 0) {
415 $str = "MEM:$prefix increased by $delta KiB";
416 } else { # delta < 0.
418 # never knew RSS could decrease, probably Size can't?
419 $str = "MEM:$prefix decreased by $delta KiB.";
424 $memusageOld = $memusage;
432 &showProc(" (\&openLog before)");
433 &openLog(); # write, append.
434 &status("--- Started logging.");
437 &loadLang($bot_data_dir. "/blootbot.lang");
441 &loadMyModulesNow(); # must be after chan file.
444 &openSQLDebug() if (&IsParam("SQLDebug"));
445 &sqlOpenDB($param{'DBName'}, $param{'DBType'}, $param{'SQLUser'},
449 &status("Setup: ". &countKeys("factoids") ." factoids.");
450 &getChanConfDefault("sendPrivateLimitLines", 3);
451 &getChanConfDefault("sendPrivateLimitBytes", 1000);
452 &getChanConfDefault("sendPublicLimitLines", 3);
453 &getChanConfDefault("sendPublicLimitBytes", 1000);
454 &getChanConfDefault("sendNoticeLimitLines", 3);
455 &getChanConfDefault("sendNoticeLimitBytes", 1000);
457 $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
459 &status("Initial memory usage: $memusage KiB");
460 &status("-------------------------------------------------------");
464 $param{'VERBOSITY'} = 1;
465 &loadConfig($bot_config_dir."/blootbot.config");
467 foreach ( qw(ircNick ircUser ircName DBType tempDir) ) {
468 next if &IsParam($_);
469 &ERROR("Parameter $_ has not been defined.");
473 if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
474 &VERB("Fixing up tempDir.",2);
477 if ($param{tempDir} =~ /~/) {
478 &ERROR("parameter tempDir still contains tilde.");
482 if (! -d $param{tempDir}) {
483 &status("making $param{tempDir}...");
484 mkdir $param{tempDir}, 0755;
487 # static scalar variables.
488 $file{utm} = "$bot_state_dir/$param{'ircUser'}.uptime";
489 $file{PID} = "$bot_run_dir/$param{'ircUser'}.pid";
493 if (&IsParam("DEBUG")) {
494 &status("enabling debug diagnostics.");
495 ### I thought disabling this reduced memory usage by 1000 KiB.
499 $count{'Question'} = 0;
500 $count{'Update'} = 0;
507 # reverse order of &setup().
508 &status("--- shutdown called.");
510 $ident ||= "blootbot"; # hack.
512 if (!&isFileUpdated("$bot_state_dir/blootbot.users", $wtime_userfile)) {
516 if (!&isFileUpdated("$bot_state_dir/blootbot.chan", $wtime_chanfile)) {
521 &closeSHM($shm); # aswell. TODO: use this in &doExit?
528 if ($$ == $bot_pid) {
529 &status("--- $sig called.");
531 ### crappy bug in Net::IRC?
532 my $delta = time() - $msgtime;
533 &DEBUG("restart: dtime = $delta");
534 if (!$conn->connected or time() - $msgtime > 900) {
535 &status("reconnecting because of uncaught disconnect \@ ".scalar(gmtime) );
542 &ircCheck(); # heh, evil!
544 &DCCBroadcast("-HUP called.","m");
546 &loadConfig($bot_config_dir."/blootbot.config");
547 &reloadAllModules() if (&IsParam("DEBUG"));
550 &status("--- End of $sig.");
552 &status("$sig called; ignoring restart.");
556 # File: Configuration.
560 if (!open(FILE, $file)) {
561 &ERROR("Failed to read configuration file ($file): $!");
562 &status("Please read the INSTALL file on how to install and setup this file.");
571 my ($set,$key,$val) = split(/\s+/, $_, 3);
574 &status("loadConfig: invalid line '$_'.");
578 # perform variable interpolation
579 $val =~ s/(\$(\w+))/$param{$2}/g;
588 &status("Loaded config $file ($count items)");