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