]> git.donarmstrong.com Git - infobot.git/blob - src/core.pl
default to _default
[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     $chan       ||= "_default";
320
321     if (exists $param{$what}) {
322         if (!exists $cache{config}{$what}) {
323             &status("conf: backward-compat: found param{$what} ($param{$what}) for $chan instead.");
324             $cache{config}{$what} = 1;
325         }
326
327         return $param{$what};
328     }
329     my $val = &getChanConf($what, $chan);
330     return $val if (defined $val);
331
332     $param{$what}       = $default;
333     &status("conf: $chan auto-setting param{$what} = $default");
334     $cache{config}{$what} = 1;
335     return $default;
336 }
337
338
339 #####
340 #  Usage: &findChanConf($param);
341 #  About: Retrieve value for 'param' value from any chan.
342 # Return: scalar for success, undef for failure.
343 sub findChanConf {
344     my($param)  = @_;
345
346     if (!defined $param) {
347         &WARN("param == NULL.");
348         return 0;
349     }
350
351     my $c;
352     foreach $c (keys %chanconf) {
353         foreach (keys %{ $chanconf{$c} }) {
354             next unless (/^$param$/);
355
356             return $chanconf{$c}{$_};
357         }
358     }
359
360     return;
361 }
362
363 sub showProc {
364     my ($prefix) = $_[0] || "";
365
366     if ($^O eq "linux") {
367         if (!open(IN, "/proc/$$/status")) {
368             &ERROR("cannot open '/proc/$$/status'.");
369             return;
370         }
371
372         while (<IN>) {
373             $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
374         }
375         close IN;
376
377     } elsif ($^O eq "netbsd") {
378         $memusage = (stat "/proc/$$/mem")[7]/1024;
379
380     } elsif ($^O =~ /^(free|open)bsd$/) {
381         my @info  = split /\s+/, `/bin/ps -l -p $$`;
382         $memusage = $info[20];
383
384     } else {
385         $memusage = "UNKNOWN";
386         return;
387     }
388
389     if (defined $memusageOld and &IsParam("DEBUG")) {
390         # it's always going to be increase.
391         my $delta = $memusage - $memusageOld;
392         my $str;
393         if ($delta == 0) {
394             return;
395         } elsif ($delta > 500) {
396             $str = "MEM:$prefix increased by $delta kB. (total: $memusage kB)";
397         } elsif ($delta > 0) {
398             $str = "MEM:$prefix increased by $delta kB";
399         } else {        # delta < 0.
400             $delta = -$delta;
401             # never knew RSS could decrease, probably Size can't?
402             $str = "MEM:$prefix decreased by $delta kB.";
403         }
404
405         &status($str);
406     }
407     $memusageOld = $memusage;
408 }
409
410 ######
411 ###### SETUP
412 ######
413
414 sub setup {
415     &showProc(" (\&openLog before)");
416     &openLog();         # write, append.
417     &status("--- Started logging.");
418
419     # read.
420     &loadLang($bot_data_dir. "/blootbot.lang");
421     &loadIRCServers();
422     &readUserFile();
423     &readChanFile();
424     &loadMyModulesNow();        # must be after chan file.
425
426     $shm = &openSHM();
427     &openSQLDebug()     if (&IsParam("SQLDebug"));
428     &openDB($param{'DBName'}, $param{'SQLUser'}, $param{'SQLPass'});
429     &checkTables();
430
431     &status("Setup: ". &countKeys("factoids") ." factoids.");
432     &News::readNews() if (&ChanConfList("news"));
433     &getChanConfDefault("sendPrivateLimitLines", 3);
434     &getChanConfDefault("sendPrivateLimitBytes", 1000);
435     &getChanConfDefault("sendPublicLimitLines", 3);
436     &getChanConfDefault("sendPublicLimitBytes", 1000);
437     &getChanConfDefault("sendNoticeLimitLines", 3);
438     &getChanConfDefault("sendNoticeLimitBytes", 1000);
439
440     $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
441
442     &status("Initial memory usage: $memusage kB");
443     &status("-------------------------------------------------------");
444 }
445
446 sub setupConfig {
447     $param{'VERBOSITY'} = 1;
448     &loadConfig($bot_config_dir."/blootbot.config");
449
450     foreach ( qw(ircNick ircUser ircName DBType tempDir) ) {
451         next if &IsParam($_);
452         &ERROR("Parameter $_ has not been defined.");
453         exit 1;
454     }
455
456     if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
457         &VERB("Fixing up tempDir.",2);
458     }
459
460     if ($param{tempDir} =~ /~/) {
461         &ERROR("parameter tempDir still contains tilde.");
462         exit 1;
463     }
464
465     if (! -d $param{tempDir}) {
466         &status("making $param{tempDir}...");
467         mkdir $param{tempDir}, 0755;
468     }
469
470     # static scalar variables.
471     $file{utm}  = "$bot_state_dir/$param{'ircUser'}.uptime";
472     $file{PID}  = "$bot_run_dir/$param{'ircUser'}.pid";
473 }
474
475 sub startup {
476     if (&IsParam("DEBUG")) {
477         &status("enabling debug diagnostics.");
478         ### I thought disabling this reduced memory usage by 1000 kB.
479         use diagnostics;
480     }
481
482     $count{'Question'}  = 0;
483     $count{'Update'}    = 0;
484     $count{'Dunno'}     = 0;
485     $count{'Moron'}     = 0;
486 }
487
488 sub shutdown {
489     # reverse order of &setup().
490     &status("--- shutdown called.");
491
492     $ident ||=  "blootbot";     # hack.
493
494     # opened files must be written to on shutdown/hup/whatever
495     # unless they're write-only, like uptime.
496     &writeUserFile();
497     &writeChanFile();
498     &News::writeNews()  if (&ChanConfList("news"));
499
500     &closeDB();
501     &closeSHM($shm);    # aswell. TODO: use this in &doExit?
502     &closeLog();
503 }
504
505 sub restart {
506     my ($sig) = @_;
507
508     if ($$ == $bot_pid) {
509         &status("--- $sig called.");
510
511         ### crappy bug in Net::IRC?
512         if (!$conn->connected and time - $msgtime > 900) {
513             &status("reconnecting because of uncaught disconnect \@ ".scalar(localtime) );
514 ###         $irc->start;
515             &clearIRCVars();
516             $conn->connect();
517 ###         return;
518         }
519
520         &ircCheck();    # heh, evil!
521
522         &DCCBroadcast("-HUP called.","m");
523         &shutdown();
524         &loadConfig($bot_config_dir."/blootbot.config");
525         &reloadAllModules() if (&IsParam("DEBUG"));
526         &setup();
527
528         &status("--- End of $sig.");
529     } else {
530         &status("$sig called; ignoring restart.");
531     }
532 }
533
534 # File: Configuration.
535 sub loadConfig {
536     my ($file) = @_;
537
538     if (!open(FILE, $file)) {
539         &ERROR("Failed to read configuration file ($file): $!");
540         &status("Please read the INSTALL file on how to install and setup this file.");
541         exit 0;
542     }
543
544     my $count = 0;
545     while (<FILE>) {
546         chomp;
547         next if /^\s*\#/;
548         next unless /\S/;
549         my ($set,$key,$val) = split(/\s+/, $_, 3);
550
551         if ($set ne "set") {
552             &status("loadConfig: invalid line '$_'.");
553             next;
554         }
555
556         # perform variable interpolation
557         $val =~ s/(\$(\w+))/$param{$2}/g;
558
559         $param{$key} = $val;
560
561         ++$count;
562     }
563     close FILE;
564
565     $file =~ s/^.*\///;
566     &status("Loaded config $file ($count items)");
567 }
568
569 1;