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