]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/Schedulers.pl
- strictify
[infobot.git] / src / IRC / Schedulers.pl
1 #
2 # ProcessExtra.pl: Extensions to Process.pl
3 #          Author: dms
4 #         Version: v0.5 (20010124)
5 #         Created: 20000117
6 #
7
8 # use strict;   # TODO
9
10 use POSIX qw(strftime);
11 use vars qw(%sched);
12
13 sub setupSchedulers {
14     &VERB("Starting schedulers...",2);
15
16     # ONCE OFF.
17
18     # REPETITIVE.
19     # 1 for run straight away, 2 for on next-run.
20     &uptimeLoop(1);
21     &randomQuote(2);
22     &randomFactoid(2);
23     &randomFreshmeat(2);
24     &logLoop(1);
25     &chanlimitCheck(1);
26     &netsplitCheck(1);  # mandatory
27     &floodLoop(1);      # mandatory
28     &seenFlush(2);
29     &leakCheck(2);      # mandatory
30     &ignoreCheck(1);    # mandatory
31     &seenFlushOld(2);
32     &ircCheck(1);       # mandatory
33     &miscCheck(1);      # mandatory
34     &miscCheck2(2);     # mandatory
35     &shmFlush(1);       # mandatory
36     &slashdotLoop(2);
37     &plugLoop(2);
38     &freshmeatLoop(2);
39     &kernelLoop(2);
40     &wingateWriteFile(2);
41     &factoidCheck(2);   # takes a couple of seconds on a 486. defer it
42     &newsFlush(1);
43
44     # todo: squeeze this into a one-liner.
45 #    my $count = map { exists $sched{$_}{TIME} } keys %sched;
46     my $count   = 0;
47     foreach (keys %sched) {
48         my $time = $sched{$_}{TIME};
49         next unless (defined $time and $time > time());
50
51         $count++;
52     }
53
54     &status("Schedulers: $count will be running.");
55 ###    &scheduleList();
56 }
57
58 sub ScheduleThis {
59     my ($interval, $codename, @args) = @_;
60     my $waittime = &getRandomInt($interval);
61
62     if (!defined $waittime) {
63         &WARN("interval == waittime == UNDEF for $codename.");
64         return;
65     }
66
67     my $time = $sched{$codename}{TIME};
68     if (defined $time and $time > time()) {
69         &WARN("Sched for $codename already exists.");
70         return;
71     }
72
73 #    &VERB("Scheduling \&$codename() for ".&Time2String($waittime),3);
74
75     my $retval = $conn->schedule($waittime, \&$codename, @args);
76     $sched{$codename}{LABEL}    = $retval;
77     $sched{$codename}{TIME}     = time()+$waittime;
78     $sched{$codename}{LOOP}     = 1;
79 }
80
81 ####
82 #### LET THE FUN BEGIN.
83 ####
84
85 sub randomQuote {
86     my $interval = &getChanConfDefault("randomQuoteInterval", 60);
87     if (@_) {
88         &ScheduleThis($interval, "randomQuote");
89         return if ($_[0] eq "2");       # defer.
90     }
91
92     my $line = &getRandomLineFromFile($bot_data_dir. "/blootbot.randtext");
93     if (!defined $line) {
94         &ERROR("random Quote: weird error?");
95         return;
96     }
97
98     foreach ( &ChanConfList("randomQuote") ) {
99         next unless (&validChan($_));
100
101         &status("sending random Quote to $_.");
102         &action($_, "Ponders: ".$line);
103     }
104     ### TODO: if there were no channels, don't reschedule until channel
105     ###         configuration is modified.
106 }
107
108 sub randomFactoid {
109     my ($key,$val);
110     my $error = 0;
111
112     my $interval = &getChanConfDefault("randomFactoidInterval", 60);
113     if (@_) {
114         &ScheduleThis($interval, "randomFactoid");
115         return if ($_[0] eq "2");       # defer.
116     }
117
118     while (1) {
119         ($key,$val) = &randKey("factoids","factoid_key,factoid_value");
120 ###     $val =~ tr/^[A-Z]/[a-z]/;       # blah is Good => blah is good.
121         last if (defined $val and $val !~ /^</);
122
123         $error++;
124         if ($error == 5) {
125             &ERROR("rF: tried 5 times but failed.");
126             return;
127         }
128     }
129
130     foreach ( &ChanConfList("randomFactoid") ) {
131         next unless (&validChan($_));
132
133         &status("sending random Factoid to $_.");
134         &action($_, "Thinks: \037$key\037 is $val");
135         ### FIXME: Use &getReply() on above to format factoid properly?
136         $good++;
137     }
138 }
139
140 sub randomFreshmeat {
141     my $interval = &getChanConfDefault("randomFreshmeatInterval", 60);
142
143     if (@_) {
144         &ScheduleThis($interval, "randomFreshmeat");
145         return if ($_[0] eq "2");       # defer.
146     }
147
148     my @chans = &ChanConfList("randomFreshmeat");
149     return unless (scalar @chans);
150
151     &Forker("freshmeat", sub {
152         my $retval = &Freshmeat::randPackage();
153
154         foreach (@chans) {
155             next unless (&validChan($_));
156
157             &status("sending random Freshmeat to $_.");
158             &say($_, $line);
159         }
160     } );
161 }
162
163 sub logLoop {
164     if (@_) {
165         &ScheduleThis(60, "logLoop");
166         return if ($_[0] eq "2");       # defer.
167     }
168
169     return unless (defined fileno LOG);
170     return unless (&IsParam("logfile"));
171     return unless (&IsParam("maxLogSize"));
172
173     ### check if current size is too large.
174     if ( -s $file{log} > $param{'maxLogSize'}) {
175         my $date = sprintf("%04d%02d%02d", (localtime)[5,4,3]);
176         $file{log} = $param{'logfile'} ."-". $date;
177         &status("cycling log file.");
178
179         if ( -e $file{log}) {
180             my $i = 1;
181             my $newlog;
182             while () {
183                 $newlog = $file{log}."-".$i;
184                 last if (! -e $newlog);
185                 $i++;
186             }
187             $file{log} = $newlog;
188         }
189
190         &closeLog();
191         CORE::system("/bin/mv '$param{'logfile'}' '$file{log}'");
192         &compress($file{log});
193         &openLog();
194         &status("cycling log file.");
195     }
196
197     ### check if all the logs exceed size.
198     if (!opendir(LOGS, $bot_log_dir)) {
199         &WARN("logLoop: could not open dir '$bot_log_dir'");
200         return;
201     }
202
203     my $tsize           = 0;
204     my (%age, %size);
205     while (defined($_ = readdir LOGS)) {
206         my $logfile     = "$bot_log_dir/$_";
207
208         next unless ( -f $logfile);
209
210         my $size        = -s $logfile;
211         my $age         = (stat $logfile)[9];
212         $age{$age}      = $logfile;
213         $size{$logfile} = $size;
214         $tsize          += $size;
215     }
216     closedir LOGS;
217
218     my $delete  = 0;
219     while ($tsize > $param{'maxLogSize'}) {
220         &status("LOG: current size > max ($tsize > $param{'maxLogSize'})");
221         my $oldest      = (sort {$a <=> $b} keys %age)[0];
222         &status("LOG: unlinking $age{$oldest}.");
223         unlink $age{$oldest};
224         $tsize          -= $oldest;
225         $delete++;
226     }
227
228     ### TODO: add how many b,kb,mb removed?
229     &status("LOG: removed $delete logs.") if ($delete);
230 }
231
232 sub seenFlushOld {
233     if (@_) {
234         &ScheduleThis(1440, "seenFlushOld");
235         return if ($_[0] eq "2");       # defer.
236     }
237
238     # is this global-only?
239     return unless (&IsChanConf("seen") > 0);
240     return unless (&IsChanConf("seenFlushInterval") > 0);
241
242     # global setting. does not make sense for per-channel.
243     my $max_time = &getChanConfDefault("seenMaxDays", 30) *60*60*24;
244     my $delete   = 0;
245
246     if ($param{'DBType'} =~ /^pgsql|mysql|sqlite/i) {
247         my $query;
248
249         if ($param{'DBType'} =~ /^mysql|sqlite$/i) {
250             $query = "SELECT nick,time FROM seen GROUP BY nick HAVING ".
251                         "UNIX_TIMESTAMP() - time > $max_time";
252         } else {        # pgsql.
253             $query = "SELECT nick,time FROM seen WHERE ".
254                 "extract(epoch from timestamp 'now') - time > $max_time";
255         }
256
257         my $sth = $dbh->prepare($query);
258         $sth->execute;
259
260         while (my @row = $sth->fetchrow_array) {
261             my ($nick,$time) = @row;
262
263             &dbDel("seen","nick",$nick);
264             $delete++;
265         }
266         $sth->finish;
267     } elsif ($param{'DBType'} =~ /^dbm/i) {
268         my $time = time();
269
270         foreach (keys %seen) {
271             my $delta_time = $time - &dbGet("seen", "time", "nick", $_);
272             next unless ($delta_time > $max_time);
273
274             &DEBUG("seenFlushOld: ".&Time2String($delta_time) );
275             delete $seen{$_};
276             $delete++;
277         }
278     } else {
279         &FIXME("seenFlushOld: for PG/NO-DB.");
280     }
281     &VERB("SEEN deleted $delete seen entries.",2);
282
283 }
284
285 sub newsFlush {
286     if (@_) {
287         &ScheduleThis(60, "newsFlush");
288         return if ($_[0] eq "2");       # defer.
289     }
290
291     if (!&ChanConfList("news")) {
292         &DEBUG("newsFlush: news disabled? (chan => $chan)");
293         return;
294     }
295
296     my $delete  = 0;
297     my $oldest  = time();
298     my %none;
299     foreach $chan (keys %::news) {
300         my $i           = 0;
301         my $total       = scalar(keys %{ $::news{$chan} });
302
303         if (!$total) {
304             delete $::news{$chan};
305             next;
306         }
307
308         foreach $item (keys %{ $::news{$chan} }) {
309             my $t = $::news{$chan}{$item}{Expire};
310
311             my $tadd    = $::news{$chan}{$item}{Time};
312             $oldest     = $tadd if ($oldest > $tadd);
313
314             next if ($t == 0 or $t == -1);
315             if ($t < 1000) {
316                 &status("newsFlush: Fixed Expire time for $chan/$item, should not happen anyway.");
317                 $::news{$chan}{$item}{Expire} = time() + $t*60*60*24;
318                 next;
319             }
320
321             my $delta = $t - time();
322
323             next unless (time() > $t);
324
325             # todo: show how old it was.
326             delete $::news{$chan}{$item};
327             &status("NEWS: (newsflush) deleted '$item'");
328             $delete++;
329             $i++;
330         }
331
332         &status("NEWS (newsflush) {$chan}: deleted [$i/$total] news entries.") if ($i);
333         $none{$chan} = 1 if ($total == $i);
334     }
335
336     # todo: flush users aswell.
337     my $duser   = 0;
338     foreach $chan (keys %::newsuser) {
339         next if (exists $none{$chan});
340
341         foreach (keys %{ $::newsuser{$chan} }) {
342             my $t = $::newsuser{$chan}{$_};
343             if (!defined $t or ($t > 2 and $t < 1000)) {
344                 &DEBUG("something wrong with newsuser{$chan}{$_} => $t");
345                 next;
346             }
347
348             next unless ($oldest > $t);
349
350             delete $::newsuser{$chan}{$_};
351             $duser++;
352         }
353
354         my $i = scalar(keys %{ $::newsuser{$chan} });
355         delete $::newsuser{$chan} unless ($i);
356     }
357
358     if ($delete or $duser) {
359         &News::writeNews();
360         &status("NewsFlush: deleted: $delete news entries; $duser user cache.");
361     }
362 }
363
364 sub chanlimitCheck {
365     my $interval = &getChanConfDefault("chanlimitcheckInterval", 10);
366
367     if (@_) {
368         &ScheduleThis($interval, "chanlimitCheck");
369         return if ($_[0] eq "2");
370     }
371
372     my $str = join(' ', &ChanConfList("chanlimitcheck") );
373
374     foreach $chan ( &ChanConfList("chanlimitcheck") ) {
375         next unless (&validChan($chan));
376
377         if ($chan eq "_default") {
378             &WARN("chanlimit: we're doing $chan!! HELP ME!");
379             next;
380         }
381
382         my $limitplus   = &getChanConfDefault("chanlimitcheckPlus", 5, $chan);
383         my $newlimit    = scalar(keys %{ $channels{$chan}{''} }) + $limitplus;
384         my $limit       = $channels{$chan}{'l'};
385
386         if (scalar keys %netsplitservers) {
387             if (defined $limit) {
388                 &status("chanlimit: netsplit; removing it for $chan.");
389                 $conn->mode($chan, "-l");
390                 $cache{chanlimitChange}{$chan} = time();
391                 &status("chanlimit: netsplit; removed.");
392             }
393
394             next;
395         }
396
397         if (defined $limit and scalar keys %{ $channels{$chan}{''} } > $limit) {
398             &FIXME("LIMIT: set too low!!! FIXME");
399             ### run NAMES again and flush it.
400         }
401
402         if (defined $limit and $limit == $newlimit) {
403             $cache{chanlimitChange}{$chan} = time();
404             next;
405         }
406
407         if (!exists $channels{$chan}{'o'}{$ident}) {
408             &status("chanlimit: dont have ops on $chan.") unless (exists $cache{warn}{chanlimit}{$chan});
409             $cache{warn}{chanlimit}{$chan} = 1;
410             &chanServCheck($chan);
411             next;
412         }
413         delete $cache{warn}{chanlimit}{$chan};
414
415         if (!defined $limit) {
416             &status("chanlimit: setting for first time or from netsplit, for $chan");
417         }
418
419         if (exists $cache{chanlimitChange}{$chan}) {
420             my $delta = time() - $cache{chanlimitChange}{$chan};
421             if ($delta < $interval*60) {
422                 &DEBUG("chanlimit: not going to change chanlimit! ($delta<$interval*60)");
423                 return;
424             }
425         }
426
427         $conn->mode($chan, "+l", $newlimit);
428         $cache{chanlimitChange}{$chan} = time();
429     }
430 }
431
432 sub netsplitCheck {
433     my ($s1,$s2);
434
435     if (@_) {
436         &ScheduleThis(15, "netsplitCheck");
437         return if ($_[0] eq "2");
438     }
439
440     $cache{'netsplitCache'}++;
441 #    &DEBUG("running netsplitCheck... $cache{netsplitCache}");
442
443     if (!scalar %netsplit and scalar %netsplitservers) {
444         &DEBUG("nsC: !hash netsplit but hash netsplitservers <- removing!");
445         undef %netsplitservers;
446         return;
447     }
448
449     # well... this shouldn't happen since %netsplit code does it anyway.
450     foreach $s1 (keys %netsplitservers) {
451
452         foreach $s2 (keys %{ $netsplitservers{$s1} }) {
453             my $delta = time() - $netsplitservers{$s1}{$s2};
454
455             if ($delta > 60*30) {
456                 &status("netsplit between $s1 and $s2 appears to be stale.");
457                 delete $netsplitservers{$s1}{$s2};
458                 &chanlimitCheck();
459             }
460         }
461
462         my $i = scalar(keys %{ $netsplitservers{$s1} });
463         delete $netsplitservers{$s1} unless ($i);
464     }
465
466     # %netsplit hash checker.
467     my $count   = scalar keys %netsplit;
468     my $delete  = 0;
469     foreach (keys %netsplit) {
470         if (&IsNickInAnyChan($_)) {     # why would this happen?
471 #           &DEBUG("nsC: $_ is in some chan; removing from netsplit list.");
472             delete $netsplit{$_};
473             $delete++;
474             next;
475         }
476
477         next unless (time() - $netsplit{$_} > 60*15);
478
479         $delete++;
480         delete $netsplit{$_};
481     }
482
483     # yet another hack.
484     foreach (keys %channels) {
485         my $i = $cache{maxpeeps}{$chan} || 0;
486         my $j = scalar(keys %{ $channels{$chan} });
487         next unless ($i > 10 and 0.25*$i > $j);
488
489         &DEBUG("netsplit: 0.25*max($i) > current($j); possible netsplit?");
490     }
491
492     if ($delete) {
493         my $j = scalar(keys %netsplit);
494         &status("nsC: removed from netsplit list: (before: $count; after: $j)");
495     }
496
497     if (!scalar %netsplit and scalar %netsplitservers) {
498         &DEBUG("nsC: ok hash netsplit is NULL; purging hash netsplitservers");
499         undef %netsplitservers;
500     }
501
502     if ($count and !scalar keys %netsplit) {
503         &DEBUG("nsC: netsplit is hopefully gone. reinstating chanlimit check.");
504         &chanlimitCheck();
505     }
506 }
507
508 sub floodLoop {
509     my $delete   = 0;
510     my $who;
511
512     if (@_) {
513         &ScheduleThis(60, "floodLoop"); # minutes.
514         return if ($_[0] eq "2");
515     }
516
517     my $time            = time();
518     my $interval        = &getChanConfDefault("floodCycle",60);
519
520     foreach $who (keys %flood) {
521         foreach (keys %{ $flood{$who} }) {
522             if (!exists $flood{$who}{$_}) {
523                 &WARN("flood{$who}{$_} undefined?");
524                 next;
525             }
526
527             if ($time - $flood{$who}{$_} > $interval) {
528                 delete $flood{$who}{$_};
529                 $delete++;
530             }
531         }
532     }
533     &VERB("floodLoop: deleted $delete items.",2);
534 }
535
536 sub seenFlush {
537     if (@_) {
538         my $interval = &getChanConfDefault("seenFlushInterval", 60);
539         &ScheduleThis($interval, "seenFlush");
540         return if ($_[0] eq "2");
541     }
542
543     my %stats;
544     my $nick;
545     my $flushed         = 0;
546     $stats{'count_old'} = &countKeys("seen") || 0;
547     $stats{'new'}       = 0;
548     $stats{'old'}       = 0;
549
550     if ($param{'DBType'} =~ /^(mysql|pgsql|sqlite|dbm)$/i) {
551         foreach $nick (keys %seencache) {
552             my $retval = &dbReplace("seen", "nick", (
553                         "nick" => lc $seencache{$nick}{'nick'},
554                         "time" => $seencache{$nick}{'time'},
555                         "host" => $seencache{$nick}{'host'},
556                         "channel" => $seencache{$nick}{'chan'},
557                         "message" => $seencache{$nick}{'msg'},
558             ) );
559             delete $seencache{$nick};
560             $flushed++;
561         }
562     } else {
563         &DEBUG("seenFlush: NO VALID FACTOID SUPPORT?");
564     }
565
566     &status("Seen: Flushed $flushed entries.")  if ($flushed);
567     &VERB(sprintf("  new seen: %03.01f%% (%d/%d)",
568         $stats{'new'}*100/($stats{'count_old'} || 1),
569         $stats{'new'}, ( $stats{'count_old'} || 1) ), 2) if ($stats{'new'});
570     &VERB(sprintf("  now seen: %3.1f%% (%d/%d)",
571         $stats{'old'}*100 / ( &countKeys("seen") || 1),
572         $stats{'old'}, &countKeys("seen") ), 2)         if ($stats{'old'});
573
574     &WARN("scalar keys seenflush != 0!")        if (scalar keys %seenflush);
575 }
576
577 sub leakCheck {
578     my ($blah1,$blah2);
579     my $count = 0;
580
581     if (@_) {
582         &ScheduleThis(240, "leakCheck");
583         return if ($_[0] eq "2");
584     }
585
586     # flood. this is dealt with in floodLoop()
587     foreach $blah1 (keys %flood) {
588         foreach $blah2 (keys %{ $flood{$blah1} }) {
589             $count += scalar(keys %{ $flood{$blah1}{$blah2} });
590         }
591     }
592     &VERB("leak: hash flood has $count total keys.",2);
593
594     # floodjoin.
595     $count = 0;
596     foreach $blah1 (keys %floodjoin) {
597         foreach $blah2 (keys %{ $floodjoin{$blah1} }) {
598             $count += scalar(keys %{ $floodjoin{$blah1}{$blah2} });
599         }
600     }
601     &VERB("leak: hash floodjoin has $count total keys.",2);
602
603     # floodwarn.
604     $count = scalar(keys %floodwarn);
605     &VERB("leak: hash floodwarn has $count total keys.",2);
606
607     my $chan;
608     foreach $chan (grep /[A-Z]/, keys %channels) {
609         &DEBUG("leak: chan => '$chan'.");
610         my ($i,$j);
611         foreach $i (keys %{ $channels{$chan} }) {
612             foreach (keys %{ $channels{$chan}{$i} }) {
613                 &DEBUG("leak:   \$channels{$chan}{$i}{$_} ...");
614             }
615         }
616     }
617
618     # chanstats
619     $count = scalar(keys %chanstats);
620     &VERB("leak: hash chanstats has $count total keys.",2);
621
622     # nuh.
623     my $delete  = 0;
624     foreach (keys %nuh) {
625         next if (&IsNickInAnyChan($_));
626         next if (exists $dcc{CHAT}{$_});
627
628         delete $nuh{$_};
629         $delete++;
630     }
631
632     &status("leak: $delete nuh{} items deleted; now have ".
633                                 scalar(keys %nuh) ) if ($delete);
634 }
635
636 sub ignoreCheck {
637     if (@_) {
638         &ScheduleThis(60, "ignoreCheck");
639         return if ($_[0] eq "2");       # defer.
640     }
641
642     my $time    = time();
643     my $count   = 0;
644
645     foreach (keys %ignore) {
646         my $chan = $_;
647
648         foreach (keys %{ $ignore{$chan} }) {
649             my @array = @{ $ignore{$chan}{$_} };
650
651             next unless ($array[0] and $time > $array[0]);
652
653             delete $ignore{$chan}{$_};
654             &status("ignore: $_/$chan has expired.");
655             $count++;
656         }
657     }
658
659     $cache{ignoreCheckTime} = time();
660
661     &VERB("ignore: $count items deleted.",2);
662 }
663
664 sub ircCheck {
665     if (@_) {
666         &ScheduleThis(15, "ircCheck");
667         return if ($_[0] eq "2");       # defer.
668     }
669
670     $cache{statusSafe} = 1;
671
672     my @x       = &getJoinChans();
673     my $iconf   = scalar( @x );
674     my $inow    = scalar( keys %channels );
675     if ($iconf > 2 and $inow * 2 <= $iconf) {
676         &FIXME("ircCheck: current channels * 2 <= config channels. FIXME.");
677         &FIXME("ircCheck: iconf = $iconf");
678         &FIXME("ircCheck: inow  = $inow");
679 #       @joinchan       = @x;
680         &joinNextChan();
681     }
682
683     if (!$conn->connected or time() - $msgtime > 3600) {
684         # todo: shouldn't we use cache{connect} somewhere?
685         if (exists $cache{connect}) {
686             &WARN("ircCheck: no msg for 3600 and disco'd! reconnecting!");
687             $msgtime = time();  # just in case.
688             &ircloop();
689             delete $cache{connect};
690         } else {
691             &status("IRCTEST: possible lost in space; checking. ".
692                 scalar(localtime) );
693             &msg($ident, "TEST");
694             $cache{connect} = time();
695         }
696     }
697
698     if ($ident !~ /^\Q$param{ircNick}\E$/) {
699         # this does not work unfortunately.
700         &WARN("ircCheck: ident($ident) != param{ircNick}($param{ircNick}).");
701
702         # this check is misleading... perhaps we should do a notify.
703         if (! &IsNickInAnyChan( $param{ircNick} ) ) {
704             &DEBUG("$param{ircNick} not in use... changing!");
705             &nick( $param{ircNick} );
706         } else {
707             &WARN("$param{ircNick} is still in use...");
708         }
709     }
710
711     if (grep /^\s*$/, keys %channels) {
712         &WARN("ircCheck: we have a NULL chan in hash channels? removing!");
713         if (!exists $channels{''}) {
714             &DEBUG("ircCheck: this should never happen!");
715         }
716
717         delete $channels{''};
718     }
719
720     $cache{statusSafe} = 0;
721
722     ### USER FILE.
723     if ($utime_userfile > $wtime_userfile and time() - $wtime_userfile > 3600) {
724         &writeUserFile();
725         $wtime_userfile = time();
726     }
727     ### CHAN FILE.
728     if ($utime_chanfile > $wtime_chanfile and time() - $wtime_chanfile > 3600) {
729         &writeChanFile();
730         $wtime_chanfile = time();
731     }
732 }
733
734 sub miscCheck {
735     if (@_) {
736         &ScheduleThis(120, "miscCheck");
737         return if ($_[0] eq "2");       # defer.
738     }
739
740     # SHM check.
741     my @ipcs;
742     if ( -x "/usr/bin/ipcs") {
743         @ipcs = `/usr/bin/ipcs`;
744     } else {
745         &WARN("ircCheck: no 'ipcs' binary.");
746         return;
747     }
748
749     # shmid stale remove.
750     foreach (@ipcs) {
751         chop;
752
753         # key, shmid, owner, perms, bytes, nattch
754         next unless (/^(0x\d+) (\d+)\s+(\S+)\s+(\d+)\s+(\d+)\s+/);
755
756         my ($shmid, $size) = ($2,$5);
757         next unless ($shmid != $shm and $size == 2000);
758         my $z   = &shmRead($shmid);
759         if ($z =~ /^(\d+): /) {
760             my $time    = $1;
761             next if (time() - $time < 60*60);
762
763         } else {
764 #           &DEBUG("shm: $shmid is not ours or old blootbot => ($z)");
765 #           next;
766         }
767
768         &status("SHM: nuking shmid $shmid");
769         CORE::system("/usr/bin/ipcrm shm $shmid >/dev/null");
770     }
771
772     # make backup of important files.
773     &mkBackup( $bot_state_dir."/blootbot.chan", 60*60*24*3);
774     &mkBackup( $bot_state_dir."/blootbot.users", 60*60*24*3);
775     &mkBackup( $bot_base_dir."/blootbot-news.txt", 60*60*24*1);
776
777     # flush cache{lobotomy}
778     foreach (keys %{ $cache{lobotomy} }) {
779         next unless (time() - $cache{lobotomy}{$_} > 60*60);
780         delete $cache{lobotomy}{$_};
781     }
782
783     ### check modules if they've been modified. might be evil.
784     &reloadAllModules();
785 }
786
787 sub miscCheck2 {
788     if (@_) {
789         &ScheduleThis(240, "miscCheck2");
790         return if ($_[0] eq "2");       # defer.
791     }
792
793     # debian check.
794     opendir(DEBIAN, "$bot_state_dir/debian");
795     foreach ( grep /gz$/, readdir(DEBIAN) ) {
796         my $exit = CORE::system("gzip -t $bot_state_dir/debian/$_");
797         next unless ($exit);
798
799         &status("debian: unlinking file => $_");
800         unlink "$bot_state_dir/debian/$_";
801     }
802     closedir DEBIAN;
803
804     # compress logs that should have been compressed.
805     # todo: use strftime?
806     my ($day,$month,$year) = (localtime(time()))[3,4,5];
807     my $date = sprintf("%04d%02d%02d",$year+1900,$month+1,$day);
808
809     if (!opendir(DIR,"$bot_log_dir")) {
810         &ERROR("misccheck2: log dir $bot_log_dir does not exist.");
811         closedir DIR;
812         return -1;
813     }
814
815     while (my $f = readdir(DIR)) {
816         next unless ( -f "$bot_log_dir/$f");
817         next if ($f =~ /gz|bz2/);
818         next unless ($f =~ /(\d{8})/);
819         next if ($date eq $1);
820
821         &compress("$bot_log_dir/$f");
822     }
823     closedir DIR;
824 }
825
826 ### this is semi-scheduled
827 sub getNickInUse {
828     if ($ident eq $param{'ircNick'}) {
829         &status("okay, got my nick back.");
830         return;
831     }
832
833     if (@_) {
834         &ScheduleThis(30, "getNickInUse");
835         return if ($_[0] eq "2");       # defer.
836     }
837
838     &nick( $param{'ircNick'} );
839 }
840
841 sub uptimeLoop {
842     return unless &IsChanConf("uptime");
843
844     if (@_) {
845         &ScheduleThis(60, "uptimeLoop");
846         return if ($_[0] eq "2");       # defer.
847     }
848
849     &uptimeWriteFile();
850 }
851
852 sub slashdotLoop {
853
854     if (@_) {
855         &ScheduleThis(60, "slashdotLoop");
856         return if ($_[0] eq "2");
857     }
858
859     my @chans = &ChanConfList("slashdotAnnounce");
860     return unless (scalar @chans);
861
862     &Forker("slashdot", sub {
863         my $line = &Slashdot::slashdotAnnounce();
864         return unless (defined $line);
865
866         foreach (@chans) {
867             next unless (&::validChan($_));
868
869             &::status("sending slashdot update to $_.");
870             &notice($_, "Slashdot: $line");
871         }
872     } );
873 }
874
875 sub plugLoop {
876
877     if (@_) {
878         &ScheduleThis(60, "plugLoop");
879         return if ($_[0] eq "2");
880     }
881
882     my @chans = &ChanConfList("plugAnnounce");
883     return unless (scalar @chans);
884
885     &Forker("plug", sub {
886         my $line = &Plug::plugAnnounce();
887         return unless (defined $line);
888
889         foreach (@chans) {
890             next unless (&::validChan($_));
891
892             &::status("sending plug update to $_.");
893             &notice($_, "Plug: $line");
894         }
895     } );
896 }
897
898 sub freshmeatLoop {
899     if (@_) {
900         &ScheduleThis(60, "freshmeatLoop");
901         return if ($_[0] eq "2");
902     }
903
904     my @chans = &ChanConfList("freshmeatAnnounce");
905     return unless (scalar @chans);
906
907     &Forker("freshmeat", sub {
908         my $data = &Freshmeat::freshmeatAnnounce();
909
910         foreach (@chans) {
911             next unless (&::validChan($_));
912
913             &::status("sending freshmeat update to $_.");
914             &msg($_, $data);
915         }
916     } );
917 }
918
919 sub kernelLoop {
920     if (@_) {
921         &ScheduleThis(240, "kernelLoop");
922         return if ($_[0] eq "2");
923     }
924
925     my @chans = &ChanConfList("kernelAnnounce");
926     return unless (scalar @chans);
927
928     &Forker("kernel", sub {
929         my @data = &Kernel::kernelAnnounce();
930
931         foreach (@chans) {
932             next unless (&::validChan($_));
933
934             &::status("sending kernel update to $_.");
935             my $c = $_;
936             foreach (@data) {
937                 &notice($c, "Kernel: $_");
938             }
939         }
940     } );
941 }
942
943 sub wingateCheck {
944     return unless &IsChanConf("wingate");
945
946     ### FILE CACHE OF OFFENDING WINGATES.
947     foreach (grep /^$host$/, @wingateBad) {
948         &status("Wingate: RUNNING ON $host BY $who");
949         &ban("*!*\@$host", "") if &IsChanConf("wingateBan");
950
951         my $reason      = &getChanConf("wingateKick");
952
953         next unless ($reason);
954         &kick($who, "", $reason)
955     }
956
957     ### RUN CACHE OF TRIED WINGATES.
958     if (grep /^$host$/, @wingateCache) {
959         push(@wingateNow, $host);       # per run.
960         push(@wingateCache, $host);     # cache per run.
961     } else {
962         &DEBUG("Already scanned $host. good.");
963     }
964
965     my $interval = &getChanConfDefault("wingateInterval", 60); # seconds.
966     return if (defined $forked{'wingate'});
967     return if (time() - $wingaterun <= $interval);
968     return unless (scalar(keys %wingateToDo));
969
970     $wingaterun = time();
971
972     &Forker("wingate", sub { &Wingate::Wingates(keys %wingateToDo); } );
973     undef @wingateNow;
974 }
975
976 ### TODO.
977 sub wingateWriteFile {
978     if (@_) {
979         &ScheduleThis(60, "wingateWriteFile");
980         return if ($_[0] eq "2");       # defer.
981     }
982
983     return unless (scalar @wingateCache);
984
985     my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
986     if ($bot_pid != $$) {
987         &DEBUG("wingateWriteFile: Reorganising!");
988
989         open(IN, $file);
990         while (<IN>) {
991             chop;
992             push(@wingateNow, $_);
993         }
994         close IN;
995
996         # very lame hack.
997         my %hash = map { $_ => 1 } @wingateNow;
998         @wingateNow = sort keys %hash;
999     }
1000
1001     &DEBUG("wingateWF: writing...");
1002     open(OUT, ">$file");
1003     foreach (@wingateNow) {
1004         print OUT "$_\n";
1005     }
1006     close OUT;
1007 }
1008
1009 sub factoidCheck {
1010     if (@_) {
1011         &ScheduleThis(720, "factoidCheck");
1012         return if ($_[0] eq "2");       # defer.
1013     }
1014
1015     my @list    = &searchTable("factoids", "factoid_key", "factoid_key", " #DEL#");
1016     my $stale   = &getChanConfDefault("factoidDeleteDelay", 14) *60*60*24;
1017     if ($stale < 1) {
1018         # disable it since it's "illegal".
1019         return;
1020     }
1021
1022     my $time    = time();
1023
1024     foreach (@list) {
1025         my $age = &getFactInfo($_, "modified_time");    
1026
1027         if (!defined $age or $age !~ /^\d+$/) {
1028             if (scalar @list > 50) {
1029                 if (!$cache{warnDel}) {
1030                     &WARN("list is over 50 (".scalar(@list)."... giving it a miss.");
1031                     $cache{warnDel} = 1;
1032                     last;
1033                 }
1034             }
1035
1036             &WARN("del factoid: old cruft (no time): $_");
1037             &delFactoid($_);
1038             next;
1039         }
1040
1041         next unless ($time - $age > $stale);
1042
1043         my $fix = $_;
1044         $fix =~ s/ #DEL#$//g;
1045         my $agestr = &Time2String($time - $age);
1046         &status("safedel: Removing '$_' for good. [$agestr old]");
1047
1048         &delFactoid($_);
1049     }
1050 }
1051
1052 sub dccStatus {
1053     return unless (scalar keys %{ $dcc{CHAT} });
1054
1055     if (@_) {
1056         &ScheduleThis(10, "dccStatus");
1057         return if ($_[0] eq "2");       # defer.
1058     }
1059
1060     my $time = strftime("%H:%M", localtime(time()) );
1061
1062     my $c;
1063     foreach (keys %channels) {
1064         my $c           = $_;
1065         my $users       = keys %{ $channels{$c}{''} };
1066         my $chops       = keys %{ $channels{$c}{o}  };
1067         my $bans        = keys %{ $channels{$c}{b}  };
1068
1069         my $txt = "[$time] $c: $users members ($chops chops), $bans bans";
1070         foreach (keys %{ $dcc{'CHAT'} }) {
1071             next unless (exists $channels{$c}{''}{lc $_});
1072             $conn->privmsg($dcc{'CHAT'}{$_}, $txt);
1073         }
1074     }
1075 }
1076
1077 sub scheduleList {
1078     ###
1079     # custom:
1080     #   a - time == now.
1081     #   b - weird time.
1082     ###
1083
1084     &DEBUG("sched:");
1085     foreach (keys %{ $irc->{_queue} }) {
1086         my $q = $_;
1087
1088         my $sched;
1089         foreach (keys %sched) {
1090             next unless ($q eq $sched{$_});
1091             $sched = $_;
1092             last;
1093         }
1094
1095         my $time = $irc->{_queue}->{$q}->[0] - time();
1096
1097         if (defined $sched) {
1098             &DEBUG("   $sched($q): ".&Time2String($time) );
1099         } else {
1100             &DEBUG("   NULL($q): ".&Time2String($time) );
1101         }
1102     }
1103
1104     &DEBUG("end of sList.");
1105 }
1106
1107 sub mkBackup {
1108     my($file, $time)    = @_;
1109     my $backup          = 0;
1110
1111     if (! -f $file) {
1112         &VERB("mkB: file '$file' does not exist.",2);
1113         return;
1114     }
1115
1116     my $age     = "New";
1117     if ( -e "$file~" ) {
1118         $backup++       if ((stat $file)[9] - (stat "$file~")[9] > $time);
1119         my $delta       = time() - (stat "$file~")[9];
1120         $age            = &Time2String($delta);
1121     } else {
1122         $backup++;
1123     }
1124
1125     return unless ($backup);
1126
1127     ### TODO: do internal copying.
1128     &status("Backup: $file ($age)");
1129     CORE::system("/bin/cp $file $file~");
1130 }
1131
1132 1;