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