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