]> git.donarmstrong.com Git - infobot.git/blob - src/core.pl
safe delete did not run delFactoid, hah! found by asuffield
[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 ### CHANGE TO STATIC.
59 $bot_version = "blootbot cvs (20001212) -- $^O";
60 $noreply        = "NOREPLY";
61
62 ##########
63 ### misc commands.
64 ###
65
66 sub doExit {
67     my ($sig)   = @_;
68
69     if (defined $flag_quit) {
70         &WARN("doExit: quit already called.");
71         return;
72     }
73     $flag_quit  = 1;
74
75     if (!defined $bot_pid) {    # independent.
76         exit 0;
77     } elsif ($bot_pid == $$) {  # parent.
78         &status("parent caught SIG$sig (pid $$).") if (defined $sig);
79
80         &status("--- Start of quit.");
81
82         &closeDCC();
83         &closePID();
84         &seenFlush();
85         &quit($param{'quitMsg'}) if (&whatInterface() =~ /IRC/);
86         &writeUserFile();
87         &writeChanFile();
88         &uptimeWriteFile()      if (&ChanConfList("uptime"));
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     # what if we have it set on _default and a few channels with
135     # negative set? perhaps we should disable -blah settings to remove
136     # this mess.
137
138     if (exists $chan{_default}) {
139         return keys %chanconf;
140     } else {
141         ### TODO: -option is included aswell though.
142         return keys %chan;
143     }
144 }
145
146 #####
147 #  Usage: &getChanConfList($param)
148 #  About: gets channels with 'param' enabled, internal use only.
149 # Return: hash of channels
150 sub getChanConfList {
151     my $param   = $_[0];
152     my %chan;
153
154     return unless (defined $param);
155
156     foreach (keys %chanconf) {
157         my $chan        = $_;
158 #       &DEBUG("chan => $chan");
159         my @array       = grep /^$param$/, keys %{ $chanconf{$chan} };
160
161         next unless (scalar @array);
162
163         if (scalar @array > 1) {
164             &WARN("multiple items found?");
165         }
166
167         if ($array[0] eq "0") {
168             $chan{$chan}        = -1;
169         } else {
170             $chan{$chan}        =  1;
171         }
172     }
173
174     return %chan;
175 }
176
177 #####
178 #  Usage: &IsChanConf($param);
179 #  About: Check for 'param' on the basis of channel config.
180 # Return: 1 for enabled, 0 for passive disable, -1 for active disable.
181 sub IsChanConf {
182     my($param)  = shift;
183
184     if (!defined $param) {
185         &WARN("param == NULL.");
186         return 0;
187     }
188
189     ### TODO: VERBOSITY on how chanconf returned 1 or 0 or -1.
190     my %chan    = &getChanConfList($param);
191     if (!defined $msgType) {
192         return $chan{_default} || 0;
193     }
194
195     if ($msgType eq "public") {
196         return $chan{lc $chan} || $chan{_default} || 0;
197     }
198
199     if ($msgType eq "private") {
200         return $chan{_default} || 0;
201     }
202
203 ### debug purposes only.
204 #    &DEBUG("param => $param, msgType => $msgType.");
205 #    foreach (keys %chan) {
206 #       &DEBUG("   $_ => $chan{$_}");
207 #    }
208
209     return 0;
210 }
211
212 #####
213 #  Usage: &getChanConf($param);
214 #  About: Retrieve value for 'param' value in current/default chan.
215 # Return: scalar for success, undef for failure.
216 sub getChanConf {
217     my($param,$chan)    = @_;
218
219     if (!defined $param) {
220         &WARN("param == NULL.");
221         return 0;
222     }
223
224     $chan       ||= "_default";
225     my @c       = grep /^$chan$/i, keys %chanconf;
226
227     if (@c and $c[0] ne $chan) {
228         &WARN("c ne chan ($c[0] ne $chan)");
229     }
230
231     return $chanconf{$c[0] || "_default"}{$param};
232 }
233
234 sub showProc {
235     my ($prefix) = $_[0] || "";
236
237     if (!open(IN, "/proc/$$/status")) {
238         &ERROR("cannot open '/proc/$$/status'.");
239         return;
240     }
241
242     if ($^O eq "linux") {
243         while (<IN>) {
244             $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
245         }
246         close IN;
247
248         if (defined $memusageOld and &IsParam("DEBUG")) {
249             # it's always going to be increase.
250             my $delta = $memusage - $memusageOld;
251             my $str;
252             if ($delta == 0) {
253                 return;
254             } elsif ($delta > 500) {
255                 $str = "MEM:$prefix increased by $delta kB. (total: $memusage kB)";
256             } elsif ($delta > 0) {
257                 $str = "MEM:$prefix increased by $delta kB";
258             } else {    # delta < 0.
259                 $delta = -$delta;
260                 # never knew RSS could decrease, probably Size can't?
261                 $str = "MEM:$prefix decreased by $delta kB. YES YES YES";
262             }
263
264             &status($str);
265         }
266         $memusageOld = $memusage;
267     } else {
268         $memusage = "UNKNOWN";
269     }
270     ### TODO: FreeBSD/*BSD support.
271 }
272
273 ######
274 ###### SETUP
275 ######
276
277 sub setup {
278     &showProc(" (\&openLog before)");
279     &openLog();         # write, append.
280     &status("--- Started logging.");
281
282     foreach ("debian") {
283         my $dir = "$bot_base_dir/$_/";
284         next if ( -d $dir);
285         &status("Making dir $_");
286         mkdir $dir, 0755;
287     }
288
289     # read.
290     &loadLang($bot_misc_dir.            "/blootbot.lang");
291     &loadIRCServers();
292     &readUserFile();
293     &readChanFile();
294     &loadMyModulesNow();        # must be after chan file.
295
296     $shm = &openSHM();
297     &openSQLDebug()     if (&IsParam("SQLDebug"));
298     &openDB($param{'DBName'}, $param{'SQLUser'}, $param{'SQLPass'});
299
300     &status("Setup: ". &countKeys("factoids") ." factoids.");
301
302     $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
303
304     &status("Initial memory usage: $memusage kB");
305 }
306
307 sub setupConfig {
308     $param{'VERBOSITY'} = 1;
309     &loadConfig($bot_misc_dir."/blootbot.config");
310
311     foreach ("ircNick", "ircUser", "ircName", "DBType", "tempDir") {
312         next if &IsParam($_);
313         &ERROR("Parameter $_ has not been defined.");
314         exit 1;
315     }
316
317     if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
318         &VERB("Fixing up tempDir.",2);
319     }
320
321     if ($param{tempDir} =~ /~/) {
322         &ERROR("parameter tempDir still contains tilde.");
323         exit 1;
324     }
325
326     if (! -d $param{tempDir}) {
327         &status("making $param{tempDir}...");
328         system("mkdir $param{tempDir}");
329     }
330
331     # static scalar variables.
332     $file{utm}  = "$bot_base_dir/$param{'ircUser'}.uptime";
333     $file{PID}  = "$bot_base_dir/$param{'ircUser'}.pid";
334 }
335
336 sub startup {
337     if (&IsParam("DEBUG")) {
338         &status("enabling debug diagnostics.");
339         ### I thought disabling this reduced memory usage by 1000 kB.
340         use diagnostics;
341     }
342
343     $count{'Question'}  = 0;
344     $count{'Update'}    = 0;
345     $count{'Dunno'}     = 0;
346     $count{'Moron'}     = 0;
347 }
348
349 sub shutdown {
350     # reverse order of &setup().
351     &DEBUG("shutdown called.");
352
353     &closeDB();
354     &closeSHM($shm);    # aswell. TODO: use this in &doExit?
355     &closeLog();
356 }
357
358 sub restart {
359     my ($sig) = @_;
360
361     if ($$ == $bot_pid) {
362         &status("--- $sig called.");
363
364         ### crappy bug in Net::IRC?
365         if (!$conn->connected and time - $msgtime > 900) {
366             &status("reconnecting because of uncaught disconnect.");
367 ##          $irc->start;
368             $conn->connect();
369             return;
370         }
371
372         &DCCBroadcast("-HUP called.","m");
373         &shutdown();
374         &loadConfig($bot_misc_dir."/blootbot.config");
375         &reloadAllModules() if (&IsParam("DEBUG"));
376         &setup();
377
378         &status("--- End of $sig.");
379     } else {
380         &status("$sig called; ignoring restart.");
381     }
382 }
383
384 # File: Configuration.
385 sub loadConfig {
386     my ($file) = @_;
387
388     if (!open(FILE, $file)) {
389         &ERROR("FAILED loadConfig ($file): $!");
390         &status("Please copy files/sample.config to files/blootbot.config");
391         &status("  and edit files/blootbot.config, modify to tastes.");
392         exit 0;
393     }
394
395     my $count = 0;
396     while (<FILE>) {
397         chomp;
398         next if /^\s*\#/;
399         next unless /\S/;
400         my ($set,$key,$val) = split(/\s+/, $_, 3);
401
402         if ($set ne "set") {
403             &status("loadConfig: invalid line '$_'.");
404             next;
405         }
406
407         # perform variable interpolation
408         $val =~ s/(\$(\w+))/$param{$2}/g;
409
410         $param{$key} = $val;
411
412         ++$count;
413     }
414     close FILE;
415
416     $file =~ s/^.*\///;
417     &status("Loaded config $file ($count items)");
418 }
419
420 1;