]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/Schedulers.pl
re-order and wait a sec for nickserv to catch up
[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
374     if (@_) {
375         &ScheduleThis($interval, "chanlimitCheck");
376         return if ($_[0] eq "2");
377     }
378
379     my $str = join(' ', &ChanConfList("chanlimitcheck") );
380
381     foreach $chan ( &ChanConfList("chanlimitcheck") ) {
382         next unless (&validChan($chan));
383
384         if ($chan eq "_default") {
385             &WARN("chanlimit: we're doing $chan!! HELP ME!");
386             next;
387         }
388
389         my $limitplus   = &getChanConfDefault("chanlimitcheckPlus", 5, $chan);
390         my $newlimit    = scalar(keys %{ $channels{$chan}{''} }) + $limitplus;
391         my $limit       = $channels{$chan}{'l'};
392
393         if (scalar keys %netsplitservers) {
394             if (defined $limit) {
395                 &status("chanlimit: netsplit; removing it for $chan.");
396                 $conn->mode($chan, "-l");
397                 $cache{chanlimitChange}{$chan} = time();
398                 &status("chanlimit: netsplit; removed.");
399             }
400
401             next;
402         }
403
404         if (defined $limit and scalar keys %{ $channels{$chan}{''} } > $limit) {
405             &FIXME("LIMIT: set too low!!!");
406             ### run NAMES again and flush it.
407         }
408
409         if (defined $limit and $limit == $newlimit) {
410             $cache{chanlimitChange}{$chan} = time();
411             next;
412         }
413
414         if (!exists $channels{$chan}{'o'}{$ident}) {
415             &status("chanlimit: dont have ops on $chan.") unless (exists $cache{warn}{chanlimit}{$chan});
416             $cache{warn}{chanlimit}{$chan} = 1;
417             &chanServCheck($chan);
418             next;
419         }
420         delete $cache{warn}{chanlimit}{$chan};
421
422         if (!defined $limit) {
423             &status("chanlimit: $chan: setting for first time or from netsplit.");
424         }
425
426         if (exists $cache{chanlimitChange}{$chan}) {
427             my $delta = time() - $cache{chanlimitChange}{$chan};
428             if ($delta < $interval*60) {
429                 &DEBUG("chanlimit: not going to change chanlimit! ($delta<$interval*60)");
430                 return;
431             }
432         }
433
434         $conn->mode($chan, "+l", $newlimit);
435         $cache{chanlimitChange}{$chan} = time();
436     }
437 }
438
439 sub netsplitCheck {
440     my ($s1,$s2);
441
442     if (@_) {
443         &ScheduleThis(15, "netsplitCheck");
444         return if ($_[0] eq "2");
445     }
446
447     $cache{'netsplitCache'}++;
448 #    &DEBUG("running netsplitCheck... $cache{netsplitCache}");
449
450     if (!scalar %netsplit and scalar %netsplitservers) {
451         &DEBUG("nsC: !hash netsplit but hash netsplitservers <- removing!");
452         undef %netsplitservers;
453         return;
454     }
455
456     # well... this shouldn't happen since %netsplit code does it anyway.
457     foreach $s1 (keys %netsplitservers) {
458
459         foreach $s2 (keys %{ $netsplitservers{$s1} }) {
460             my $delta = time() - $netsplitservers{$s1}{$s2};
461
462             if ($delta > 60*30) {
463                 &status("netsplit between $s1 and $s2 appears to be stale.");
464                 delete $netsplitservers{$s1}{$s2};
465                 &chanlimitCheck();
466             }
467         }
468
469         my $i = scalar(keys %{ $netsplitservers{$s1} });
470         delete $netsplitservers{$s1} unless ($i);
471     }
472
473     # %netsplit hash checker.
474     my $count   = scalar keys %netsplit;
475     my $delete  = 0;
476     foreach (keys %netsplit) {
477         if (&IsNickInAnyChan($_)) {     # why would this happen?
478 #           &DEBUG("nsC: $_ is in some chan; removing from netsplit list.");
479             delete $netsplit{$_};
480             $delete++;
481             next;
482         }
483
484         next unless (time() - $netsplit{$_} > 60*15);
485
486         $delete++;
487         delete $netsplit{$_};
488     }
489
490     # yet another hack.
491     foreach (keys %channels) {
492         my $i = $cache{maxpeeps}{$chan} || 0;
493         my $j = scalar(keys %{ $channels{$chan} });
494         next unless ($i > 10 and 0.25*$i > $j);
495
496         &DEBUG("netsplit: 0.25*max($i) > current($j); possible netsplit?");
497     }
498
499     if ($delete) {
500         my $j = scalar(keys %netsplit);
501         &status("nsC: removed from netsplit list: (before: $count; after: $j)");
502     }
503
504     if (!scalar %netsplit and scalar %netsplitservers) {
505         &DEBUG("nsC: ok hash netsplit is NULL; purging hash netsplitservers");
506         undef %netsplitservers;
507     }
508
509     if ($count and !scalar keys %netsplit) {
510         &DEBUG("nsC: netsplit is hopefully gone. reinstating chanlimit check.");
511         &chanlimitCheck();
512     }
513 }
514
515 sub floodLoop {
516     my $delete   = 0;
517     my $who;
518
519     if (@_) {
520         &ScheduleThis(60, "floodLoop"); # minutes.
521         return if ($_[0] eq "2");
522     }
523
524     my $time            = time();
525     my $interval        = &getChanConfDefault("floodCycle",60);
526
527     foreach $who (keys %flood) {
528         foreach (keys %{ $flood{$who} }) {
529             if (!exists $flood{$who}{$_}) {
530                 &WARN("flood{$who}{$_} undefined?");
531                 next;
532             }
533
534             if ($time - $flood{$who}{$_} > $interval) {
535                 delete $flood{$who}{$_};
536                 $delete++;
537             }
538         }
539     }
540     &VERB("floodLoop: deleted $delete items.",2);
541 }
542
543 sub seenFlush {
544     if (@_) {
545         my $interval = &getChanConfDefault("seenFlushInterval", 60);
546         &ScheduleThis($interval, "seenFlush");
547         return if ($_[0] eq "2");
548     }
549
550     my %stats;
551     my $nick;
552     my $flushed         = 0;
553     $stats{'count_old'} = &countKeys("seen") || 0;
554     $stats{'new'}       = 0;
555     $stats{'old'}       = 0;
556
557     if ($param{'DBType'} =~ /^(mysql|pgsql|sqlite)$/i) {
558         foreach $nick (keys %seencache) {
559             my $retval = &sqlReplace("seen", {
560                         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         &DEBUG("ircCheck for $_");
682         my @join = &getJoinChans(1);
683         if (scalar @join) {
684             &FIXME('ircCheck: found channels to join! ' . join(',',@join));
685             &joinNextChan();
686         }
687
688         # TODO: fix on_disconnect()
689
690         if (time() - $msgtime > 3600) {
691             # TODO: shouldn't we use cache{connect} somewhere?
692             if (exists $cache{connect}) {
693                 &WARN("ircCheck: no msg for 3600 and disco'd! reconnecting!");
694                 $msgtime = time();      # just in case.
695                 &ircloop();
696                 delete $cache{connect};
697             } else {
698                 &status('ircCheck: possible lost in space; checking.'.
699                     scalar(gmtime) );
700                 &msg($ident, "TEST");
701                 $cache{connect} = time();
702             }
703         }
704
705         if (grep /^\s*$/, keys %channels) {
706             &WARN('ircCheck: we have a NULL chan in hash channels? removing!');
707             if (!exists $channels{''}) {
708                 &DEBUG('ircCheck: this should never happen!');
709             }
710
711             delete $channels{''};
712         }
713     }
714
715     $cache{statusSafe} = 0;
716
717     ### USER FILE.
718     if ($utime_userfile > $wtime_userfile and time() - $wtime_userfile > 3600) {
719         &writeUserFile();
720         $wtime_userfile = time();
721     }
722     ### CHAN FILE.
723     if ($utime_chanfile > $wtime_chanfile and time() - $wtime_chanfile > 3600) {
724         &writeChanFile();
725         $wtime_chanfile = time();
726     }
727 }
728
729 sub miscCheck {
730     if (@_) {
731         &ScheduleThis(120, "miscCheck");
732         return if ($_[0] eq "2");       # defer.
733     }
734
735     # SHM check.
736     my @ipcs;
737     if ( -x "/usr/bin/ipcs") {
738         @ipcs = `/usr/bin/ipcs`;
739     } else {
740         &WARN("ircCheck: no 'ipcs' binary.");
741         return;
742     }
743
744     # make backup of important files.
745     &mkBackup( $bot_state_dir."/blootbot.chan", 60*60*24*3);
746     &mkBackup( $bot_state_dir."/blootbot.users", 60*60*24*3);
747     &mkBackup( $bot_base_dir."/blootbot-news.txt", 60*60*24*1);
748
749     # flush cache{lobotomy}
750     foreach (keys %{ $cache{lobotomy} }) {
751         next unless (time() - $cache{lobotomy}{$_} > 60*60);
752         delete $cache{lobotomy}{$_};
753     }
754
755     ### check modules if they've been modified. might be evil.
756     &reloadAllModules();
757
758     # shmid stale remove.
759     foreach (@ipcs) {
760         chop;
761
762         # key, shmid, owner, perms, bytes, nattch
763         next unless (/^(0x\d+) (\d+)\s+(\S+)\s+(\d+)\s+(\d+)\s+/);
764
765         my ($shmid, $size) = ($2,$5);
766         next unless ($shmid != $shm and $size == 2000);
767         my $z   = &shmRead($shmid);
768         if ($z =~ /^(\S+):(\d+):(\d+): /) {
769             my $n       = $1;
770             my $pid     = $2;
771             my $time    = $3;
772             next if (time() - $time < 60*60);
773             # FIXME remove not-pid shm if parent process dead
774             next if ($pid == $bot_pid);
775             # don't touch other bots, if they're running.
776             next unless ($param{ircUser} =~ /^\Q$n\E$/);
777         } else {
778             &DEBUG("shm: $shmid is not ours or old blootbot => ($z)");
779             next;
780         }
781
782         &status("SHM: nuking shmid $shmid");
783         CORE::system("/usr/bin/ipcrm shm $shmid >/dev/null");
784     }
785 }
786
787 sub miscCheck2 {
788     if (@_) {
789         &ScheduleThis(240, "miscCheck2");
790         return if ($_[0] eq "2");       # defer.
791     }
792
793     # debian check.
794     opendir(DEBIAN, "$bot_state_dir/debian");
795     foreach ( grep /gz$/, readdir(DEBIAN) ) {
796         my $exit = CORE::system("gzip -t $bot_state_dir/debian/$_");
797         next unless ($exit);
798
799         &status("debian: unlinking file => $_");
800         unlink "$bot_state_dir/debian/$_";
801     }
802     closedir DEBIAN;
803
804     # compress logs that should have been compressed.
805     # TODO: use strftime?
806     my ($day,$month,$year) = (gmtime(time()))[3,4,5];
807     my $date = sprintf("%04d%02d%02d",$year+1900,$month+1,$day);
808
809     if (!opendir(DIR,"$bot_log_dir")) {
810         &ERROR("misccheck2: log dir $bot_log_dir does not exist.");
811         closedir DIR;
812         return -1;
813     }
814
815     while (my $f = readdir(DIR)) {
816         next unless ( -f "$bot_log_dir/$f");
817         next if ($f =~ /gz|bz2/);
818         next unless ($f =~ /(\d{8})/);
819         next if ($date eq $1);
820
821         &compress("$bot_log_dir/$f");
822     }
823     closedir DIR;
824 }
825
826 ### this is semi-scheduled
827 sub getNickInUse {
828 # FIXME: broken for multiple connects
829 #    if ($ident eq $param{'ircNick'}) {
830 #       &status("okay, got my nick back.");
831 #       return;
832 #    }
833 #
834 #    if (@_) {
835 #       &ScheduleThis(30, "getNickInUse");
836 #       return if ($_[0] eq "2");       # defer.
837 #    }
838 #
839 #    &nick( $param{'ircNick'} );
840 }
841
842 sub uptimeLoop {
843     return if (!defined &uptimeWriteFile);
844 #    return unless &IsChanConf("uptime");
845
846     if (@_) {
847         &ScheduleThis(60, "uptimeLoop");
848         return if ($_[0] eq "2");       # defer.
849     }
850
851     &uptimeWriteFile();
852 }
853
854 sub slashdotLoop {
855
856     if (@_) {
857         &ScheduleThis(60, "slashdotLoop");
858         return if ($_[0] eq "2");
859     }
860
861     my @chans = &ChanConfList("slashdotAnnounce");
862     return unless (scalar @chans);
863
864     &Forker("slashdot", sub {
865         my $line = &Slashdot::slashdotAnnounce();
866         return unless (defined $line);
867
868         foreach (@chans) {
869             next unless (&::validChan($_));
870
871             &::status("sending slashdot update to $_.");
872             &notice($_, "Slashdot: $line");
873         }
874     } );
875 }
876
877 sub plugLoop {
878
879     if (@_) {
880         &ScheduleThis(60, "plugLoop");
881         return if ($_[0] eq "2");
882     }
883
884     my @chans = &ChanConfList("plugAnnounce");
885     return unless (scalar @chans);
886
887     &Forker("plug", sub {
888         my $line = &Plug::plugAnnounce();
889         return unless (defined $line);
890
891         foreach (@chans) {
892             next unless (&::validChan($_));
893
894             &::status("sending plug update to $_.");
895             &notice($_, "Plug: $line");
896         }
897     } );
898 }
899
900 sub kernelLoop {
901     if (@_) {
902         &ScheduleThis(240, "kernelLoop");
903         return if ($_[0] eq "2");
904     }
905
906     my @chans = &ChanConfList("kernelAnnounce");
907     return unless (scalar @chans);
908
909     &Forker("kernel", sub {
910         my @data = &Kernel::kernelAnnounce();
911
912         foreach (@chans) {
913             next unless (&::validChan($_));
914
915             &::status("sending kernel update to $_.");
916             my $c = $_;
917             foreach (@data) {
918                 &notice($c, "Kernel: $_");
919             }
920         }
921     } );
922 }
923
924 sub wingateCheck {
925     return unless &IsChanConf("wingate");
926
927     ### FILE CACHE OF OFFENDING WINGATES.
928     foreach (grep /^$host$/, @wingateBad) {
929         &status("Wingate: RUNNING ON $host BY $who");
930         &ban("*!*\@$host", "") if &IsChanConf("wingateBan");
931
932         my $reason      = &getChanConf("wingateKick");
933
934         next unless ($reason);
935         &kick($who, "", $reason)
936     }
937
938     ### RUN CACHE OF TRIED WINGATES.
939     if (grep /^$host$/, @wingateCache) {
940         push(@wingateNow, $host);       # per run.
941         push(@wingateCache, $host);     # cache per run.
942     } else {
943         &DEBUG("Already scanned $host. good.");
944     }
945
946     my $interval = &getChanConfDefault("wingateInterval", 60); # seconds.
947     return if (defined $forked{'wingate'});
948     return if (time() - $wingaterun <= $interval);
949     return unless (scalar(keys %wingateToDo));
950
951     $wingaterun = time();
952
953     &Forker("wingate", sub { &Wingate::Wingates(keys %wingateToDo); } );
954     undef @wingateNow;
955 }
956
957 ### TODO: ??
958 sub wingateWriteFile {
959     if (@_) {
960         &ScheduleThis(60, "wingateWriteFile");
961         return if ($_[0] eq "2");       # defer.
962     }
963
964     return unless (scalar @wingateCache);
965
966     my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
967     if ($bot_pid != $$) {
968         &DEBUG("wingateWriteFile: Reorganising!");
969
970         open(IN, $file);
971         while (<IN>) {
972             chop;
973             push(@wingateNow, $_);
974         }
975         close IN;
976
977         # very lame hack.
978         my %hash = map { $_ => 1 } @wingateNow;
979         @wingateNow = sort keys %hash;
980     }
981
982     &DEBUG("wingateWF: writing...");
983     open(OUT, ">$file");
984     foreach (@wingateNow) {
985         print OUT "$_\n";
986     }
987     close OUT;
988 }
989
990 sub factoidCheck {
991     if (@_) {
992         &ScheduleThis(720, "factoidCheck");
993         return if ($_[0] eq "2");       # defer.
994     }
995
996     my @list    = &searchTable("factoids", "factoid_key", "factoid_key", " #DEL#");
997     my $stale   = &getChanConfDefault("factoidDeleteDelay", 14) *60*60*24;
998     if ($stale < 1) {
999         # disable it since it's "illegal".
1000         return;
1001     }
1002
1003     my $time    = time();
1004
1005     foreach (@list) {
1006         my $age = &getFactInfo($_, "modified_time");
1007
1008         if (!defined $age or $age !~ /^\d+$/) {
1009             if (scalar @list > 50) {
1010                 if (!$cache{warnDel}) {
1011                     &WARN("list is over 50 (".scalar(@list)."... giving it a miss.");
1012                     $cache{warnDel} = 1;
1013                     last;
1014                 }
1015             }
1016
1017             &WARN("del factoid: old cruft (no time): $_");
1018             &delFactoid($_);
1019             next;
1020         }
1021
1022         next unless ($time - $age > $stale);
1023
1024         my $fix = $_;
1025         $fix =~ s/ #DEL#$//g;
1026         my $agestr = &Time2String($time - $age);
1027         &status("safedel: Removing '$_' for good. [$agestr old]");
1028
1029         &delFactoid($_);
1030     }
1031 }
1032
1033 sub dccStatus {
1034     return unless (scalar keys %{ $dcc{CHAT} });
1035
1036     if (@_) {
1037         &ScheduleThis(10, "dccStatus");
1038         return if ($_[0] eq "2");       # defer.
1039     }
1040
1041     my $time = strftime("%H:%M", gmtime(time()) );
1042
1043     my $c;
1044     foreach (keys %channels) {
1045         my $c           = $_;
1046         my $users       = keys %{ $channels{$c}{''} };
1047         my $chops       = keys %{ $channels{$c}{o}  };
1048         my $bans        = keys %{ $channels{$c}{b}  };
1049
1050         my $txt = "[$time] $c: $users members ($chops chops), $bans bans";
1051         foreach (keys %{ $dcc{'CHAT'} }) {
1052             next unless (exists $channels{$c}{''}{lc $_});
1053             $conn->privmsg($dcc{'CHAT'}{$_}, $txt);
1054         }
1055     }
1056 }
1057
1058 sub scheduleList {
1059     ###
1060     # custom:
1061     #   a - time == now.
1062     #   b - weird time.
1063     ###
1064
1065     my $reply = "sched:";
1066     foreach (keys %{ $irc->{_queue}}) {
1067         my $q = $_;
1068         my $coderef = $irc->{_queue}->{$q}->[1];
1069         my $sched;
1070         foreach (keys %sched) {
1071             my $schedname = $_;
1072             next unless defined(\&$schedname);
1073             next unless ($coderef eq \&$schedname);
1074             $sched = $schedname;
1075             last;
1076         }
1077
1078         my $time = $irc->{_queue}->{$q}->[0] - time();
1079
1080         if (defined $sched) {
1081             $reply = "$reply, $sched($q):" . &Time2String($time);
1082         } else {
1083             $reply = "$reply, NULL($q):" . &Time2String($time);
1084         }
1085     }
1086
1087     &DEBUG("$reply");
1088 }
1089
1090 sub mkBackup {
1091     my($file, $time)    = @_;
1092     my $backup          = 0;
1093
1094     if (! -f $file) {
1095         &VERB("mkB: file '$file' does not exist.",2);
1096         return;
1097     }
1098
1099     my $age     = "New";
1100     if ( -e "$file~" ) {
1101         $backup++       if ((stat $file)[9] - (stat "$file~")[9] > $time);
1102         my $delta       = time() - (stat "$file~")[9];
1103         $age            = &Time2String($delta);
1104     } else {
1105         $backup++;
1106     }
1107
1108     return unless ($backup);
1109
1110     ### TODO: do internal copying.
1111     &status("Backup: $file ($age)");
1112     CORE::system("/bin/cp $file $file~");
1113 }
1114
1115 1;