]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/Schedulers.pl
- another round of patches from lear. "we love you, lear!" j/k :o
[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     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" => lc $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_state_dir."/blootbot.chan", 60*60*24*3);
821     &mkBackup( $bot_state_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     if (!opendir(DIR,"$bot_log_dir")) {
857         &ERROR("misccheck2: log dir $bot_log_dir does not exist.");
858         closedir DIR;
859         return -1;
860     }
861
862     while (my $f = readdir(DIR)) {
863         next unless ( -f "$bot_log_dir/$f");
864         next if ($f =~ /gz|bz2/);
865         next unless ($f =~ /(\d{8})/);
866         next if ($date eq $1);
867
868         &compress("$bot_log_dir/$f");
869     }
870     closedir DIR;
871 }
872
873 sub shmFlush {
874     return if ($$ != $::bot_pid); # fork protection.
875
876     if (@_) {
877         &ScheduleThis(5, "shmFlush");
878         return if ($_[0] eq "2");
879     }
880
881     my $time;
882     my $shmmsg = &shmRead($shm);
883     $shmmsg =~ s/\0//g;         # remove padded \0's.
884     if ($shmmsg =~ s/^(\d+): //) {
885         $time   = $1;
886     }
887
888     foreach (split '\|\|', $shmmsg) {
889         next if (/^$/);
890         &VERB("shm: Processing '$_'.",2);
891
892         if (/^DCC SEND (\S+) (\S+)$/) {
893             my ($nick,$file) = ($1,$2);
894             if (exists $dcc{'SEND'}{$who}) {
895                 &msg($nick, "DCC already active.");
896             } else {
897                 &DEBUG("shm: dcc sending $2 to $1.");
898                 $conn->new_send($1,$2);
899                 $dcc{'SEND'}{$who} = time();
900             }
901         } elsif (/^SET FORKPID (\S+) (\S+)/) {
902             $forked{$1}{PID} = $2;
903         } elsif (/^DELETE FORK (\S+)$/) {
904             delete $forked{$1};
905         } elsif (/^EVAL (.*)$/) {
906             &DEBUG("evaling '$1'.");
907             eval $1;
908         } else {
909             &DEBUG("shm: unknown msg. ($_)");
910         }
911     }
912
913     &shmWrite($shm,"") if ($shmmsg ne "");
914 }
915
916 ### this is semi-scheduled
917 sub getNickInUse {
918     if ($ident eq $param{'ircNick'}) {
919         &status("okay, got my nick back.");
920         return;
921     }
922
923     if (@_) {
924         &ScheduleThis(30, "getNickInUse");
925         return if ($_[0] eq "2");       # defer.
926     }
927
928     &nick( $param{'ircNick'} );
929 }
930
931 sub uptimeLoop {
932     return unless &IsChanConf("uptime");
933
934     if (@_) {
935         &ScheduleThis(60, "uptimeLoop");
936         return if ($_[0] eq "2");       # defer.
937     }
938
939     &uptimeWriteFile();
940 }
941
942 sub slashdotLoop {
943
944     if (@_) {
945         &ScheduleThis(60, "slashdotLoop");
946         return if ($_[0] eq "2");
947     }
948
949     my @chans = &ChanConfList("slashdotAnnounce");
950     return unless (scalar @chans);
951
952     &Forker("slashdot", sub {
953         my $line = &Slashdot::slashdotAnnounce();
954         return unless (defined $line);
955
956         foreach (@chans) {
957             next unless (&::validChan($_));
958
959             &::status("sending slashdot update to $_.");
960             &notice($_, "Slashdot: $line");
961         }
962     } );
963 }
964
965 sub freshmeatLoop {
966     if (@_) {
967         &ScheduleThis(60, "freshmeatLoop");
968         return if ($_[0] eq "2");
969     }
970
971     my @chans = &ChanConfList("freshmeatAnnounce");
972     return unless (scalar @chans);
973
974     &Forker("freshmeat", sub {
975         my $data = &Freshmeat::freshmeatAnnounce();
976
977         foreach (@chans) {
978             next unless (&::validChan($_));
979
980             &::status("sending freshmeat update to $_.");
981             &msg($_, $data);
982         }
983     } );
984 }
985
986 sub kernelLoop {
987     if (@_) {
988         &ScheduleThis(240, "kernelLoop");
989         return if ($_[0] eq "2");
990     }
991
992     my @chans = &ChanConfList("kernelAnnounce");
993     return unless (scalar @chans);
994
995     &Forker("kernel", sub {
996         my @data = &Kernel::kernelAnnounce();
997
998         foreach (@chans) {
999             next unless (&::validChan($_));
1000
1001             &::status("sending kernel update to $_.");
1002             my $c = $_;
1003             foreach (@data) {
1004                 &notice($c, "Kernel: $_");
1005             }
1006         }
1007     } );
1008 }
1009
1010 sub wingateCheck {
1011     return unless &IsChanConf("wingate");
1012
1013     ### FILE CACHE OF OFFENDING WINGATES.
1014     foreach (grep /^$host$/, @wingateBad) {
1015         &status("Wingate: RUNNING ON $host BY $who");
1016         &ban("*!*\@$host", "") if &IsChanConf("wingateBan");
1017
1018         my $reason      = &getChanConf("wingateKick");
1019
1020         next unless ($reason);
1021         &kick($who, "", $reason)
1022     }
1023
1024     ### RUN CACHE OF TRIED WINGATES.
1025     if (grep /^$host$/, @wingateCache) {
1026         push(@wingateNow, $host);       # per run.
1027         push(@wingateCache, $host);     # cache per run.
1028     } else {
1029         &DEBUG("Already scanned $host. good.");
1030     }
1031
1032     my $interval = &getChanConfDefault("wingateInterval", 60); # seconds.
1033     return if (defined $forked{'wingate'});
1034     return if (time() - $wingaterun <= $interval);
1035     return unless (scalar(keys %wingateToDo));
1036
1037     $wingaterun = time();
1038
1039     &Forker("wingate", sub { &Wingate::Wingates(keys %wingateToDo); } );
1040     undef @wingateNow;
1041 }
1042
1043 ### TODO.
1044 sub wingateWriteFile {
1045     if (@_) {
1046         &ScheduleThis(60, "wingateWriteFile");
1047         return if ($_[0] eq "2");       # defer.
1048     }
1049
1050     return unless (scalar @wingateCache);
1051
1052     my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
1053     if ($bot_pid != $$) {
1054         &DEBUG("wingateWriteFile: Reorganising!");
1055
1056         open(IN, $file);
1057         while (<IN>) {
1058             chop;
1059             push(@wingateNow, $_);
1060         }
1061         close IN;
1062
1063         # very lame hack.
1064         my %hash = map { $_ => 1 } @wingateNow;
1065         @wingateNow = sort keys %hash;
1066     }
1067
1068     &DEBUG("wingateWF: writing...");
1069     open(OUT, ">$file");
1070     foreach (@wingateNow) {
1071         print OUT "$_\n";
1072     }
1073     close OUT;
1074 }
1075
1076 sub factoidCheck {
1077     if (@_) {
1078         &ScheduleThis(720, "factoidCheck");
1079         return if ($_[0] eq "2");       # defer.
1080     }
1081
1082     my @list    = &searchTable("factoids", "factoid_key", "factoid_key", " #DEL#");
1083     my $stale   = &getChanConfDefault("factoidDeleteDelay", 14) *60*60*24;
1084     if ($stale < 1) {
1085         # disable it since it's "illegal".
1086         return;
1087     }
1088
1089     my $time    = time();
1090
1091     foreach (@list) {
1092         my $age = &getFactInfo($_, "modified_time");    
1093
1094         if (!defined $age or $age !~ /^\d+$/) {
1095             if (scalar @list > 50) {
1096                 if (!$cache{warnDel}) {
1097                     &WARN("list is over 50 (".scalar(@list)."... giving it a miss.");
1098                     $cache{warnDel} = 1;
1099                     last;
1100                 }
1101             }
1102
1103             &WARN("del factoid: old cruft (no time): $_");
1104             &delFactoid($_);
1105             next;
1106         }
1107
1108         next unless ($time - $age > $stale);
1109
1110         my $fix = $_;
1111         $fix =~ s/ #DEL#$//g;
1112         my $agestr = &Time2String($time - $age);
1113         &status("safedel: Removing '$_' for good. [$agestr old]");
1114
1115         &delFactoid($_);
1116     }
1117 }
1118
1119 sub dccStatus {
1120     return unless (scalar keys %{ $dcc{CHAT} });
1121
1122     if (@_) {
1123         &ScheduleThis(10, "dccStatus");
1124         return if ($_[0] eq "2");       # defer.
1125     }
1126
1127     my $time = strftime("%H:%M", localtime(time()) );
1128
1129     my $c;
1130     foreach (keys %channels) {
1131         my $c           = $_;
1132         my $users       = keys %{ $channels{$c}{''} };
1133         my $chops       = keys %{ $channels{$c}{o}  };
1134         my $bans        = keys %{ $channels{$c}{b}  };
1135
1136         my $txt = "[$time] $c: $users members ($chops chops), $bans bans";
1137         foreach (keys %{ $dcc{'CHAT'} }) {
1138             next unless (exists $channels{$c}{''}{lc $_});
1139             $conn->privmsg($dcc{'CHAT'}{$_}, $txt);
1140         }
1141     }
1142 }
1143
1144 sub scheduleList {
1145     ###
1146     # custom:
1147     #   a - time == now.
1148     #   b - weird time.
1149     ###
1150
1151     &DEBUG("sched:");
1152     foreach (keys %{ $irc->{_queue} }) {
1153         my $q = $_;
1154
1155         my $sched;
1156         foreach (keys %sched) {
1157             next unless ($q eq $sched{$_});
1158             $sched = $_;
1159             last;
1160         }
1161
1162         my $time = $irc->{_queue}->{$q}->[0] - time();
1163
1164         if (defined $sched) {
1165             &DEBUG("   $sched($q): ".&Time2String($time) );
1166         } else {
1167             &DEBUG("   NULL($q): ".&Time2String($time) );
1168         }
1169     }
1170
1171     &DEBUG("end of sList.");
1172 }
1173
1174 sub getChanConfDefault {
1175     my($what, $default, $chan) = @_;
1176
1177     if (exists $param{$what}) {
1178         if (!exists $cache{config}{$what}) {
1179             &status("conf: backward-compat: found param{$what} ($param{$what}) instead.");
1180             $cache{config}{$what} = 1;
1181         }
1182
1183         return $param{$what};
1184     }
1185
1186     my $val = &getChanConf($what, $chan);
1187     if (defined $val) {
1188         return $val;
1189     }
1190
1191     $param{$what}       = $default;
1192     &status("conf: auto-setting param{$what} = $default");
1193     $cache{config}{$what} = 1;
1194
1195     return $default;
1196 }
1197
1198 sub mkBackup {
1199     my($file, $time)    = @_;
1200     my $backup          = 0;
1201
1202     if (! -f $file) {
1203         &VERB("mkB: file '$file' does not exist.",2);
1204         return;
1205     }
1206
1207     my $age     = "New";
1208     if ( -e "$file~" ) {
1209         $backup++       if ((stat $file)[9] - (stat "$file~")[9] > $time);
1210         my $delta       = time() - (stat "$file~")[9];
1211         $age            = &Time2String($delta);
1212     } else {
1213         $backup++;
1214     }
1215
1216     return unless ($backup);
1217
1218     ### TODO: do internal copying.
1219     &status("Backup: $file ($age)");
1220     CORE::system("/bin/cp $file $file~");
1221 }
1222
1223 1;