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