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