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