]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/Schedulers.pl
uptime -> Uptime
[infobot.git] / src / IRC / Schedulers.pl
1 #
2 # ProcessExtra.pl: Extensions to Process.pl
3 #          Author: dms
4 #         Version: v0.5 (20010124)
5 #         Created: 20000117
6 #
7
8 # use strict;   # TODO
9
10 use POSIX qw(strftime);
11 use vars qw(%sched %schedule);
12
13 # format: function name = (
14 #       str     chanconfdefault,
15 #       int     internaldefault,
16 #       bool    deferred,
17 #       int     next run,               (optional)
18 # )
19
20 #%schedule = {
21 #       uptimeLoop => ("", 60, 1),
22 #};
23
24 sub setupSchedulersII {
25     foreach (keys %schedule) {
26         &queueTask($_, @{ $schedule{$_} });
27     }
28 }
29
30 sub queueTask {
31     my($codename, $chanconfdef, $intervaldef, $defer) = @_;
32     my $t = &getChanConfDefault($chanconfdef, $intervaldef);
33     my $waittime = &getRandomInt($t);
34
35     if (!defined $waittime) {
36         &WARN("interval == waittime == UNDEF for $codename.");
37         return;
38     }
39
40     my $time = $schedule{$codename}[3];
41     if (defined $time and $time > time()) {
42         &WARN("Sched for $codename already exists 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);
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);
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) *60*60*24;
263     my $delete   = 0;
264
265     if ($param{'DBType'} =~ /^(pgsql|mysql|sqlite)/i) {
266         my $query;
267
268         if ($param{'DBType'} =~ /^mysql|sqlite$/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);
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);
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);
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)$/i) {
559         foreach $nick (keys %seencache) {
560             my $retval = &sqlReplace("seen", {
561                         nick    => lc $seencache{$nick}{'nick'},
562                         time    => $seencache{$nick}{'time'},
563                         host    => $seencache{$nick}{'host'},
564                         channel => $seencache{$nick}{'chan'},
565                         message => $seencache{$nick}{'msg'},
566             } );
567
568             delete $seencache{$nick};
569             $flushed++;
570         }
571     } else {
572         &DEBUG("seenFlush: NO VALID FACTOID SUPPORT?");
573     }
574
575     &status("Seen: Flushed $flushed entries.")  if ($flushed);
576     &VERB(sprintf("  new seen: %03.01f%% (%d/%d)",
577         $stats{'new'}*100/($stats{'count_old'} || 1),
578         $stats{'new'}, ( $stats{'count_old'} || 1) ), 2) if ($stats{'new'});
579     &VERB(sprintf("  now seen: %3.1f%% (%d/%d)",
580         $stats{'old'}*100 / ( &countKeys("seen") || 1),
581         $stats{'old'}, &countKeys("seen") ), 2)         if ($stats{'old'});
582
583     &WARN("scalar keys seenflush != 0!")        if (scalar keys %seenflush);
584 }
585
586 sub leakCheck {
587     my ($blah1,$blah2);
588     my $count = 0;
589
590     if (@_) {
591         &ScheduleThis(240, "leakCheck");
592         return if ($_[0] eq "2");
593     }
594
595     # flood. this is dealt with in floodLoop()
596     foreach $blah1 (keys %flood) {
597         foreach $blah2 (keys %{ $flood{$blah1} }) {
598             $count += scalar(keys %{ $flood{$blah1}{$blah2} });
599         }
600     }
601     &VERB("leak: hash flood has $count total keys.",2);
602
603     # floodjoin.
604     $count = 0;
605     foreach $blah1 (keys %floodjoin) {
606         foreach $blah2 (keys %{ $floodjoin{$blah1} }) {
607             $count += scalar(keys %{ $floodjoin{$blah1}{$blah2} });
608         }
609     }
610     &VERB("leak: hash floodjoin has $count total keys.",2);
611
612     # floodwarn.
613     $count = scalar(keys %floodwarn);
614     &VERB("leak: hash floodwarn has $count total keys.",2);
615
616     my $chan;
617     foreach $chan (grep /[A-Z]/, keys %channels) {
618         &DEBUG("leak: chan => '$chan'.");
619         my ($i,$j);
620         foreach $i (keys %{ $channels{$chan} }) {
621             foreach (keys %{ $channels{$chan}{$i} }) {
622                 &DEBUG("leak:   \$channels{$chan}{$i}{$_} ...");
623             }
624         }
625     }
626
627     # chanstats
628     $count = scalar(keys %chanstats);
629     &VERB("leak: hash chanstats has $count total keys.",2);
630
631     # nuh.
632     my $delete  = 0;
633     foreach (keys %nuh) {
634         next if (&IsNickInAnyChan($_));
635         next if (exists $dcc{CHAT}{$_});
636
637         delete $nuh{$_};
638         $delete++;
639     }
640
641     &status("leak: $delete nuh{} items deleted; now have ".
642                                 scalar(keys %nuh) ) if ($delete);
643 }
644
645 sub ignoreCheck {
646     if (@_) {
647         &ScheduleThis(60, "ignoreCheck");
648         return if ($_[0] eq "2");       # defer.
649     }
650
651     my $time    = time();
652     my $count   = 0;
653
654     foreach (keys %ignore) {
655         my $chan = $_;
656
657         foreach (keys %{ $ignore{$chan} }) {
658             my @array = @{ $ignore{$chan}{$_} };
659
660             next unless ($array[0] and $time > $array[0]);
661
662             delete $ignore{$chan}{$_};
663             &status("ignore: $_/$chan has expired.");
664             $count++;
665         }
666     }
667
668     $cache{ignoreCheckTime} = time();
669
670     &VERB("ignore: $count items deleted.",2);
671 }
672
673 sub ircCheck {
674     if (@_) {
675         &ScheduleThis(15, "ircCheck");
676         return if ($_[0] eq "2");       # defer.
677     }
678
679     $cache{statusSafe} = 1;
680     foreach (sort keys %conns) {
681         $conn=$conns{$_};
682         my $mynick=$conn->nick();
683         &DEBUG("ircCheck for $_");
684         my @join = &getJoinChans(1);
685         if (scalar @join) {
686             &FIXME('ircCheck: found channels to join! ' . join(',',@join));
687             &joinNextChan();
688         }
689
690         # TODO: fix on_disconnect()
691
692         if (time() - $msgtime > 3600) {
693             # TODO: shouldn't we use cache{connect} somewhere?
694             if (exists $cache{connect}) {
695                 &WARN("ircCheck: no msg for 3600 and disco'd! reconnecting!");
696                 $msgtime = time();      # just in case.
697                 &ircloop();
698                 delete $cache{connect};
699             } else {
700                 &status('ircCheck: possible lost in space; checking.'.
701                     scalar(gmtime) );
702                 &msg($mynick, "TEST");
703                 $cache{connect} = time();
704             }
705         }
706
707         if (grep /^\s*$/, keys %channels) {
708             &WARN('ircCheck: we have a NULL chan in hash channels? removing!');
709             if (!exists $channels{''}) {
710                 &DEBUG('ircCheck: this should never happen!');
711             }
712
713             delete $channels{''};
714         }
715     }
716
717     $cache{statusSafe} = 0;
718
719     ### USER FILE.
720     if ($utime_userfile > $wtime_userfile and time() - $wtime_userfile > 3600) {
721         &writeUserFile();
722         $wtime_userfile = time();
723     }
724     ### CHAN FILE.
725     if ($utime_chanfile > $wtime_chanfile and time() - $wtime_chanfile > 3600) {
726         &writeChanFile();
727         $wtime_chanfile = time();
728     }
729 }
730
731 sub miscCheck {
732     if (@_) {
733         &ScheduleThis(120, "miscCheck");
734         return if ($_[0] eq "2");       # defer.
735     }
736
737     # SHM check.
738     my @ipcs;
739     if ( -x "/usr/bin/ipcs") {
740         @ipcs = `/usr/bin/ipcs`;
741     } else {
742         &WARN("ircCheck: no 'ipcs' binary.");
743         return;
744     }
745
746     # make backup of important files.
747     &mkBackup( $bot_state_dir."/blootbot.chan", 60*60*24*3);
748     &mkBackup( $bot_state_dir."/blootbot.users", 60*60*24*3);
749     &mkBackup( $bot_base_dir."/blootbot-news.txt", 60*60*24*1);
750
751     # flush cache{lobotomy}
752     foreach (keys %{ $cache{lobotomy} }) {
753         next unless (time() - $cache{lobotomy}{$_} > 60*60);
754         delete $cache{lobotomy}{$_};
755     }
756
757     ### check modules if they've been modified. might be evil.
758     &reloadAllModules();
759
760     # shmid stale remove.
761     foreach (@ipcs) {
762         chop;
763
764         # key, shmid, owner, perms, bytes, nattch
765         next unless (/^(0x\d+) (\d+)\s+(\S+)\s+(\d+)\s+(\d+)\s+/);
766
767         my ($shmid, $size) = ($2,$5);
768         next unless ($shmid != $shm and $size == 2000);
769         my $z   = &shmRead($shmid);
770         if ($z =~ /^(\S+):(\d+):(\d+): /) {
771             my $n       = $1;
772             my $pid     = $2;
773             my $time    = $3;
774             next if (time() - $time < 60*60);
775             # FIXME remove not-pid shm if parent process dead
776             next if ($pid == $bot_pid);
777             # don't touch other bots, if they're running.
778             next unless ($param{ircUser} =~ /^\Q$n\E$/);
779         } else {
780             &DEBUG("shm: $shmid is not ours or old blootbot => ($z)");
781             next;
782         }
783
784         &status("SHM: nuking shmid $shmid");
785         CORE::system("/usr/bin/ipcrm shm $shmid >/dev/null");
786     }
787 }
788
789 sub miscCheck2 {
790     if (@_) {
791         &ScheduleThis(240, "miscCheck2");
792         return if ($_[0] eq "2");       # defer.
793     }
794
795     # debian check.
796     opendir(DEBIAN, "$bot_state_dir/debian");
797     foreach ( grep /gz$/, readdir(DEBIAN) ) {
798         my $exit = CORE::system("gzip -t $bot_state_dir/debian/$_");
799         next unless ($exit);
800
801         &status("debian: unlinking file => $_");
802         unlink "$bot_state_dir/debian/$_";
803     }
804     closedir DEBIAN;
805
806     # compress logs that should have been compressed.
807     # TODO: use strftime?
808     my ($day,$month,$year) = (gmtime(time()))[3,4,5];
809     my $date = sprintf("%04d%02d%02d",$year+1900,$month+1,$day);
810
811     if (!opendir(DIR,"$bot_log_dir")) {
812         &ERROR("misccheck2: log dir $bot_log_dir does not exist.");
813         closedir DIR;
814         return -1;
815     }
816
817     while (my $f = readdir(DIR)) {
818         next unless ( -f "$bot_log_dir/$f");
819         next if ($f =~ /gz|bz2/);
820         next unless ($f =~ /(\d{8})/);
821         next if ($date eq $1);
822
823         &compress("$bot_log_dir/$f");
824     }
825     closedir DIR;
826 }
827
828 ### this is semi-scheduled
829 sub getNickInUse {
830 # FIXME: broken for multiple connects
831 #    if ($ident eq $param{'ircNick'}) {
832 #       &status("okay, got my nick back.");
833 #       return;
834 #    }
835 #
836 #    if (@_) {
837 #       &ScheduleThis(30, "getNickInUse");
838 #       return if ($_[0] eq "2");       # defer.
839 #    }
840 #
841 #    &nick( $param{'ircNick'} );
842 }
843
844 sub uptimeLoop {
845     return if (!defined &uptimeWriteFile);
846 #    return unless &IsChanConf('Uptime');
847
848     if (@_) {
849         &ScheduleThis(60, 'uptimeLoop');
850         return if ($_[0] eq '2');       # defer.
851     }
852
853     &uptimeWriteFile();
854 }
855
856 sub slashdotLoop {
857
858     if (@_) {
859         &ScheduleThis(60, 'slashdotLoop');
860         return if ($_[0] eq "2");
861     }
862
863     my @chans = &ChanConfList('slashdotAnnounce');
864     return unless (scalar @chans);
865
866     &Forker('slashdot', sub {
867         my $line = &Slashdot::slashdotAnnounce();
868         return unless (defined $line);
869
870         foreach (@chans) {
871             next unless (&::validChan($_));
872
873             &::status("sending slashdot update to $_.");
874             &notice($_, "Slashdot: $line");
875         }
876     } );
877 }
878
879 sub plugLoop {
880
881     if (@_) {
882         &ScheduleThis(60, 'plugLoop');
883         return if ($_[0] eq "2");
884     }
885
886     my @chans = &ChanConfList('plugAnnounce');
887     return unless (scalar @chans);
888
889     &Forker('Plug', sub {
890         my $line = &Plug::plugAnnounce();
891         return unless (defined $line);
892
893         foreach (@chans) {
894             next unless (&::validChan($_));
895
896             &::status("sending plug update to $_.");
897             &notice($_, "Plug: $line");
898         }
899     } );
900 }
901
902 sub kernelLoop {
903     if (@_) {
904         &ScheduleThis(240, "kernelLoop");
905         return if ($_[0] eq "2");
906     }
907
908     my @chans = &ChanConfList("kernelAnnounce");
909     return unless (scalar @chans);
910
911     &Forker("kernel", sub {
912         my @data = &Kernel::kernelAnnounce();
913
914         foreach (@chans) {
915             next unless (&::validChan($_));
916
917             &::status("sending kernel update to $_.");
918             my $c = $_;
919             foreach (@data) {
920                 &notice($c, "Kernel: $_");
921             }
922         }
923     } );
924 }
925
926 sub wingateCheck {
927     return unless &IsChanConf("wingate");
928
929     ### FILE CACHE OF OFFENDING WINGATES.
930     foreach (grep /^$host$/, @wingateBad) {
931         &status("Wingate: RUNNING ON $host BY $who");
932         &ban("*!*\@$host", "") if &IsChanConf("wingateBan");
933
934         my $reason      = &getChanConf("wingateKick");
935
936         next unless ($reason);
937         &kick($who, "", $reason)
938     }
939
940     ### RUN CACHE OF TRIED WINGATES.
941     if (grep /^$host$/, @wingateCache) {
942         push(@wingateNow, $host);       # per run.
943         push(@wingateCache, $host);     # cache per run.
944     } else {
945         &DEBUG("Already scanned $host. good.");
946     }
947
948     my $interval = &getChanConfDefault("wingateInterval", 60); # seconds.
949     return if (defined $forked{'wingate'});
950     return if (time() - $wingaterun <= $interval);
951     return unless (scalar(keys %wingateToDo));
952
953     $wingaterun = time();
954
955     &Forker("wingate", sub { &Wingate::Wingates(keys %wingateToDo); } );
956     undef @wingateNow;
957 }
958
959 ### TODO: ??
960 sub wingateWriteFile {
961     if (@_) {
962         &ScheduleThis(60, "wingateWriteFile");
963         return if ($_[0] eq "2");       # defer.
964     }
965
966     return unless (scalar @wingateCache);
967
968     my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
969     if ($bot_pid != $$) {
970         &DEBUG("wingateWriteFile: Reorganising!");
971
972         open(IN, $file);
973         while (<IN>) {
974             chop;
975             push(@wingateNow, $_);
976         }
977         close IN;
978
979         # very lame hack.
980         my %hash = map { $_ => 1 } @wingateNow;
981         @wingateNow = sort keys %hash;
982     }
983
984     &DEBUG("wingateWF: writing...");
985     open(OUT, ">$file");
986     foreach (@wingateNow) {
987         print OUT "$_\n";
988     }
989     close OUT;
990 }
991
992 sub factoidCheck {
993     if (@_) {
994         &ScheduleThis(720, "factoidCheck");
995         return if ($_[0] eq "2");       # defer.
996     }
997
998     my @list    = &searchTable("factoids", "factoid_key", "factoid_key", " #DEL#");
999     my $stale   = &getChanConfDefault("factoidDeleteDelay", 14) *60*60*24;
1000     if ($stale < 1) {
1001         # disable it since it's "illegal".
1002         return;
1003     }
1004
1005     my $time    = time();
1006
1007     foreach (@list) {
1008         my $age = &getFactInfo($_, "modified_time");
1009
1010         if (!defined $age or $age !~ /^\d+$/) {
1011             if (scalar @list > 50) {
1012                 if (!$cache{warnDel}) {
1013                     &WARN("list is over 50 (".scalar(@list)."... giving it a miss.");
1014                     $cache{warnDel} = 1;
1015                     last;
1016                 }
1017             }
1018
1019             &WARN("del factoid: old cruft (no time): $_");
1020             &delFactoid($_);
1021             next;
1022         }
1023
1024         next unless ($time - $age > $stale);
1025
1026         my $fix = $_;
1027         $fix =~ s/ #DEL#$//g;
1028         my $agestr = &Time2String($time - $age);
1029         &status("safedel: Removing '$_' for good. [$agestr old]");
1030
1031         &delFactoid($_);
1032     }
1033 }
1034
1035 sub dccStatus {
1036     return unless (scalar keys %{ $dcc{CHAT} });
1037
1038     if (@_) {
1039         &ScheduleThis(10, "dccStatus");
1040         return if ($_[0] eq "2");       # defer.
1041     }
1042
1043     my $time = strftime("%H:%M", gmtime(time()) );
1044
1045     my $c;
1046     foreach (keys %channels) {
1047         my $c           = $_;
1048         my $users       = keys %{ $channels{$c}{''} };
1049         my $chops       = keys %{ $channels{$c}{o}  };
1050         my $bans        = keys %{ $channels{$c}{b}  };
1051
1052         my $txt = "[$time] $c: $users members ($chops chops), $bans bans";
1053         foreach (keys %{ $dcc{'CHAT'} }) {
1054             next unless (exists $channels{$c}{''}{lc $_});
1055             $conn->privmsg($dcc{'CHAT'}{$_}, $txt);
1056         }
1057     }
1058 }
1059
1060 sub scheduleList {
1061     ###
1062     # custom:
1063     #   a - time == now.
1064     #   b - weird time.
1065     ###
1066
1067     my $reply = "sched:";
1068     foreach (keys %{ $irc->{_queue}}) {
1069         my $q = $_;
1070         my $coderef = $irc->{_queue}->{$q}->[1];
1071         my $sched;
1072         foreach (keys %sched) {
1073             my $schedname = $_;
1074             next unless defined(\&$schedname);
1075             next unless ($coderef eq \&$schedname);
1076             $sched = $schedname;
1077             last;
1078         }
1079
1080         my $time = $irc->{_queue}->{$q}->[0] - time();
1081
1082         if (defined $sched) {
1083             $reply = "$reply, $sched($q):" . &Time2String($time);
1084         } else {
1085             $reply = "$reply, NULL($q):" . &Time2String($time);
1086         }
1087     }
1088
1089     &DEBUG("$reply");
1090 }
1091
1092 sub mkBackup {
1093     my($file, $time)    = @_;
1094     my $backup          = 0;
1095
1096     if (! -f $file) {
1097         &VERB("mkB: file '$file' does not exist.",2);
1098         return;
1099     }
1100
1101     my $age     = "New";
1102     if ( -e "$file~" ) {
1103         $backup++       if ((stat $file)[9] - (stat "$file~")[9] > $time);
1104         my $delta       = time() - (stat "$file~")[9];
1105         $age            = &Time2String($delta);
1106     } else {
1107         $backup++;
1108     }
1109
1110     return unless ($backup);
1111
1112     ### TODO: do internal copying.
1113     &status("Backup: $file ($age)");
1114     CORE::system("/bin/cp $file $file~");
1115 }
1116
1117 1;