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