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