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