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