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