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