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