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