]> git.donarmstrong.com Git - infobot.git/blob - src/core.pl
- irctextcounters: add percentage to top3
[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
23         $msgsize $msgcount $msgtime
24         $notsize $notcount $nottime
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       = 0;
63 $pubtime        = 0;
64 $pubsize        = 0;
65 $pubcount       = 0;
66 $nottime        = 0;
67 $notsize        = 0;
68 $notcount       = 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         &closeStats();
103         &seenFlush();
104         &quit($param{'quitMsg'}) if (&whatInterface() =~ /IRC/);
105         &writeUserFile();
106         &writeChanFile();
107         &uptimeWriteFile()      if (&ChanConfList("uptime"));
108         &News::writeNews()      if (&ChanConfList("news"));
109         &closeDB();
110         &closeSHM($shm);
111         &dumpallvars()          if (&IsParam("dumpvarsAtExit"));
112         &closeLog();
113         &closeSQLDebug()        if (&IsParam("SQLDebug"));
114
115         &status("--- QUIT.");
116     } else {                                    # child.
117         &status("child caught SIG$sig (pid $$).");
118     }
119
120     exit 0;
121 }
122
123 sub doWarn {
124     $SIG{__WARN__} = sub { warn $_[0]; };
125
126     foreach (@_) {
127         &WARN("PERL: $_");
128     }
129
130     $SIG{__WARN__} = 'doWarn';  # ???
131 }
132
133 # Usage: &IsParam($param);
134 # blootbot.config specific.
135 sub IsParam {
136     my $param = $_[0];
137
138     return 0 unless (defined $param);
139     return 0 unless (exists $param{$param});
140     return 0 unless ($param{$param});
141     return 0 if $param{$param} =~ /^false$/i;
142     return 1;
143 }
144
145 #####
146 #  Usage: &ChanConfList($param)
147 #  About: gets channels with 'param' enabled. (!!!)
148 # Return: array of channels
149 sub ChanConfList {
150     my $param   = $_[0];
151     return unless (defined $param);
152     my %chan    = &getChanConfList($param);
153
154     if (exists $chan{_default}) {
155         return keys %chanconf;
156     } else {
157         return keys %chan;
158     }
159 }
160
161 #####
162 #  Usage: &getChanConfList($param)
163 #  About: gets channels with 'param' enabled, internal use only.
164 # Return: hash of channels
165 sub getChanConfList {
166     my $param   = $_[0];
167     my %chan;
168
169     return unless (defined $param);
170
171     foreach (keys %chanconf) {
172         my $chan        = $_;
173 #       &DEBUG("chan => $chan");
174         my @array       = grep /^$param$/, keys %{ $chanconf{$chan} };
175
176         next unless (scalar @array);
177
178         if (scalar @array > 1) {
179             &WARN("multiple items found?");
180         }
181
182         if ($array[0] eq "0") {
183             $chan{$chan}        = -1;
184         } else {
185             $chan{$chan}        =  1;
186         }
187     }
188
189     return %chan;
190 }
191
192 #####
193 #  Usage: &IsChanConf($param);
194 #  About: Check for 'param' on the basis of channel config.
195 # Return: 1 for enabled, 0 for passive disable, -1 for active disable.
196 sub IsChanConf {
197     my($param)  = shift;
198     my $debug   = 0;    # knocked tons of bugs with this! :)
199
200     if (!defined $param) {
201         &WARN("IsChanConf: param == NULL.");
202         return 0;
203     }
204
205     $chan       ||= "_default";
206
207     my $old = $chan;
208     if ($chan =~ tr/A-Z/a-z/) {
209         &WARN("IsChanConf: lowercased chan. ($old)");
210     }
211
212     ### TODO: VERBOSITY on how chanconf returned 1 or 0 or -1.
213     my %chan    = &getChanConfList($param);
214     my $nomatch = 0;
215     if (!defined $msgType) {
216         $nomatch++;
217     } else {
218         $nomatch++ if ($msgType eq "");
219         $nomatch++ unless ($msgType =~ /^(public|private)$/i);
220     }
221
222 ### debug purposes only.
223 #    &DEBUG("param => $param, msgType => $msgType.");
224 #    foreach (keys %chan) {
225 #       &DEBUG("   $_ => $chan{$_}");
226 #    }
227
228     if ($nomatch) {
229         if ($chan{$chan}) {
230             &DEBUG("ICC: other: $chan{$chan} (_default/$param)") if ($debug);
231         } elsif ($chan{_default}) {
232             &DEBUG("ICC: other: $chan{_default} (_default/$param)") if ($debug);
233         } else {
234             &DEBUG("ICC: other: 0 ($param)") if ($debug);
235         }
236
237         return $chan{$chan} || $chan{_default} || 0;
238     }
239
240     if ($msgType eq "public") {
241         if ($chan{$chan}) {
242             &DEBUG("ICC: public: $chan{$chan} ($chan/$param)") if ($debug);
243         } elsif ($chan{_default}) {
244             &DEBUG("ICC: public: $chan{_default} (_default/$param)") if ($debug);
245         } else {
246             &DEBUG("ICC: public: 0 ($param)") if ($debug);
247         }
248
249         return $chan{$chan} || $chan{_default} || 0;
250     }
251
252     if ($msgType eq "private") {
253         if ($chan{_default}) {
254             &DEBUG("ICC: private: $chan{_default} (_default/$param)") if ($debug);
255         } elsif ($chan{$chan}) {
256             &DEBUG("ICC: private: $chan{$chan} ($chan/$param) (hack)") if ($debug);
257         } else {
258             &DEBUG("ICC: private: 0 ($param)") if ($debug);
259         }
260
261         return $chan{$chan} || $chan{_default} || 0;
262     }
263
264     &DEBUG("ICC: no-match: 0/$param (msgType = $msgType)");
265
266     return 0;
267 }
268
269 #####
270 #  Usage: &getChanConf($param);
271 #  About: Retrieve value for 'param' value in current/default chan.
272 # Return: scalar for success, undef for failure.
273 sub getChanConf {
274     my($param,$c)       = @_;
275
276     if (!defined $param) {
277         &WARN("param == NULL.");
278         return 0;
279     }
280
281     # this looks evil... 
282     if (0 and !defined $chan) {
283         &DEBUG("gCC: ok !chan... doing _default instead.");
284     }
285
286     $c          ||= $chan;
287     $c          ||= "_default";
288     $c          = "_default" if ($c eq "*");    # fix!
289     my @c       = grep /^$c$/i, keys %chanconf;
290
291     if (@c) {
292         if (0 and $c[0] ne $c) {
293             &WARN("c ne chan ($c[0] ne $chan)");
294         }
295         return $chanconf{$c[0]}{$param};
296     }
297
298 #    &DEBUG("gCC: returning _default... ");
299     return $chanconf{"_default"}{$param};
300 }
301
302 sub showProc {
303     my ($prefix) = $_[0] || "";
304
305     if (!open(IN, "/proc/$$/status")) {
306         &ERROR("cannot open '/proc/$$/status'.");
307         return;
308     }
309
310     if ($^O eq "linux") {
311         while (<IN>) {
312             $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
313         }
314         close IN;
315
316     } elsif ($^O eq "netbsd") {
317         $memusage = (stat "/proc/$$/mem")[7]/1024;
318
319     } elsif ($^O =~ /^(free|open)bsd$/) {
320         my @info  = split /\s+/, `/bin/ps -l -p $$`;
321         $memusage = $info[20];
322
323     } else {
324         $memusage = "UNKNOWN";
325         return;
326     }
327
328     if (defined $memusageOld and &IsParam("DEBUG")) {
329         # it's always going to be increase.
330         my $delta = $memusage - $memusageOld;
331         my $str;
332         if ($delta == 0) {
333             return;
334         } elsif ($delta > 500) {
335             $str = "MEM:$prefix increased by $delta kB. (total: $memusage kB)";
336         } elsif ($delta > 0) {
337             $str = "MEM:$prefix increased by $delta kB";
338         } else {        # delta < 0.
339             $delta = -$delta;
340             # never knew RSS could decrease, probably Size can't?
341             $str = "MEM:$prefix decreased by $delta kB. YES YES YES";
342         }
343
344         &status($str);
345     }
346     $memusageOld = $memusage;
347 }
348
349 ######
350 ###### SETUP
351 ######
352
353 sub setup {
354     &showProc(" (\&openLog before)");
355     &openLog();         # write, append.
356     &status("--- Started logging.");
357
358     foreach ("debian") {
359         my $dir = "$bot_base_dir/$_/";
360         next if ( -d $dir);
361         &status("Making dir $_");
362         mkdir $dir, 0755;
363     }
364
365     # read.
366     &loadLang($bot_misc_dir.            "/blootbot.lang");
367     &loadIRCServers();
368     &readUserFile();
369     &readChanFile();
370     &loadMyModulesNow();        # must be after chan file.
371
372     $shm = &openSHM();
373     &openSQLDebug()     if (&IsParam("SQLDebug"));
374     &openDB($param{'DBName'}, $param{'SQLUser'}, $param{'SQLPass'});
375     &checkTables();
376
377     &status("Setup: ". &countKeys("factoids") ." factoids.");
378     &News::readNews() if (&ChanConfList("news"));
379     &getChanConfDefault("sendPrivateLimitLines", 3);
380     &getChanConfDefault("sendPrivateLimitBytes", 1000);
381     &getChanConfDefault("sendPublicLimitLines", 3);
382     &getChanConfDefault("sendPublicLimitBytes", 1000);
383     &getChanConfDefault("sendNoticeLimitLines", 3);
384     &getChanConfDefault("sendNoticeLimitBytes", 1000);
385
386     $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
387
388     &status("Initial memory usage: $memusage kB");
389     &status("-------------------------------------------------------");
390 }
391
392 sub setupConfig {
393     $param{'VERBOSITY'} = 1;
394     &loadConfig($bot_misc_dir."/blootbot.config");
395
396     foreach ("ircNick", "ircUser", "ircName", "DBType", "tempDir") {
397         next if &IsParam($_);
398         &ERROR("Parameter $_ has not been defined.");
399         exit 1;
400     }
401
402     if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
403         &VERB("Fixing up tempDir.",2);
404     }
405
406     if ($param{tempDir} =~ /~/) {
407         &ERROR("parameter tempDir still contains tilde.");
408         exit 1;
409     }
410
411     if (! -d $param{tempDir}) {
412         &status("making $param{tempDir}...");
413         system("mkdir $param{tempDir}");
414     }
415
416     # static scalar variables.
417     $file{utm}  = "$bot_base_dir/$param{'ircUser'}.uptime";
418     $file{PID}  = "$bot_base_dir/$param{'ircUser'}.pid";
419 }
420
421 sub startup {
422     if (&IsParam("DEBUG")) {
423         &status("enabling debug diagnostics.");
424         ### I thought disabling this reduced memory usage by 1000 kB.
425         use diagnostics;
426     }
427
428     $count{'Question'}  = 0;
429     $count{'Update'}    = 0;
430     $count{'Dunno'}     = 0;
431     $count{'Moron'}     = 0;
432 }
433
434 sub shutdown {
435     # reverse order of &setup().
436     &status("--- shutdown called.");
437
438     $ident ||=  "blootbot";     # hack.
439
440     # opened files must be written to on shutdown/hup/whatever
441     # unless they're write-only, like uptime.
442     &writeUserFile();
443     &writeChanFile();
444     &News::writeNews()  if (&ChanConfList("news"));
445
446     &closeDB();
447     &closeSHM($shm);    # aswell. TODO: use this in &doExit?
448     &closeLog();
449 }
450
451 sub restart {
452     my ($sig) = @_;
453
454     if ($$ == $bot_pid) {
455         &status("--- $sig called.");
456
457         ### crappy bug in Net::IRC?
458         if (!$conn->connected and time - $msgtime > 900) {
459             &status("reconnecting because of uncaught disconnect \@ ".scalar(localtime) );
460 ###         $irc->start;
461             $conn->connect();
462 ###         return;
463         }
464
465         &ircCheck();    # heh, evil!
466
467         &DCCBroadcast("-HUP called.","m");
468         &shutdown();
469         &loadConfig($bot_misc_dir."/blootbot.config");
470         &reloadAllModules() if (&IsParam("DEBUG"));
471         &setup();
472
473         &status("--- End of $sig.");
474     } else {
475         &status("$sig called; ignoring restart.");
476     }
477 }
478
479 # File: Configuration.
480 sub loadConfig {
481     my ($file) = @_;
482
483     if (!open(FILE, $file)) {
484         &ERROR("FAILED loadConfig ($file): $!");
485         &status("Please copy files/sample.config to files/blootbot.config");
486         &status("  and edit files/blootbot.config, modify to tastes.");
487         exit 0;
488     }
489
490     my $count = 0;
491     while (<FILE>) {
492         chomp;
493         next if /^\s*\#/;
494         next unless /\S/;
495         my ($set,$key,$val) = split(/\s+/, $_, 3);
496
497         if ($set ne "set") {
498             &status("loadConfig: invalid line '$_'.");
499             next;
500         }
501
502         # perform variable interpolation
503         $val =~ s/(\$(\w+))/$param{$2}/g;
504
505         $param{$key} = $val;
506
507         ++$count;
508     }
509     close FILE;
510
511     $file =~ s/^.*\///;
512     &status("Loaded config $file ($count items)");
513 }
514
515 1;