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