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