]> git.donarmstrong.com Git - infobot.git/blob - src/core.pl
- fixed "news #debian latest" - how did I break it?
[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         &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,$c)       = @_;
272
273     if (!defined $param) {
274         &WARN("param == NULL.");
275         return 0;
276     }
277
278     # this looks evil... 
279     if (0 and !defined $chan) {
280         &DEBUG("gCC: ok !chan... doing _default instead.");
281     }
282
283     $c          ||= $chan;
284     $c          ||= "_default";
285     $c          = "_default" if ($c eq "*");    # fix!
286     my @c       = grep /^$c$/i, keys %chanconf;
287
288     if (@c) {
289         if (0 and $c[0] ne $c) {
290             &WARN("c ne chan ($c[0] ne $chan)");
291         }
292         return $chanconf{$c[0]}{$param};
293     }
294
295 #    &DEBUG("gCC: returning _default... ");
296     return $chanconf{"_default"}{$param};
297 }
298
299 sub showProc {
300     my ($prefix) = $_[0] || "";
301
302     if (!open(IN, "/proc/$$/status")) {
303         &ERROR("cannot open '/proc/$$/status'.");
304         return;
305     }
306
307     if ($^O eq "linux") {
308         while (<IN>) {
309             $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
310         }
311         close IN;
312
313     } elsif ($^O eq "netbsd") {
314         $memusage = (stat "/proc/$$/mem")[7]/1024;
315
316     } elsif ($^O =~ /^(free|open)bsd$/) {
317         my @info  = split /\s+/, `/bin/ps -l -p $$`;
318         $memusage = $info[20];
319
320     } else {
321         $memusage = "UNKNOWN";
322         return;
323     }
324
325     if (defined $memusageOld and &IsParam("DEBUG")) {
326         # it's always going to be increase.
327         my $delta = $memusage - $memusageOld;
328         my $str;
329         if ($delta == 0) {
330             return;
331         } elsif ($delta > 500) {
332             $str = "MEM:$prefix increased by $delta kB. (total: $memusage kB)";
333         } elsif ($delta > 0) {
334             $str = "MEM:$prefix increased by $delta kB";
335         } else {        # delta < 0.
336             $delta = -$delta;
337             # never knew RSS could decrease, probably Size can't?
338             $str = "MEM:$prefix decreased by $delta kB. YES YES YES";
339         }
340
341         &status($str);
342     }
343     $memusageOld = $memusage;
344 }
345
346 ######
347 ###### SETUP
348 ######
349
350 sub setup {
351     &showProc(" (\&openLog before)");
352     &openLog();         # write, append.
353     &status("--- Started logging.");
354
355     foreach ("debian") {
356         my $dir = "$bot_base_dir/$_/";
357         next if ( -d $dir);
358         &status("Making dir $_");
359         mkdir $dir, 0755;
360     }
361
362     # read.
363     &loadLang($bot_misc_dir.            "/blootbot.lang");
364     &loadIRCServers();
365     &readUserFile();
366     &readChanFile();
367     &loadMyModulesNow();        # must be after chan file.
368
369     $shm = &openSHM();
370     &openSQLDebug()     if (&IsParam("SQLDebug"));
371     &openDB($param{'DBName'}, $param{'SQLUser'}, $param{'SQLPass'});
372     &checkTables();
373
374     &status("Setup: ". &countKeys("factoids") ." factoids.");
375     &News::readNews() if (&ChanConfList("news"));
376     &getChanConfDefault("sendPrivateLimitLines", 3);
377     &getChanConfDefault("sendPrivateLimitBytes", 1000);
378     &getChanConfDefault("sendPublicLimitLines", 3);
379     &getChanConfDefault("sendPublicLimitBytes", 1000);
380     &getChanConfDefault("sendNoticeLimitLines", 3);
381     &getChanConfDefault("sendNoticeLimitBytes", 1000);
382
383     $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
384
385     &status("Initial memory usage: $memusage kB");
386     &status("-------------------------------------------------------");
387 }
388
389 sub setupConfig {
390     $param{'VERBOSITY'} = 1;
391     &loadConfig($bot_misc_dir."/blootbot.config");
392
393     foreach ("ircNick", "ircUser", "ircName", "DBType", "tempDir") {
394         next if &IsParam($_);
395         &ERROR("Parameter $_ has not been defined.");
396         exit 1;
397     }
398
399     if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
400         &VERB("Fixing up tempDir.",2);
401     }
402
403     if ($param{tempDir} =~ /~/) {
404         &ERROR("parameter tempDir still contains tilde.");
405         exit 1;
406     }
407
408     if (! -d $param{tempDir}) {
409         &status("making $param{tempDir}...");
410         system("mkdir $param{tempDir}");
411     }
412
413     # static scalar variables.
414     $file{utm}  = "$bot_base_dir/$param{'ircUser'}.uptime";
415     $file{PID}  = "$bot_base_dir/$param{'ircUser'}.pid";
416 }
417
418 sub startup {
419     if (&IsParam("DEBUG")) {
420         &status("enabling debug diagnostics.");
421         ### I thought disabling this reduced memory usage by 1000 kB.
422         use diagnostics;
423     }
424
425     $count{'Question'}  = 0;
426     $count{'Update'}    = 0;
427     $count{'Dunno'}     = 0;
428     $count{'Moron'}     = 0;
429 }
430
431 sub shutdown {
432     # reverse order of &setup().
433     &status("--- shutdown called.");
434
435     $ident ||=  "blootbot";     # hack.
436
437     # opened files must be written to on shutdown/hup/whatever
438     # unless they're write-only, like uptime.
439     &writeUserFile();
440     &writeChanFile();
441     &News::writeNews()  if (&ChanConfList("news"));
442
443     &closeDB();
444     &closeSHM($shm);    # aswell. TODO: use this in &doExit?
445     &closeLog();
446 }
447
448 sub restart {
449     my ($sig) = @_;
450
451     if ($$ == $bot_pid) {
452         &status("--- $sig called.");
453
454         ### crappy bug in Net::IRC?
455         if (!$conn->connected and time - $msgtime > 900) {
456             &status("reconnecting because of uncaught disconnect.");
457 ###         $irc->start;
458             $conn->connect();
459 ###         return;
460         }
461
462         &ircCheck();    # heh, evil!
463
464         &DCCBroadcast("-HUP called.","m");
465         &shutdown();
466         &loadConfig($bot_misc_dir."/blootbot.config");
467         &reloadAllModules() if (&IsParam("DEBUG"));
468         &setup();
469
470         &status("--- End of $sig.");
471     } else {
472         &status("$sig called; ignoring restart.");
473     }
474 }
475
476 # File: Configuration.
477 sub loadConfig {
478     my ($file) = @_;
479
480     if (!open(FILE, $file)) {
481         &ERROR("FAILED loadConfig ($file): $!");
482         &status("Please copy files/sample.config to files/blootbot.config");
483         &status("  and edit files/blootbot.config, modify to tastes.");
484         exit 0;
485     }
486
487     my $count = 0;
488     while (<FILE>) {
489         chomp;
490         next if /^\s*\#/;
491         next unless /\S/;
492         my ($set,$key,$val) = split(/\s+/, $_, 3);
493
494         if ($set ne "set") {
495             &status("loadConfig: invalid line '$_'.");
496             next;
497         }
498
499         # perform variable interpolation
500         $val =~ s/(\$(\w+))/$param{$2}/g;
501
502         $param{$key} = $val;
503
504         ++$count;
505     }
506     close FILE;
507
508     $file =~ s/^.*\///;
509     &status("Loaded config $file ($count items)");
510 }
511
512 1;