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