]> git.donarmstrong.com Git - infobot.git/blob - src/core.pl
- forgot to set forked{}{PID} in addForked
[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         $answer $correction_plausible $talkchannel
14         $statcount $memusage $user $memusageOld $bot_version $dbh
15         $shm $host $msg $bot_misc_dir $bot_pid $bot_base_dir $noreply
16         $bot_src_dir $conn $irc $learnok $nick $ident $no_syscall
17         $force_public_reply $addrchar $userHandle $addressedother
18         $floodwho $chan $msgtime $server $firsttime $wingaterun
19         $flag_quit $msgType
20         $utime_userfile $wtime_userfile $ucount_userfile
21         $utime_chanfile $wtime_chanfile $ucount_chanfile
22         $pubsize $pubcount $pubtime $pubsleep
23         $msgsize $msgcount $msgtime $msgsleep
24         $notsize $notcount $nottime $notsleep
25 );
26
27 # dynamic hash.
28 use vars qw(@joinchan @ircServers @wingateBad @wingateNow @wingateCache
29 );
30
31 ### dynamic hash. MUST BE REDUCED IN SIZE!!!
32
33 use vars qw(%count %netsplit %netsplitservers %flood %dcc %orig
34             %nuh %talkWho %seen %floodwarn %param %dbh %ircPort
35             %topic %moduleAge %last %time %mask %file
36             %forked %chanconf %channels
37 );
38
39 # Signals.
40 $SIG{'HUP'}  = 'restart'; #  1.
41 $SIG{'INT'}  = 'doExit';  #  2.
42 $SIG{'KILL'} = 'doExit';  #  9. DOES NOT WORK. 'man perlipc' for details.
43 $SIG{'TERM'} = 'doExit';  # 15.
44 $SIG{'__WARN__'} = 'doWarn';
45
46 # initialize variables.
47 $last{buflen}   = 0;
48 $last{say}      = "";
49 $last{msg}      = "";
50 $userHandle     = "default";
51 $wingaterun     = time();
52 $firsttime      = 1;
53 $utime_userfile = 0;
54 $wtime_userfile = 0;
55 $ucount_userfile = 0;
56 $utime_chanfile = 0;
57 $wtime_chanfile = 0;
58 $ucount_chanfile = 0;
59 ### more variables...
60 $msgtime        = time();
61 $msgsize        = 0;
62 $msgcount       = $msgsleep     = 0;
63 $pubtime        = 0;
64 $pubsize        = 0;
65 $pubcount       = $pubsleep     = 0;
66 $nottime        = 0;
67 $notsize        = 0;
68 $notcount       = $notsleep     = 0;
69 ###
70 $bot_version    = "blootbot cvs (20010214) -- $^O";
71 $noreply        = "NOREPLY";
72
73 ##########
74 ### misc commands.
75 ###
76
77 sub doExit {
78     my ($sig)   = @_;
79
80     if (defined $flag_quit) {
81         &WARN("doExit: quit already called.");
82         return;
83     }
84     $flag_quit  = 1;
85
86     if (!defined $bot_pid) {    # independent.
87         exit 0;
88     } elsif ($bot_pid == $$) {  # parent.
89         &status("parent caught SIG$sig (pid $$).") if (defined $sig);
90
91         &status("--- Start of quit.");
92
93         &closeDCC();
94         &closePID();
95         &seenFlush();
96         &quit($param{'quitMsg'}) if (&whatInterface() =~ /IRC/);
97         &writeUserFile();
98         &writeChanFile();
99         &uptimeWriteFile()      if (&ChanConfList("uptime"));
100         &News::writeNews()      if (&ChanConfList("news"));
101         &closeDB();
102         &closeSHM($shm);
103         &dumpallvars()          if (&IsParam("dumpvarsAtExit"));
104         &closeLog();
105         &closeSQLDebug()        if (&IsParam("SQLDebug"));
106
107         &status("--- QUIT.");
108     } else {                                    # child.
109         &status("child caught SIG$sig (pid $$).");
110     }
111
112     exit 0;
113 }
114
115 sub doWarn {
116     $SIG{__WARN__} = sub { warn $_[0]; };
117
118     foreach (@_) {
119         &WARN("PERL: $_");
120     }
121
122     $SIG{__WARN__} = 'doWarn';  # ???
123 }
124
125 # Usage: &IsParam($param);
126 # blootbot.config specific.
127 sub IsParam {
128     my $param = $_[0];
129
130     return 0 unless (defined $param);
131     return 0 unless (exists $param{$param});
132     return 0 unless ($param{$param});
133     return 0 if $param{$param} =~ /^false$/i;
134     return 1;
135 }
136
137 #####
138 #  Usage: &ChanConfList($param)
139 #  About: gets channels with 'param' enabled. (!!!)
140 # Return: array of channels
141 sub ChanConfList {
142     my $param   = $_[0];
143     return unless (defined $param);
144     my %chan    = &getChanConfList($param);
145
146     if (exists $chan{_default}) {
147         return keys %chanconf;
148     } else {
149         return keys %chan;
150     }
151 }
152
153 #####
154 #  Usage: &getChanConfList($param)
155 #  About: gets channels with 'param' enabled, internal use only.
156 # Return: hash of channels
157 sub getChanConfList {
158     my $param   = $_[0];
159     my %chan;
160
161     return unless (defined $param);
162
163     foreach (keys %chanconf) {
164         my $chan        = $_;
165 #       &DEBUG("chan => $chan");
166         my @array       = grep /^$param$/, keys %{ $chanconf{$chan} };
167
168         next unless (scalar @array);
169
170         if (scalar @array > 1) {
171             &WARN("multiple items found?");
172         }
173
174         if ($array[0] eq "0") {
175             $chan{$chan}        = -1;
176         } else {
177             $chan{$chan}        =  1;
178         }
179     }
180
181     return %chan;
182 }
183
184 #####
185 #  Usage: &IsChanConf($param);
186 #  About: Check for 'param' on the basis of channel config.
187 # Return: 1 for enabled, 0 for passive disable, -1 for active disable.
188 sub IsChanConf {
189     my($param)  = shift;
190     my $debug   = 0;    # knocked tons of bugs with this! :)
191
192     if (!defined $param) {
193         &WARN("IsChanConf: param == NULL.");
194         return 0;
195     }
196
197     my $old = $chan;
198     if ($chan =~ tr/A-Z/a-z/) {
199         &WARN("IsChanConf: lowercased chan. ($old)");
200     }
201
202     ### TODO: VERBOSITY on how chanconf returned 1 or 0 or -1.
203     my %chan    = &getChanConfList($param);
204     my $nomatch = 0;
205     if (!defined $msgType) {
206         $nomatch++;
207     } else {
208         $nomatch++ if ($msgType eq "");
209         $nomatch++ unless ($msgType =~ /^(public|private)$/i);
210     }
211
212 ### debug purposes only.
213 #    &DEBUG("param => $param, msgType => $msgType.");
214 #    foreach (keys %chan) {
215 #       &DEBUG("   $_ => $chan{$_}");
216 #    }
217
218     if ($nomatch) {
219         if ($chan{$chan}) {
220             &DEBUG("ICC: other: $chan{$chan} (_default/$param)") if ($debug);
221         } elsif ($chan{_default}) {
222             &DEBUG("ICC: other: $chan{_default} (_default/$param)") if ($debug);
223         } else {
224             &DEBUG("ICC: other: 0 ($param)") if ($debug);
225         }
226
227         return $chan{$chan} || $chan{_default} || 0;
228     }
229
230     if ($msgType eq "public") {
231         if ($chan{$chan}) {
232             &DEBUG("ICC: public: $chan{$chan} ($chan/$param)") if ($debug);
233         } elsif ($chan{_default}) {
234             &DEBUG("ICC: public: $chan{_default} (_default/$param)") if ($debug);
235         } else {
236             &DEBUG("ICC: public: 0 ($param)") if ($debug);
237         }
238
239         return $chan{$chan} || $chan{_default} || 0;
240     }
241
242     if ($msgType eq "private") {
243         if ($chan{_default}) {
244             &DEBUG("ICC: private: $chan{_default} (_default/$param)") if ($debug);
245         } elsif ($chan{$chan}) {
246             &DEBUG("ICC: private: $chan{$chan} ($chan/$param) (hack)") if ($debug);
247         } else {
248             &DEBUG("ICC: private: 0 ($param)") if ($debug);
249         }
250
251         return $chan{$chan} || $chan{_default} || 0;
252     }
253
254     &DEBUG("ICC: no-match: 0/$param (msgType = $msgType)");
255
256     return 0;
257 }
258
259 #####
260 #  Usage: &getChanConf($param);
261 #  About: Retrieve value for 'param' value in current/default chan.
262 # Return: scalar for success, undef for failure.
263 sub getChanConf {
264     my($param,$chan)    = @_;
265
266     if (!defined $param) {
267         &WARN("param == NULL.");
268         return 0;
269     }
270
271     $chan       ||= "_default";
272     my @c       = grep /^$chan$/i, keys %chanconf;
273
274     if (@c) {
275         if ($c[0] ne $chan) {
276             &WARN("c ne chan ($c[0] ne $chan)");
277         }
278         return $chanconf{$c[0]}{$param};
279     }
280
281     return $chanconf{"_default"}{$param};
282 }
283
284 sub showProc {
285     my ($prefix) = $_[0] || "";
286
287     if (!open(IN, "/proc/$$/status")) {
288         &ERROR("cannot open '/proc/$$/status'.");
289         return;
290     }
291
292     if ($^O eq "linux") {
293         while (<IN>) {
294             $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
295         }
296         close IN;
297
298     } elsif ($^O eq "netbsd") {
299         $memusage = (stat "/proc/$$/mem")[7]/1024;
300
301     } elsif ($^O =~ /^(free|open)bsd$/) {
302         my @info  = split /\s+/, `/bin/ps -l -p $$`;
303         $memusage = $info[20];
304
305     } else {
306         $memusage = "UNKNOWN";
307         return;
308     }
309
310     if (defined $memusageOld and &IsParam("DEBUG")) {
311         # it's always going to be increase.
312         my $delta = $memusage - $memusageOld;
313         my $str;
314         if ($delta == 0) {
315             return;
316         } elsif ($delta > 500) {
317             $str = "MEM:$prefix increased by $delta kB. (total: $memusage kB)";
318         } elsif ($delta > 0) {
319             $str = "MEM:$prefix increased by $delta kB";
320         } else {        # delta < 0.
321             $delta = -$delta;
322             # never knew RSS could decrease, probably Size can't?
323             $str = "MEM:$prefix decreased by $delta kB. YES YES YES";
324         }
325
326         &status($str);
327     }
328     $memusageOld = $memusage;
329 }
330
331 ######
332 ###### SETUP
333 ######
334
335 sub setup {
336     &showProc(" (\&openLog before)");
337     &openLog();         # write, append.
338     &status("--- Started logging.");
339
340     foreach ("debian") {
341         my $dir = "$bot_base_dir/$_/";
342         next if ( -d $dir);
343         &status("Making dir $_");
344         mkdir $dir, 0755;
345     }
346
347     # read.
348     &loadLang($bot_misc_dir.            "/blootbot.lang");
349     &loadIRCServers();
350     &readUserFile();
351     &readChanFile();
352     &loadMyModulesNow();        # must be after chan file.
353
354     $shm = &openSHM();
355     &openSQLDebug()     if (&IsParam("SQLDebug"));
356     &openDB($param{'DBName'}, $param{'SQLUser'}, $param{'SQLPass'});
357
358     &status("Setup: ". &countKeys("factoids") ." factoids.");
359     &News::readNews() if (&ChanConfList("news"));
360     &getChanConfDefault("sendPrivateLimitLines", 3);
361     &getChanConfDefault("sendPrivateLimitBytes", 1000);
362     &getChanConfDefault("sendPublicLimitLines", 3);
363     &getChanConfDefault("sendPublicLimitBytes", 1000);
364     &getChanConfDefault("sendNoticeLimitLines", 3);
365     &getChanConfDefault("sendNoticeLimitBytes", 1000);
366
367     $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
368
369     &status("Initial memory usage: $memusage kB");
370 }
371
372 sub setupConfig {
373     $param{'VERBOSITY'} = 1;
374     &loadConfig($bot_misc_dir."/blootbot.config");
375
376     foreach ("ircNick", "ircUser", "ircName", "DBType", "tempDir") {
377         next if &IsParam($_);
378         &ERROR("Parameter $_ has not been defined.");
379         exit 1;
380     }
381
382     if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
383         &VERB("Fixing up tempDir.",2);
384     }
385
386     if ($param{tempDir} =~ /~/) {
387         &ERROR("parameter tempDir still contains tilde.");
388         exit 1;
389     }
390
391     if (! -d $param{tempDir}) {
392         &status("making $param{tempDir}...");
393         system("mkdir $param{tempDir}");
394     }
395
396     # static scalar variables.
397     $file{utm}  = "$bot_base_dir/$param{'ircUser'}.uptime";
398     $file{PID}  = "$bot_base_dir/$param{'ircUser'}.pid";
399 }
400
401 sub startup {
402     if (&IsParam("DEBUG")) {
403         &status("enabling debug diagnostics.");
404         ### I thought disabling this reduced memory usage by 1000 kB.
405         use diagnostics;
406     }
407
408     $count{'Question'}  = 0;
409     $count{'Update'}    = 0;
410     $count{'Dunno'}     = 0;
411     $count{'Moron'}     = 0;
412 }
413
414 sub shutdown {
415     # reverse order of &setup().
416     &DEBUG("shutdown called.");
417
418     # opened files must be written to on shutdown/hup/whatever
419     # unless they're write-only, like uptime.
420     &writeUserFile();
421     &writeChanFile();
422     &News::writeNews()  if (&ChanConfList("news"));
423
424     &closeDB();
425     &closeSHM($shm);    # aswell. TODO: use this in &doExit?
426     &closeLog();
427 }
428
429 sub restart {
430     my ($sig) = @_;
431
432     if ($$ == $bot_pid) {
433         &status("--- $sig called.");
434
435         ### crappy bug in Net::IRC?
436         if (!$conn->connected and time - $msgtime > 900) {
437             &status("reconnecting because of uncaught disconnect.");
438 ###         $irc->start;
439             $conn->connect();
440 ###         return;
441         }
442
443         &ircCheck();    # heh, evil!
444
445         &DCCBroadcast("-HUP called.","m");
446         &shutdown();
447         &loadConfig($bot_misc_dir."/blootbot.config");
448         &reloadAllModules() if (&IsParam("DEBUG"));
449         &setup();
450
451         &status("--- End of $sig.");
452     } else {
453         &status("$sig called; ignoring restart.");
454     }
455 }
456
457 # File: Configuration.
458 sub loadConfig {
459     my ($file) = @_;
460
461     if (!open(FILE, $file)) {
462         &ERROR("FAILED loadConfig ($file): $!");
463         &status("Please copy files/sample.config to files/blootbot.config");
464         &status("  and edit files/blootbot.config, modify to tastes.");
465         exit 0;
466     }
467
468     my $count = 0;
469     while (<FILE>) {
470         chomp;
471         next if /^\s*\#/;
472         next unless /\S/;
473         my ($set,$key,$val) = split(/\s+/, $_, 3);
474
475         if ($set ne "set") {
476             &status("loadConfig: invalid line '$_'.");
477             next;
478         }
479
480         # perform variable interpolation
481         $val =~ s/(\$(\w+))/$param{$2}/g;
482
483         $param{$key} = $val;
484
485         ++$count;
486     }
487     close FILE;
488
489     $file =~ s/^.*\///;
490     &status("Loaded config $file ($count items)");
491 }
492
493 1;