]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/Schedulers.pl
* Add back in missing semicolon
[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       }
723     if ($ident !~ /^\Q$param{ircNick}\E$/) {
724         # this does not work unfortunately.
725         &WARN("ircCheck: ident($ident) != param{ircNick}($param{ircNick}).");
726
727         # this check is misleading... perhaps we should do a notify.
728         if (! &IsNickInAnyChan( $param{ircNick} ) ) {
729             &DEBUG("$param{ircNick} not in use... changing!");
730             &nick( $param{ircNick} );
731         } else {
732             &WARN("$param{ircNick} is still in use...");
733         }
734     }
735
736     $cache{statusSafe} = 0;
737
738     ### USER FILE.
739     if ($utime_userfile > $wtime_userfile and time() - $wtime_userfile > 3600) {
740         &writeUserFile();
741         $wtime_userfile = time();
742     }
743     ### CHAN FILE.
744     if ($utime_chanfile > $wtime_chanfile and time() - $wtime_chanfile > 3600) {
745         &writeChanFile();
746         $wtime_chanfile = time();
747     }
748 }
749
750 sub miscCheck {
751     if (@_) {
752         &ScheduleThis(120, "miscCheck");
753         return if ($_[0] eq "2");       # defer.
754     }
755
756     # SHM check.
757     my @ipcs;
758     if ( -x "/usr/bin/ipcs") {
759         @ipcs = `/usr/bin/ipcs`;
760     } else {
761         &WARN("ircCheck: no 'ipcs' binary.");
762         return;
763     }
764
765     # make backup of important files.
766     &mkBackup( $bot_state_dir."/blootbot.chan", 60*60*24*3);
767     &mkBackup( $bot_state_dir."/blootbot.users", 60*60*24*3);
768     &mkBackup( $bot_base_dir."/blootbot-news.txt", 60*60*24*1);
769
770     # flush cache{lobotomy}
771     foreach (keys %{ $cache{lobotomy} }) {
772         next unless (time() - $cache{lobotomy}{$_} > 60*60);
773         delete $cache{lobotomy}{$_};
774     }
775
776     ### check modules if they've been modified. might be evil.
777     &reloadAllModules();
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 =~ /^(\S+):(\d+):(\d+): /) {
790             my $n       = $1;
791             my $pid     = $2;
792             my $time    = $3;
793             next if (time() - $time < 60*60);
794             # FIXME remove not-pid shm if parent process dead
795             next if ($pid == $bot_pid);
796             # don't touch other bots, if they're running.
797             next unless ($param{ircUser} =~ /^\Q$n\E$/);
798         } else {
799             &DEBUG("shm: $shmid is not ours or old blootbot => ($z)");
800             next;
801         }
802
803         &status("SHM: nuking shmid $shmid");
804         CORE::system("/usr/bin/ipcrm shm $shmid >/dev/null");
805     }
806 }
807
808 sub miscCheck2 {
809     if (@_) {
810         &ScheduleThis(240, "miscCheck2");
811         return if ($_[0] eq "2");       # defer.
812     }
813
814     # debian check.
815     opendir(DEBIAN, "$bot_state_dir/debian");
816     foreach ( grep /gz$/, readdir(DEBIAN) ) {
817         my $exit = CORE::system("gzip -t $bot_state_dir/debian/$_");
818         next unless ($exit);
819
820         &status("debian: unlinking file => $_");
821         unlink "$bot_state_dir/debian/$_";
822     }
823     closedir DEBIAN;
824
825     # compress logs that should have been compressed.
826     # TODO: use strftime?
827     my ($day,$month,$year) = (gmtime(time()))[3,4,5];
828     my $date = sprintf("%04d%02d%02d",$year+1900,$month+1,$day);
829
830     if (!opendir(DIR,"$bot_log_dir")) {
831         &ERROR("misccheck2: log dir $bot_log_dir does not exist.");
832         closedir DIR;
833         return -1;
834     }
835
836     while (my $f = readdir(DIR)) {
837         next unless ( -f "$bot_log_dir/$f");
838         next if ($f =~ /gz|bz2/);
839         next unless ($f =~ /(\d{8})/);
840         next if ($date eq $1);
841
842         &compress("$bot_log_dir/$f");
843     }
844     closedir DIR;
845 }
846
847 ### this is semi-scheduled
848 sub getNickInUse {
849 # FIXME: broken for multiple connects
850 #    if ($ident eq $param{'ircNick'}) {
851 #       &status("okay, got my nick back.");
852 #       return;
853 #    }
854 #
855 #    if (@_) {
856 #       &ScheduleThis(30, "getNickInUse");
857 #       return if ($_[0] eq "2");       # defer.
858 #    }
859 #
860 #    &nick( $param{'ircNick'} );
861 }
862
863 sub uptimeLoop {
864     return if (!defined &uptimeWriteFile);
865 #    return unless &IsParam('Uptime');
866
867     if (@_) {
868         &ScheduleThis(60, 'uptimeLoop');
869         return if ($_[0] eq '2');       # defer.
870     }
871
872     &uptimeWriteFile();
873 }
874
875 sub slashdotLoop {
876
877     if (@_) {
878         &ScheduleThis(60, 'slashdotLoop');
879         return if ($_[0] eq "2");
880     }
881
882     my @chans = &ChanConfList('slashdotAnnounce');
883     return unless (scalar @chans);
884
885     &Forker('slashdot', sub {
886         my $line = &Slashdot::slashdotAnnounce();
887         return unless (defined $line);
888
889         foreach (@chans) {
890             next unless (&::validChan($_));
891
892             &::status("sending slashdot update to $_.");
893             &notice($_, "Slashdot: $line");
894         }
895     } );
896 }
897
898 sub plugLoop {
899
900     if (@_) {
901         &ScheduleThis(60, 'plugLoop');
902         return if ($_[0] eq "2");
903     }
904
905     my @chans = &ChanConfList('plugAnnounce');
906     return unless (scalar @chans);
907
908     &Forker('Plug', sub {
909         my $line = &Plug::plugAnnounce();
910         return unless (defined $line);
911
912         foreach (@chans) {
913             next unless (&::validChan($_));
914
915             &::status("sending plug update to $_.");
916             &notice($_, "Plug: $line");
917         }
918     } );
919 }
920
921 sub kernelLoop {
922     if (@_) {
923         &ScheduleThis(240, "kernelLoop");
924         return if ($_[0] eq "2");
925     }
926
927     my @chans = &ChanConfList("kernelAnnounce");
928     return unless (scalar @chans);
929
930     &Forker("Kernel", sub {
931         my @data = &Kernel::kernelAnnounce();
932
933         foreach (@chans) {
934             next unless (&::validChan($_));
935
936             &::status("sending kernel update to $_.");
937             my $c = $_;
938             foreach (@data) {
939                 &notice($c, "Kernel: $_");
940             }
941         }
942     } );
943 }
944
945 sub wingateCheck {
946     return unless &IsChanConf('Wingate') > 0;
947
948     ### FILE CACHE OF OFFENDING WINGATES.
949     foreach (grep /^$host$/, @wingateBad) {
950         &status("Wingate: RUNNING ON $host BY $who");
951         &ban("*!*\@$host", "") if &IsChanConf('wingateBan') > 0;
952
953         my $reason      = &getChanConf('wingateKick');
954
955         next unless ($reason);
956         &kick($who, "", $reason)
957     }
958
959     ### RUN CACHE OF TRIED WINGATES.
960     if (grep /^$host$/, @wingateCache) {
961         push(@wingateNow, $host);       # per run.
962         push(@wingateCache, $host);     # cache per run.
963     } else {
964         &DEBUG("Already scanned $host. good.");
965     }
966
967     my $interval = &getChanConfDefault('wingateInterval', 60, $chan); # seconds.
968     return if (defined $forked{'Wingate'});
969     return if (time() - $wingaterun <= $interval);
970     return unless (scalar(keys %wingateToDo));
971
972     $wingaterun = time();
973
974     &Forker('Wingate', sub { &Wingate::Wingates(keys %wingateToDo); } );
975     undef @wingateNow;
976 }
977
978 ### TODO: ??
979 sub wingateWriteFile {
980     if (@_) {
981         &ScheduleThis(60, 'wingateWriteFile');
982         return if ($_[0] eq "2");       # defer.
983     }
984
985     return unless (scalar @wingateCache);
986
987     my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
988     if ($bot_pid != $$) {
989         &DEBUG('wingateWriteFile: Reorganising!');
990
991         open(IN, $file);
992         while (<IN>) {
993             chop;
994             push(@wingateNow, $_);
995         }
996         close IN;
997
998         # very lame hack.
999         my %hash = map { $_ => 1 } @wingateNow;
1000         @wingateNow = sort keys %hash;
1001     }
1002
1003     &DEBUG('wingateWF: writing...');
1004     open(OUT, ">$file");
1005     foreach (@wingateNow) {
1006         print OUT "$_\n";
1007     }
1008     close OUT;
1009 }
1010
1011 sub factoidCheck {
1012     if (@_) {
1013         &ScheduleThis(720, "factoidCheck");
1014         return if ($_[0] eq "2");       # defer.
1015     }
1016
1017     my @list    = &searchTable("factoids", "factoid_key", "factoid_key", " #DEL#");
1018     my $stale   = &getChanConfDefault("factoidDeleteDelay", 14, $chan) *60*60*24;
1019     if ($stale < 1) {
1020         # disable it since it's "illegal".
1021         return;
1022     }
1023
1024     my $time    = time();
1025
1026     foreach (@list) {
1027         my $age = &getFactInfo($_, "modified_time");
1028
1029         if (!defined $age or $age !~ /^\d+$/) {
1030             if (scalar @list > 50) {
1031                 if (!$cache{warnDel}) {
1032                     &WARN("list is over 50 (".scalar(@list)."... giving it a miss.");
1033                     $cache{warnDel} = 1;
1034                     last;
1035                 }
1036             }
1037
1038             &WARN("del factoid: old cruft (no time): $_");
1039             &delFactoid($_);
1040             next;
1041         }
1042
1043         next unless ($time - $age > $stale);
1044
1045         my $fix = $_;
1046         $fix =~ s/ #DEL#$//g;
1047         my $agestr = &Time2String($time - $age);
1048         &status("safedel: Removing '$_' for good. [$agestr old]");
1049
1050         &delFactoid($_);
1051     }
1052 }
1053
1054 sub dccStatus {
1055     return unless (scalar keys %{ $dcc{CHAT} });
1056
1057     if (@_) {
1058         &ScheduleThis(10, "dccStatus");
1059         return if ($_[0] eq "2");       # defer.
1060     }
1061
1062     my $time = strftime("%H:%M", gmtime(time()) );
1063
1064     my $c;
1065     foreach (keys %channels) {
1066         my $c           = $_;
1067         my $users       = keys %{ $channels{$c}{''} };
1068         my $chops       = keys %{ $channels{$c}{o}  };
1069         my $bans        = keys %{ $channels{$c}{b}  };
1070
1071         my $txt = "[$time] $c: $users members ($chops chops), $bans bans";
1072         foreach (keys %{ $dcc{'CHAT'} }) {
1073             next unless (exists $channels{$c}{''}{lc $_});
1074             $conn->privmsg($dcc{'CHAT'}{$_}, $txt);
1075         }
1076     }
1077 }
1078
1079 sub scheduleList {
1080     ###
1081     # custom:
1082     #   a - time == now.
1083     #   b - weird time.
1084     ###
1085
1086     my $reply = "sched:";
1087     foreach (keys %{ $irc->{_queue}}) {
1088         my $q = $_;
1089         my $coderef = $irc->{_queue}->{$q}->[1];
1090         my $sched;
1091         foreach (keys %sched) {
1092             my $schedname = $_;
1093             next unless defined(\&$schedname);
1094             next unless ($coderef eq \&$schedname);
1095             $sched = $schedname;
1096             last;
1097         }
1098
1099         my $time = $irc->{_queue}->{$q}->[0] - time();
1100
1101         if (defined $sched) {
1102             $reply = "$reply, $sched($q):" . &Time2String($time);
1103         } else {
1104             $reply = "$reply, NULL($q):" . &Time2String($time);
1105         }
1106     }
1107
1108     &DEBUG("$reply");
1109 }
1110
1111 sub mkBackup {
1112     my($file, $time)    = @_;
1113     my $backup          = 0;
1114
1115     if (! -f $file) {
1116         &VERB("mkB: file '$file' does not exist.",2);
1117         return;
1118     }
1119
1120     my $age     = "New";
1121     if ( -e "$file~" ) {
1122         $backup++       if ((stat $file)[9] - (stat "$file~")[9] > $time);
1123         my $delta       = time() - (stat "$file~")[9];
1124         $age            = &Time2String($delta);
1125     } else {
1126         $backup++;
1127     }
1128
1129     return unless ($backup);
1130
1131     ### TODO: do internal copying.
1132     &status("Backup: $file ($age)");
1133     CORE::system("/bin/cp $file $file~");
1134 }
1135
1136 1;