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