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