]> git.donarmstrong.com Git - infobot.git/blob - src/core.pl
- berkeley dbm support now works! thanks to tim riker.
[infobot.git] / src / core.pl
1 #
2 #   core.pl: Important functions stuff...
3 #    Author: dms
4 #   Version: v0.4 (20000718)
5 #   Created: 20000322
6 #
7
8 use strict;
9
10 # dynamic scalar. MUST BE REDUCED IN SIZE!!!
11 ### TODO: reorder.
12 use vars qw(
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
26         $running
27 );
28
29 # dynamic hash.
30 use vars qw(@joinchan @ircServers @wingateBad @wingateNow @wingateCache
31 );
32
33 ### dynamic hash. MUST BE REDUCED IN SIZE!!!
34
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
39 );
40
41 # Signals.
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';
47
48 # initialize variables.
49 $last{buflen}   = 0;
50 $last{say}      = "";
51 $last{msg}      = "";
52 $userHandle     = "default";
53 $wingaterun     = time();
54 $firsttime      = 1;
55 $utime_userfile = 0;
56 $wtime_userfile = 0;
57 $ucount_userfile = 0;
58 $utime_chanfile = 0;
59 $wtime_chanfile = 0;
60 $ucount_chanfile = 0;
61 $running        = 0;
62 ### more variables...
63 $msgtime        = time();
64 $msgsize        = 0;
65 $msgcount       = 0;
66 $pubtime        = 0;
67 $pubsize        = 0;
68 $pubcount       = 0;
69 $nottime        = 0;
70 $notsize        = 0;
71 $notcount       = 0;
72 ###
73 if ( -d "CVS" ) {
74     use POSIX qw(strftime);
75     $bot_release        = strftime("cvs (%Y%m%d)", localtime( (stat("CVS"))[9] ) );
76 } else {
77     $bot_release        = "1.0.10 (2001xxxx)";
78 }
79 $bot_version    = "blootbot $bot_release -- $^O";
80 $noreply        = "NOREPLY";
81
82 ##########
83 ### misc commands.
84 ###
85
86 sub doExit {
87     my ($sig)   = @_;
88
89     if (defined $flag_quit) {
90         &WARN("doExit: quit already called.");
91         return;
92     }
93     $flag_quit  = 1;
94
95     if (!defined $bot_pid) {    # independent.
96         exit 0;
97     } elsif ($bot_pid == $$) {  # parent.
98         &status("parent caught SIG$sig (pid $$).") if (defined $sig);
99
100         &status("--- Start of quit.");
101         $ident ||= "blootbot";  # lame hack.
102
103         &closeDCC() if (&whatInterface() =~ /IRC/); 
104         &closePID();
105         &closeStats();
106         &seenFlush() if (&whatInterface() =~ /IRC/);
107         &quit($param{'quitMsg'}) if (&whatInterface() =~ /IRC/);
108         &writeUserFile();
109         &writeChanFile();
110         &uptimeWriteFile()      if (&ChanConfList("uptime"));
111         &News::writeNews()      if (&ChanConfList("news"));
112         &closeDB();
113         &closeSHM($shm);
114         &dumpallvars()          if (&IsParam("dumpvarsAtExit"));
115         &symdumpAll()           if (&IsParam("symdumpAtExit"));
116         &closeLog();
117         &closeSQLDebug()        if (&IsParam("SQLDebug"));
118
119         &status("--- QUIT.");
120     } else {                                    # child.
121         &status("child caught SIG$sig (pid $$).");
122     }
123
124     exit 0;
125 }
126
127 sub doWarn {
128     $SIG{__WARN__} = sub { warn $_[0]; };
129
130     foreach (@_) {
131         &WARN("PERL: $_");
132     }
133
134     $SIG{__WARN__} = 'doWarn';  # ???
135 }
136
137 # Usage: &IsParam($param);
138 # blootbot.config specific.
139 sub IsParam {
140     my $param = $_[0];
141
142     return 0 unless (defined $param);
143     return 0 unless (exists $param{$param});
144     return 0 unless ($param{$param});
145     return 0 if $param{$param} =~ /^false$/i;
146     return 1;
147 }
148
149 #####
150 #  Usage: &ChanConfList($param)
151 #  About: gets channels with 'param' enabled. (!!!)
152 # Return: array of channels
153 sub ChanConfList {
154     my $param   = $_[0];
155     return unless (defined $param);
156     my %chan    = &getChanConfList($param);
157
158     if (exists $chan{_default}) {
159         return keys %chanconf;
160     } else {
161         return keys %chan;
162     }
163 }
164
165 #####
166 #  Usage: &getChanConfList($param)
167 #  About: gets channels with 'param' enabled, internal use only.
168 # Return: hash of channels
169 sub getChanConfList {
170     my $param   = $_[0];
171     my %chan;
172
173     return unless (defined $param);
174
175     foreach (keys %chanconf) {
176         my $chan        = $_;
177 #       &DEBUG("chan => $chan");
178         my @array       = grep /^$param$/, keys %{ $chanconf{$chan} };
179
180         next unless (scalar @array);
181
182         if (scalar @array > 1) {
183             &WARN("multiple items found?");
184         }
185
186         if ($array[0] eq "0") {
187             $chan{$chan}        = -1;
188         } else {
189             $chan{$chan}        =  1;
190         }
191     }
192
193     return %chan;
194 }
195
196 #####
197 #  Usage: &IsChanConf($param);
198 #  About: Check for 'param' on the basis of channel config.
199 # Return: 1 for enabled, 0 for passive disable, -1 for active disable.
200 sub IsChanConf {
201     my($param)  = shift;
202     my $debug   = 0;    # knocked tons of bugs with this! :)
203
204     if (!defined $param) {
205         &WARN("IsChanConf: param == NULL.");
206         return 0;
207     }
208
209     $chan       ||= "_default";
210
211     my $old = $chan;
212     if ($chan =~ tr/A-Z/a-z/) {
213         &WARN("IsChanConf: lowercased chan. ($old)");
214     }
215
216     ### TODO: VERBOSITY on how chanconf returned 1 or 0 or -1.
217     my %chan    = &getChanConfList($param);
218     my $nomatch = 0;
219     if (!defined $msgType) {
220         $nomatch++;
221     } else {
222         $nomatch++ if ($msgType eq "");
223         $nomatch++ unless ($msgType =~ /^(public|private)$/i);
224     }
225
226 ### debug purposes only.
227 #    &DEBUG("param => $param, msgType => $msgType.");
228 #    foreach (keys %chan) {
229 #       &DEBUG("   $_ => $chan{$_}");
230 #    }
231
232     if ($nomatch) {
233         if ($chan{$chan}) {
234             &DEBUG("ICC: other: $chan{$chan} (_default/$param)") if ($debug);
235         } elsif ($chan{_default}) {
236             &DEBUG("ICC: other: $chan{_default} (_default/$param)") if ($debug);
237         } else {
238             &DEBUG("ICC: other: 0 ($param)") if ($debug);
239         }
240
241         return $chan{$chan} || $chan{_default} || 0;
242     }
243
244     if ($msgType eq "public") {
245         if ($chan{$chan}) {
246             &DEBUG("ICC: public: $chan{$chan} ($chan/$param)") if ($debug);
247         } elsif ($chan{_default}) {
248             &DEBUG("ICC: public: $chan{_default} (_default/$param)") if ($debug);
249         } else {
250             &DEBUG("ICC: public: 0 ($param)") if ($debug);
251         }
252
253         return $chan{$chan} || $chan{_default} || 0;
254     }
255
256     if ($msgType eq "private") {
257         if ($chan{_default}) {
258             &DEBUG("ICC: private: $chan{_default} (_default/$param)") if ($debug);
259         } elsif ($chan{$chan}) {
260             &DEBUG("ICC: private: $chan{$chan} ($chan/$param) (hack)") if ($debug);
261         } else {
262             &DEBUG("ICC: private: 0 ($param)") if ($debug);
263         }
264
265         return $chan{$chan} || $chan{_default} || 0;
266     }
267
268     &DEBUG("ICC: no-match: 0/$param (msgType = $msgType)");
269
270     return 0;
271 }
272
273 #####
274 #  Usage: &getChanConf($param);
275 #  About: Retrieve value for 'param' value in current/default chan.
276 # Return: scalar for success, undef for failure.
277 sub getChanConf {
278     my($param,$c)       = @_;
279
280     if (!defined $param) {
281         &WARN("param == NULL.");
282         return 0;
283     }
284
285     # this looks evil... 
286     if (0 and !defined $chan) {
287         &DEBUG("gCC: ok !chan... doing _default instead.");
288     }
289
290     $c          ||= $chan;
291     $c          ||= "_default";
292     $c          = "_default" if ($c eq "*");    # fix!
293     my @c       = grep /^$c$/i, keys %chanconf;
294
295     if (@c) {
296         if (0 and $c[0] ne $c) {
297             &WARN("c ne chan ($c[0] ne $chan)");
298         }
299         return $chanconf{$c[0]}{$param};
300     }
301
302 #    &DEBUG("gCC: returning _default... ");
303     return $chanconf{"_default"}{$param};
304 }
305
306 sub getChanConfDefault {
307     my($what, $default, $chan) = @_;
308
309     if (exists $param{$what}) {
310         if (!exists $cache{config}{$what}) {
311             &status("conf: backward-compat: found param{$what} ($param{$what}) instead.");
312             $cache{config}{$what} = 1;
313         }
314
315         return $param{$what};
316     }
317     my $val = &getChanConf($what, $chan);
318     return $val if (defined $val);
319
320     $param{$what}       = $default;
321     &status("conf: auto-setting param{$what} = $default");
322     $cache{config}{$what} = 1;
323     return $default;
324 }
325
326
327 #####
328 #  Usage: &findChanConf($param);
329 #  About: Retrieve value for 'param' value from any chan.
330 # Return: scalar for success, undef for failure.
331 sub findChanConf {
332     my($param)  = @_;
333
334     if (!defined $param) {
335         &WARN("param == NULL.");
336         return 0;
337     }
338
339     my $c;
340     foreach $c (keys %chanconf) {
341         foreach (keys %{ $chanconf{$c} }) {
342             next unless (/^$param$/);
343
344             &DEBUG("chanconf{$c}{$_} ...");
345             return $chanconf{$c}{$_};
346         }
347     }
348
349     return;
350 }
351
352 sub showProc {
353     my ($prefix) = $_[0] || "";
354
355     if ($^O eq "linux") {
356         if (!open(IN, "/proc/$$/status")) {
357             &ERROR("cannot open '/proc/$$/status'.");
358             return;
359         }
360
361         while (<IN>) {
362             $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
363         }
364         close IN;
365
366     } elsif ($^O eq "netbsd") {
367         $memusage = (stat "/proc/$$/mem")[7]/1024;
368
369     } elsif ($^O =~ /^(free|open)bsd$/) {
370         my @info  = split /\s+/, `/bin/ps -l -p $$`;
371         $memusage = $info[20];
372
373     } else {
374         $memusage = "UNKNOWN";
375         return;
376     }
377
378     if (defined $memusageOld and &IsParam("DEBUG")) {
379         # it's always going to be increase.
380         my $delta = $memusage - $memusageOld;
381         my $str;
382         if ($delta == 0) {
383             return;
384         } elsif ($delta > 500) {
385             $str = "MEM:$prefix increased by $delta kB. (total: $memusage kB)";
386         } elsif ($delta > 0) {
387             $str = "MEM:$prefix increased by $delta kB";
388         } else {        # delta < 0.
389             $delta = -$delta;
390             # never knew RSS could decrease, probably Size can't?
391             $str = "MEM:$prefix decreased by $delta kB.";
392         }
393
394         &status($str);
395     }
396     $memusageOld = $memusage;
397 }
398
399 ######
400 ###### SETUP
401 ######
402
403 sub setup {
404     &showProc(" (\&openLog before)");
405     &openLog();         # write, append.
406     &status("--- Started logging.");
407
408     foreach ("debian") {
409         my $dir = "$bot_base_dir/$_/";
410         next if ( -d $dir);
411         &status("Making dir $_");
412         mkdir $dir, 0755;
413     }
414
415     # read.
416     &loadLang($bot_data_dir. "/blootbot.lang");
417     &loadIRCServers();
418     &readUserFile();
419     &readChanFile();
420     &loadMyModulesNow();        # must be after chan file.
421
422     $shm = &openSHM();
423     &openSQLDebug()     if (&IsParam("SQLDebug"));
424     &openDB($param{'DBName'}, $param{'SQLUser'}, $param{'SQLPass'});
425     &checkTables();
426
427     &status("Setup: ". &countKeys("factoids") ." factoids.");
428     &News::readNews() if (&ChanConfList("news"));
429     &getChanConfDefault("sendPrivateLimitLines", 3);
430     &getChanConfDefault("sendPrivateLimitBytes", 1000);
431     &getChanConfDefault("sendPublicLimitLines", 3);
432     &getChanConfDefault("sendPublicLimitBytes", 1000);
433     &getChanConfDefault("sendNoticeLimitLines", 3);
434     &getChanConfDefault("sendNoticeLimitBytes", 1000);
435
436     $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
437
438     &status("Initial memory usage: $memusage kB");
439     &status("-------------------------------------------------------");
440 }
441
442 sub setupConfig {
443     $param{'VERBOSITY'} = 1;
444     &loadConfig($bot_config_dir."/blootbot.config");
445
446     foreach ("ircNick", "ircUser", "ircName", "DBType", "tempDir") {
447         next if &IsParam($_);
448         &ERROR("Parameter $_ has not been defined.");
449         exit 1;
450     }
451
452     if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
453         &VERB("Fixing up tempDir.",2);
454     }
455
456     if ($param{tempDir} =~ /~/) {
457         &ERROR("parameter tempDir still contains tilde.");
458         exit 1;
459     }
460
461     if (! -d $param{tempDir}) {
462         &status("making $param{tempDir}...");
463         mkdir $param{tempDir}, 0755;
464     }
465
466     # static scalar variables.
467     $file{utm}  = "$bot_state_dir/$param{'ircUser'}.uptime";
468     $file{PID}  = "$bot_run_dir/$param{'ircUser'}.pid";
469 }
470
471 sub startup {
472     if (&IsParam("DEBUG")) {
473         &status("enabling debug diagnostics.");
474         ### I thought disabling this reduced memory usage by 1000 kB.
475         use diagnostics;
476     }
477
478     $count{'Question'}  = 0;
479     $count{'Update'}    = 0;
480     $count{'Dunno'}     = 0;
481     $count{'Moron'}     = 0;
482 }
483
484 sub shutdown {
485     # reverse order of &setup().
486     &status("--- shutdown called.");
487
488     $ident ||=  "blootbot";     # hack.
489
490     # opened files must be written to on shutdown/hup/whatever
491     # unless they're write-only, like uptime.
492     &writeUserFile();
493     &writeChanFile();
494     &News::writeNews()  if (&ChanConfList("news"));
495
496     &closeDB();
497     &closeSHM($shm);    # aswell. TODO: use this in &doExit?
498     &closeLog();
499 }
500
501 sub restart {
502     my ($sig) = @_;
503
504     if ($$ == $bot_pid) {
505         &status("--- $sig called.");
506
507         ### crappy bug in Net::IRC?
508         if (!$conn->connected and time - $msgtime > 900) {
509             &status("reconnecting because of uncaught disconnect \@ ".scalar(localtime) );
510 ###         $irc->start;
511             &clearIRCVars();
512             $conn->connect();
513 ###         return;
514         }
515
516         &ircCheck();    # heh, evil!
517
518         &DCCBroadcast("-HUP called.","m");
519         &shutdown();
520         &loadConfig($bot_config_dir."/blootbot.config");
521         &reloadAllModules() if (&IsParam("DEBUG"));
522         &setup();
523
524         &status("--- End of $sig.");
525     } else {
526         &status("$sig called; ignoring restart.");
527     }
528 }
529
530 # File: Configuration.
531 sub loadConfig {
532     my ($file) = @_;
533
534     if (!open(FILE, $file)) {
535         &ERROR("Failed to read configuration file ($file): $!");
536         &status("Please read the INSTALL file on how to install and setup this file.");
537         exit 0;
538     }
539
540     my $count = 0;
541     while (<FILE>) {
542         chomp;
543         next if /^\s*\#/;
544         next unless /\S/;
545         my ($set,$key,$val) = split(/\s+/, $_, 3);
546
547         if ($set ne "set") {
548             &status("loadConfig: invalid line '$_'.");
549             next;
550         }
551
552         # perform variable interpolation
553         $val =~ s/(\$(\w+))/$param{$2}/g;
554
555         $param{$key} = $val;
556
557         ++$count;
558     }
559     close FILE;
560
561     $file =~ s/^.*\///;
562     &status("Loaded config $file ($count items)");
563 }
564
565 1;