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