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