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