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