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