]> git.donarmstrong.com Git - infobot.git/blob - src/core.pl
minor updates, warn fixes, removed comments
[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         &closeDB();
89         &closeSHM($shm);
90         &dumpallvars()          if (&IsParam("dumpvarsAtExit"));
91         &closeLog();
92         &closeSQLDebug()        if (&IsParam("SQLDebug"));
93
94         &status("--- QUIT.");
95     } else {                                    # child.
96         &status("child caught SIG$sig (pid $$).");
97     }
98
99     exit 0;
100 }
101
102 sub doWarn {
103     $SIG{__WARN__} = sub { warn $_[0]; };
104
105     foreach (@_) {
106         &WARN("PERL: $_");
107     }
108
109     $SIG{__WARN__} = 'doWarn';  # ???
110 }
111
112 # Usage: &IsParam($param);
113 # blootbot.config specific.
114 sub IsParam {
115     my $param = $_[0];
116
117     return 0 unless (defined $param);
118     return 0 unless (exists $param{$param});
119     return 0 unless ($param{$param});
120     return 0 if $param{$param} =~ /^false$/i;
121     return 1;
122 }
123
124 #####
125 #  Usage: &ChanConfList($param)
126 #  About: gets channels with 'param' enabled. (!!!)
127 # Return: array of channels
128 sub ChanConfList {
129     my $param   = $_[0];
130     return unless (defined $param);
131     my %chan    = &getChanConfList($param);
132
133     if (exists $chan{_default}) {
134         return keys %chanconf;
135     } else {
136         return keys %chan;
137     }
138 }
139
140 #####
141 #  Usage: &getChanConfList($param)
142 #  About: gets channels with 'param' enabled, internal use only.
143 # Return: hash of channels
144 sub getChanConfList {
145     my $param   = $_[0];
146     my %chan;
147
148     return unless (defined $param);
149
150     foreach (keys %chanconf) {
151         my $chan        = $_;
152 #       &DEBUG("chan => $chan");
153         my @array       = grep /^$param$/, keys %{ $chanconf{$chan} };
154
155         next unless (scalar @array);
156
157         if (scalar @array > 1) {
158             &WARN("multiple items found?");
159         }
160
161         if ($array[0] eq "0") {
162             $chan{$chan}        = -1;
163         } else {
164             $chan{$chan}        =  1;
165         }
166     }
167
168     return %chan;
169 }
170
171 #####
172 #  Usage: &IsChanConf($param);
173 #  About: Check for 'param' on the basis of channel config.
174 # Return: 1 for enabled, 0 for passive disable, -1 for active disable.
175 sub IsChanConf {
176     my($param)  = shift;
177
178     if (!defined $param) {
179         &WARN("param == NULL.");
180         return 0;
181     }
182
183     ### TODO: VERBOSITY on how chanconf returned 1 or 0 or -1.
184     my %chan    = &getChanConfList($param);
185     if (!defined $msgType) {
186         return $chan{_default} || 0;
187     }
188
189     if ($msgType eq "public") {
190         return $chan{lc $chan} || $chan{_default} || 0;
191     }
192
193     if ($msgType eq "private") {
194         return $chan{_default} || 0;
195     }
196
197 ### debug purposes only.
198 #    &DEBUG("param => $param, msgType => $msgType.");
199 #    foreach (keys %chan) {
200 #       &DEBUG("   $_ => $chan{$_}");
201 #    }
202
203     return 0;
204 }
205
206 #####
207 #  Usage: &getChanConf($param);
208 #  About: Retrieve value for 'param' value in current/default chan.
209 # Return: scalar for success, undef for failure.
210 sub getChanConf {
211     my($param,$chan)    = @_;
212
213     if (!defined $param) {
214         &WARN("param == NULL.");
215         return 0;
216     }
217
218     $chan       ||= "_default";
219     my @c       = grep /^$chan$/i, keys %chanconf;
220
221     if (@c and $c[0] ne $chan) {
222         &WARN("c ne chan ($c[0] ne $chan)");
223     }
224
225     return $chanconf{$c[0] || "_default"}{$param};
226 }
227
228 sub showProc {
229     my ($prefix) = $_[0] || "";
230
231     if (!open(IN, "/proc/$$/status")) {
232         &ERROR("cannot open '/proc/$$/status'.");
233         return;
234     }
235
236     if ($^O eq "linux") {
237         while (<IN>) {
238             $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
239         }
240         close IN;
241
242     } elsif ($^O eq "netbsd") {
243         $memusage = (stat "/proc/$$/mem")[7]/1024;
244
245     } elsif ($^O =~ /^(free|open)bsd$/) {
246         my @info  = split /\s+/, `/bin/ps -l -p $$`;
247         $memusage = $info[20];
248
249     } else {
250         $memusage = "UNKNOWN";
251         return;
252     }
253
254     if (defined $memusageOld and &IsParam("DEBUG")) {
255         # it's always going to be increase.
256         my $delta = $memusage - $memusageOld;
257         my $str;
258         if ($delta == 0) {
259             return;
260         } elsif ($delta > 500) {
261             $str = "MEM:$prefix increased by $delta kB. (total: $memusage kB)";
262         } elsif ($delta > 0) {
263             $str = "MEM:$prefix increased by $delta kB";
264         } else {        # delta < 0.
265             $delta = -$delta;
266             # never knew RSS could decrease, probably Size can't?
267             $str = "MEM:$prefix decreased by $delta kB. YES YES YES";
268         }
269
270         &status($str);
271     }
272     $memusageOld = $memusage;
273 }
274
275 ######
276 ###### SETUP
277 ######
278
279 sub setup {
280     &showProc(" (\&openLog before)");
281     &openLog();         # write, append.
282     &status("--- Started logging.");
283
284     foreach ("debian") {
285         my $dir = "$bot_base_dir/$_/";
286         next if ( -d $dir);
287         &status("Making dir $_");
288         mkdir $dir, 0755;
289     }
290
291     # read.
292     &loadLang($bot_misc_dir.            "/blootbot.lang");
293     &loadIRCServers();
294     &readUserFile();
295     &readChanFile();
296     &loadMyModulesNow();        # must be after chan file.
297
298     $shm = &openSHM();
299     &openSQLDebug()     if (&IsParam("SQLDebug"));
300     &openDB($param{'DBName'}, $param{'SQLUser'}, $param{'SQLPass'});
301
302     &status("Setup: ". &countKeys("factoids") ." factoids.");
303
304     $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
305
306     &status("Initial memory usage: $memusage kB");
307 }
308
309 sub setupConfig {
310     $param{'VERBOSITY'} = 1;
311     &loadConfig($bot_misc_dir."/blootbot.config");
312
313     foreach ("ircNick", "ircUser", "ircName", "DBType", "tempDir") {
314         next if &IsParam($_);
315         &ERROR("Parameter $_ has not been defined.");
316         exit 1;
317     }
318
319     if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
320         &VERB("Fixing up tempDir.",2);
321     }
322
323     if ($param{tempDir} =~ /~/) {
324         &ERROR("parameter tempDir still contains tilde.");
325         exit 1;
326     }
327
328     if (! -d $param{tempDir}) {
329         &status("making $param{tempDir}...");
330         system("mkdir $param{tempDir}");
331     }
332
333     # static scalar variables.
334     $file{utm}  = "$bot_base_dir/$param{'ircUser'}.uptime";
335     $file{PID}  = "$bot_base_dir/$param{'ircUser'}.pid";
336 }
337
338 sub startup {
339     if (&IsParam("DEBUG")) {
340         &status("enabling debug diagnostics.");
341         ### I thought disabling this reduced memory usage by 1000 kB.
342         use diagnostics;
343     }
344
345     $count{'Question'}  = 0;
346     $count{'Update'}    = 0;
347     $count{'Dunno'}     = 0;
348     $count{'Moron'}     = 0;
349 }
350
351 sub shutdown {
352     # reverse order of &setup().
353     &DEBUG("shutdown called.");
354
355     &closeDB();
356     &closeSHM($shm);    # aswell. TODO: use this in &doExit?
357     &closeLog();
358 }
359
360 sub restart {
361     my ($sig) = @_;
362
363     if ($$ == $bot_pid) {
364         &status("--- $sig called.");
365
366         ### crappy bug in Net::IRC?
367         if (!$conn->connected and time - $msgtime > 900) {
368             &status("reconnecting because of uncaught disconnect.");
369 ##          $irc->start;
370             $conn->connect();
371             return;
372         }
373
374         &DCCBroadcast("-HUP called.","m");
375         &shutdown();
376         &loadConfig($bot_misc_dir."/blootbot.config");
377         &reloadAllModules() if (&IsParam("DEBUG"));
378         &setup();
379
380         &status("--- End of $sig.");
381     } else {
382         &status("$sig called; ignoring restart.");
383     }
384 }
385
386 # File: Configuration.
387 sub loadConfig {
388     my ($file) = @_;
389
390     if (!open(FILE, $file)) {
391         &ERROR("FAILED loadConfig ($file): $!");
392         &status("Please copy files/sample.config to files/blootbot.config");
393         &status("  and edit files/blootbot.config, modify to tastes.");
394         exit 0;
395     }
396
397     my $count = 0;
398     while (<FILE>) {
399         chomp;
400         next if /^\s*\#/;
401         next unless /\S/;
402         my ($set,$key,$val) = split(/\s+/, $_, 3);
403
404         if ($set ne "set") {
405             &status("loadConfig: invalid line '$_'.");
406             next;
407         }
408
409         # perform variable interpolation
410         $val =~ s/(\$(\w+))/$param{$2}/g;
411
412         $param{$key} = $val;
413
414         ++$count;
415     }
416     close FILE;
417
418     $file =~ s/^.*\///;
419     &status("Loaded config $file ($count items)");
420 }
421
422 1;