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