]> git.donarmstrong.com Git - infobot.git/blob - src/core.pl
- write opened files on shutdown/hup
[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
179     if (!defined $param) {
180         &WARN("param == NULL.");
181         return 0;
182     }
183
184     ### TODO: VERBOSITY on how chanconf returned 1 or 0 or -1.
185     my %chan    = &getChanConfList($param);
186     if (!defined $msgType) {
187         return $chan{_default} || 0;
188     }
189
190     if ($msgType eq "public") {
191         return $chan{lc $chan} || $chan{_default} || 0;
192     }
193
194     if ($msgType eq "private") {
195         return $chan{_default} || 0;
196     }
197
198 ### debug purposes only.
199 #    &DEBUG("param => $param, msgType => $msgType.");
200 #    foreach (keys %chan) {
201 #       &DEBUG("   $_ => $chan{$_}");
202 #    }
203
204     return 0;
205 }
206
207 #####
208 #  Usage: &getChanConf($param);
209 #  About: Retrieve value for 'param' value in current/default chan.
210 # Return: scalar for success, undef for failure.
211 sub getChanConf {
212     my($param,$chan)    = @_;
213
214     if (!defined $param) {
215         &WARN("param == NULL.");
216         return 0;
217     }
218
219     $chan       ||= "_default";
220     my @c       = grep /^$chan$/i, keys %chanconf;
221
222     if (@c and $c[0] ne $chan) {
223         &WARN("c ne chan ($c[0] ne $chan)");
224     }
225
226     return $chanconf{$c[0] || "_default"}{$param};
227 }
228
229 sub showProc {
230     my ($prefix) = $_[0] || "";
231
232     if (!open(IN, "/proc/$$/status")) {
233         &ERROR("cannot open '/proc/$$/status'.");
234         return;
235     }
236
237     if ($^O eq "linux") {
238         while (<IN>) {
239             $memusage = $1 if (/^VmSize:\s+(\d+) kB/);
240         }
241         close IN;
242
243     } elsif ($^O eq "netbsd") {
244         $memusage = (stat "/proc/$$/mem")[7]/1024;
245
246     } elsif ($^O =~ /^(free|open)bsd$/) {
247         my @info  = split /\s+/, `/bin/ps -l -p $$`;
248         $memusage = $info[20];
249
250     } else {
251         $memusage = "UNKNOWN";
252         return;
253     }
254
255     if (defined $memusageOld and &IsParam("DEBUG")) {
256         # it's always going to be increase.
257         my $delta = $memusage - $memusageOld;
258         my $str;
259         if ($delta == 0) {
260             return;
261         } elsif ($delta > 500) {
262             $str = "MEM:$prefix increased by $delta kB. (total: $memusage kB)";
263         } elsif ($delta > 0) {
264             $str = "MEM:$prefix increased by $delta kB";
265         } else {        # delta < 0.
266             $delta = -$delta;
267             # never knew RSS could decrease, probably Size can't?
268             $str = "MEM:$prefix decreased by $delta kB. YES YES YES";
269         }
270
271         &status($str);
272     }
273     $memusageOld = $memusage;
274 }
275
276 ######
277 ###### SETUP
278 ######
279
280 sub setup {
281     &showProc(" (\&openLog before)");
282     &openLog();         # write, append.
283     &status("--- Started logging.");
284
285     foreach ("debian") {
286         my $dir = "$bot_base_dir/$_/";
287         next if ( -d $dir);
288         &status("Making dir $_");
289         mkdir $dir, 0755;
290     }
291
292     # read.
293     &loadLang($bot_misc_dir.            "/blootbot.lang");
294     &loadIRCServers();
295     &readUserFile();
296     &readChanFile();
297     &loadMyModulesNow();        # must be after chan file.
298
299     $shm = &openSHM();
300     &openSQLDebug()     if (&IsParam("SQLDebug"));
301     &openDB($param{'DBName'}, $param{'SQLUser'}, $param{'SQLPass'});
302
303     &status("Setup: ". &countKeys("factoids") ." factoids.");
304     &News::readNews() if (&ChanConfList("news"));
305
306     $param{tempDir} =~ s#\~/#$ENV{HOME}/#;
307
308     &status("Initial memory usage: $memusage kB");
309 }
310
311 sub setupConfig {
312     $param{'VERBOSITY'} = 1;
313     &loadConfig($bot_misc_dir."/blootbot.config");
314
315     foreach ("ircNick", "ircUser", "ircName", "DBType", "tempDir") {
316         next if &IsParam($_);
317         &ERROR("Parameter $_ has not been defined.");
318         exit 1;
319     }
320
321     if ($param{tempDir} =~ s#\~/#$ENV{HOME}/#) {
322         &VERB("Fixing up tempDir.",2);
323     }
324
325     if ($param{tempDir} =~ /~/) {
326         &ERROR("parameter tempDir still contains tilde.");
327         exit 1;
328     }
329
330     if (! -d $param{tempDir}) {
331         &status("making $param{tempDir}...");
332         system("mkdir $param{tempDir}");
333     }
334
335     # static scalar variables.
336     $file{utm}  = "$bot_base_dir/$param{'ircUser'}.uptime";
337     $file{PID}  = "$bot_base_dir/$param{'ircUser'}.pid";
338 }
339
340 sub startup {
341     if (&IsParam("DEBUG")) {
342         &status("enabling debug diagnostics.");
343         ### I thought disabling this reduced memory usage by 1000 kB.
344         use diagnostics;
345     }
346
347     $count{'Question'}  = 0;
348     $count{'Update'}    = 0;
349     $count{'Dunno'}     = 0;
350     $count{'Moron'}     = 0;
351 }
352
353 sub shutdown {
354     # reverse order of &setup().
355     &DEBUG("shutdown called.");
356
357     # opened files must be written to on shutdown/hup/whatever
358     # unless they're write-only, like uptime.
359     &writeUserFile();
360     &writeChanFile();
361     &News::writeNews()  if (&ChanConfList("news"));
362
363     &closeDB();
364     &closeSHM($shm);    # aswell. TODO: use this in &doExit?
365     &closeLog();
366 }
367
368 sub restart {
369     my ($sig) = @_;
370
371     if ($$ == $bot_pid) {
372         &status("--- $sig called.");
373
374         ### crappy bug in Net::IRC?
375         if (!$conn->connected and time - $msgtime > 900) {
376             &status("reconnecting because of uncaught disconnect.");
377 ##          $irc->start;
378             $conn->connect();
379             return;
380         }
381
382         &DCCBroadcast("-HUP called.","m");
383         &shutdown();
384         &loadConfig($bot_misc_dir."/blootbot.config");
385         &reloadAllModules() if (&IsParam("DEBUG"));
386         &setup();
387
388         &status("--- End of $sig.");
389     } else {
390         &status("$sig called; ignoring restart.");
391     }
392 }
393
394 # File: Configuration.
395 sub loadConfig {
396     my ($file) = @_;
397
398     if (!open(FILE, $file)) {
399         &ERROR("FAILED loadConfig ($file): $!");
400         &status("Please copy files/sample.config to files/blootbot.config");
401         &status("  and edit files/blootbot.config, modify to tastes.");
402         exit 0;
403     }
404
405     my $count = 0;
406     while (<FILE>) {
407         chomp;
408         next if /^\s*\#/;
409         next unless /\S/;
410         my ($set,$key,$val) = split(/\s+/, $_, 3);
411
412         if ($set ne "set") {
413             &status("loadConfig: invalid line '$_'.");
414             next;
415         }
416
417         # perform variable interpolation
418         $val =~ s/(\$(\w+))/$param{$2}/g;
419
420         $param{$key} = $val;
421
422         ++$count;
423     }
424     close FILE;
425
426     $file =~ s/^.*\///;
427     &status("Loaded config $file ($count items)");
428 }
429
430 1;