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