]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/Schedulers.pl
* Undo "less verbose" patch from r1153 to properly display Chans: in console logs
[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     # FIXED: $ch should be used rather than $chan since it creates NULL channels in the hash
493     foreach my $ch (keys %channels) {
494         my $i = $cache{maxpeeps}{$ch} || 0;
495         my $j = scalar(keys %{ $channels{$ch} });
496         next unless ($i > 10 and 0.25*$i > $j);
497
498         &DEBUG("netsplit: 0.25*max($i) > current($j); possible netsplit?");
499     }
500
501     if ($delete) {
502         my $j = scalar(keys %netsplit);
503         &status("nsC: removed from netsplit list: (before: $count; after: $j)");
504     }
505
506     if (!scalar %netsplit and scalar %netsplitservers) {
507         &DEBUG("nsC: ok hash netsplit is NULL; purging hash netsplitservers");
508         undef %netsplitservers;
509     }
510
511     if ($count and !scalar keys %netsplit) {
512         &DEBUG("nsC: netsplit is hopefully gone. reinstating chanlimit check.");
513         &chanlimitCheck();
514     }
515 }
516
517 sub floodLoop {
518     my $delete   = 0;
519     my $who;
520
521     if (@_) {
522         &ScheduleThis(60, 'floodLoop'); # minutes.
523         return if ($_[0] eq '2');
524     }
525
526     my $time            = time();
527     my $interval        = &getChanConfDefault('floodCycle',60, $chan);
528
529     foreach $who (keys %flood) {
530         foreach (keys %{ $flood{$who} }) {
531             if (!exists $flood{$who}{$_}) {
532                 &WARN("flood{$who}{$_} undefined?");
533                 next;
534             }
535
536             if ($time - $flood{$who}{$_} > $interval) {
537                 delete $flood{$who}{$_};
538                 $delete++;
539             }
540         }
541     }
542     &VERB("floodLoop: deleted $delete items.",2);
543 }
544
545 sub seenFlush {
546     if (@_) {
547         my $interval = &getChanConfDefault('seenFlushInterval', 60, $chan);
548         &ScheduleThis($interval, 'seenFlush');
549         return if ($_[0] eq '2');
550     }
551
552     my %stats;
553     my $nick;
554     my $flushed = 0;
555     $stats{'count_old'} = &countKeys('seen') || 0;
556     $stats{'new'}       = 0;
557     $stats{'old'}       = 0;
558
559     if ($param{'DBType'} =~ /^(mysql|pgsql|sqlite(2)?)$/i) {
560         foreach $nick (keys %seencache) {
561             my $retval = &sqlSet('seen', {'nick' => lc $seencache{$nick}{'nick'}}, {
562                         time    => $seencache{$nick}{'time'},
563                         host    => $seencache{$nick}{'host'},
564                         channel => $seencache{$nick}{'chan'},
565                         message => $seencache{$nick}{'msg'},
566             } );
567
568             delete $seencache{$nick};
569             $flushed++;
570         }
571     } else {
572         &DEBUG("seenFlush: NO VALID FACTOID SUPPORT?");
573     }
574
575     &status("Seen: Flushed $flushed entries.")  if ($flushed);
576     &VERB(sprintf("  new seen: %03.01f%% (%d/%d)",
577         $stats{'new'}*100/($stats{'count_old'} || 1),
578         $stats{'new'}, ( $stats{'count_old'} || 1) ), 2) if ($stats{'new'});
579     &VERB(sprintf("  now seen: %3.1f%% (%d/%d)",
580         $stats{'old'}*100 / ( &countKeys('seen') || 1),
581         $stats{'old'}, &countKeys('seen') ), 2)         if ($stats{'old'});
582
583     &WARN("scalar keys seenflush != 0!")        if (scalar keys %seenflush);
584 }
585
586 sub leakCheck {
587     my ($blah1,$blah2);
588     my $count = 0;
589
590     if (@_) {
591         &ScheduleThis(240, 'leakCheck');
592         return if ($_[0] eq '2');
593     }
594
595     # flood. this is dealt with in floodLoop()
596     foreach $blah1 (keys %flood) {
597         foreach $blah2 (keys %{ $flood{$blah1} }) {
598             $count += scalar(keys %{ $flood{$blah1}{$blah2} });
599         }
600     }
601     &VERB("leak: hash flood has $count total keys.",2);
602
603     # floodjoin.
604     $count = 0;
605     foreach $blah1 (keys %floodjoin) {
606         foreach $blah2 (keys %{ $floodjoin{$blah1} }) {
607             $count += scalar(keys %{ $floodjoin{$blah1}{$blah2} });
608         }
609     }
610     &VERB("leak: hash floodjoin has $count total keys.",2);
611
612     # floodwarn.
613     $count = scalar(keys %floodwarn);
614     &VERB("leak: hash floodwarn has $count total keys.",2);
615
616     my $chan;
617     foreach $chan (grep /[A-Z]/, keys %channels) {
618         &DEBUG("leak: chan => '$chan'.");
619         my ($i,$j);
620         foreach $i (keys %{ $channels{$chan} }) {
621             foreach (keys %{ $channels{$chan}{$i} }) {
622                 &DEBUG("leak:   \$channels{$chan}{$i}{$_} ...");
623             }
624         }
625     }
626
627     # chanstats
628     $count = scalar(keys %chanstats);
629     &VERB("leak: hash chanstats has $count total keys.",2);
630
631     # nuh.
632     my $delete  = 0;
633     foreach (keys %nuh) {
634         next if (&IsNickInAnyChan($_));
635         next if (exists $dcc{CHAT}{$_});
636
637         delete $nuh{$_};
638         $delete++;
639     }
640
641     &status("leak: $delete nuh{} items deleted; now have ".
642                                 scalar(keys %nuh) ) if ($delete);
643 }
644
645 sub ignoreCheck {
646     if (@_) {
647         &ScheduleThis(60, 'ignoreCheck');
648         return if ($_[0] eq '2');       # defer.
649     }
650
651     my $time    = time();
652     my $count   = 0;
653
654     foreach (keys %ignore) {
655         my $chan = $_;
656
657         foreach (keys %{ $ignore{$chan} }) {
658             my @array = @{ $ignore{$chan}{$_} };
659
660             next unless ($array[0] and $time > $array[0]);
661
662             delete $ignore{$chan}{$_};
663             &status("ignore: $_/$chan has expired.");
664             $count++;
665         }
666     }
667
668     $cache{ignoreCheckTime} = time();
669
670     &VERB("ignore: $count items deleted.",2);
671 }
672
673 sub ircCheck {
674     if (@_) {
675         &ScheduleThis(15, 'ircCheck');
676         return if ($_[0] eq '2');       # defer.
677     }
678
679     $cache{statusSafe} = 1;
680     foreach (sort keys %conns) {
681         $conn=$conns{$_};
682         my $mynick=$conn->nick();
683         &DEBUG("ircCheck for $_");
684         my @join = &getJoinChans(900); # Display with min of 900sec delay between redisplay
685         if (scalar @join) {
686             &FIXME('ircCheck: found channels to join! ' . join(',',@join));
687             &joinNextChan();
688         }
689
690         # TODO: fix on_disconnect()
691
692         if (time() - $msgtime > 3600) {
693             # TODO: shouldn't we use cache{connect} somewhere?
694             if (exists $cache{connect}) {
695                 &WARN("ircCheck: no msg for 3600 and disco'd! reconnecting!");
696                 $msgtime = time();      # just in case.
697                 &ircloop();
698                 delete $cache{connect};
699             } else {
700                 &status('ircCheck: possible lost in space; checking.'.
701                     scalar(gmtime) );
702                 &msg($mynick, 'TEST');
703                 $cache{connect} = time();
704             }
705         }
706     }
707
708         if (grep /^\s*$/, keys %channels) {
709             &WARN('ircCheck: we have a NULL chan in hash channels? removing!');
710             if (!exists $channels{''}) {
711                 &DEBUG('ircCheck: this should never happen!');
712             }
713        }
714      if ($ident !~ /^\Q$param{ircNick}\E$/) {
715        # this does not work unfortunately.
716        &WARN("ircCheck: ident($ident) != param{ircNick}($param{ircNick}).");
717
718        # this check is misleading... perhaps we should do a notify.
719        if (! &IsNickInAnyChan( $param{ircNick} ) ) {
720            &DEBUG("$param{ircNick} not in use... changing!");
721            &nick( $param{ircNick} );
722        } else {
723            &WARN("$param{ircNick} is still in use...");
724         }
725     }
726
727     $cache{statusSafe} = 0;
728
729     ### USER FILE.
730     if ($utime_userfile > $wtime_userfile and time() - $wtime_userfile > 3600) {
731         &writeUserFile();
732         $wtime_userfile = time();
733     }
734     ### CHAN FILE.
735     if ($utime_chanfile > $wtime_chanfile and time() - $wtime_chanfile > 3600) {
736         &writeChanFile();
737         $wtime_chanfile = time();
738     }
739 }
740
741 sub miscCheck {
742     if (@_) {
743         &ScheduleThis(120, 'miscCheck');
744         return if ($_[0] eq '2');       # defer.
745     }
746
747     # SHM check.
748     my @ipcs;
749     if ( -x "/usr/bin/ipcs") {
750         @ipcs = `/usr/bin/ipcs`;
751     } else {
752         &WARN("ircCheck: no 'ipcs' binary.");
753         return;
754     }
755
756     # make backup of important files.
757     &mkBackup( $bot_state_dir."/infobot.chan", 60*60*24*3);
758     &mkBackup( $bot_state_dir."/infobot.users", 60*60*24*3);
759     &mkBackup( $bot_base_dir."/infobot-news.txt", 60*60*24*1);
760
761     # flush cache{lobotomy}
762     foreach (keys %{ $cache{lobotomy} }) {
763         next unless (time() - $cache{lobotomy}{$_} > 60*60);
764         delete $cache{lobotomy}{$_};
765     }
766
767     ### check modules if they've been modified. might be evil.
768     &reloadAllModules();
769
770     # shmid stale remove.
771     foreach (@ipcs) {
772         chop;
773
774         # key, shmid, owner, perms, bytes, nattch
775         next unless (/^(0x\d+) (\d+)\s+(\S+)\s+(\d+)\s+(\d+)\s+/);
776
777         my ($shmid, $size) = ($2,$5);
778         next unless ($shmid != $shm and $size == 2000);
779         my $z   = &shmRead($shmid);
780         if ($z =~ /^(\S+):(\d+):(\d+): /) {
781             my $n       = $1;
782             my $pid     = $2;
783             my $time    = $3;
784             next if (time() - $time < 60*60);
785             # FIXME remove not-pid shm if parent process dead
786             next if ($pid == $bot_pid);
787             # don't touch other bots, if they're running.
788             next unless ($param{ircUser} =~ /^\Q$n\E$/);
789         } else {
790             &DEBUG("shm: $shmid is not ours or old infobot => ($z)");
791             next;
792         }
793
794         &status("SHM: nuking shmid $shmid");
795         CORE::system("/usr/bin/ipcrm shm $shmid >/dev/null");
796     }
797 }
798
799 sub miscCheck2 {
800     if (@_) {
801         &ScheduleThis(240, 'miscCheck2');
802         return if ($_[0] eq '2');       # defer.
803     }
804
805     # debian check.
806     opendir(DEBIAN, "$bot_state_dir/debian");
807     foreach ( grep /gz$/, readdir(DEBIAN) ) {
808         my $exit = CORE::system("gzip -t $bot_state_dir/debian/$_");
809         next unless ($exit);
810
811         &status("debian: unlinking file => $_");
812         unlink "$bot_state_dir/debian/$_";
813     }
814     closedir DEBIAN;
815
816     # compress logs that should have been compressed.
817     # TODO: use strftime?
818     my ($day,$month,$year) = (gmtime(time()))[3,4,5];
819     my $date = sprintf("%04d%02d%02d",$year+1900,$month+1,$day);
820
821     if (!opendir(DIR,"$bot_log_dir")) {
822         &ERROR("misccheck2: log dir $bot_log_dir does not exist.");
823         closedir DIR;
824         return -1;
825     }
826
827     while (my $f = readdir(DIR)) {
828         next unless ( -f "$bot_log_dir/$f");
829         next if ($f =~ /gz|bz2/);
830         next unless ($f =~ /(\d{8})/);
831         next if ($date eq $1);
832
833         &compress("$bot_log_dir/$f");
834     }
835     closedir DIR;
836 }
837
838 ### this is semi-scheduled
839 sub getNickInUse {
840 # FIXME: broken for multiple connects
841 #    if ($ident eq $param{'ircNick'}) {
842 #       &status("okay, got my nick back.");
843 #       return;
844 #    }
845 #
846 #    if (@_) {
847 #       &ScheduleThis(30, 'getNickInUse');
848 #       return if ($_[0] eq '2');       # defer.
849 #    }
850 #
851 #    &nick( $param{'ircNick'} );
852 }
853
854 sub uptimeLoop {
855     return if (!defined &uptimeWriteFile);
856 #    return unless &IsParam('Uptime');
857
858     if (@_) {
859         &ScheduleThis(60, 'uptimeLoop');
860         return if ($_[0] eq '2');       # defer.
861     }
862
863     &uptimeWriteFile();
864 }
865
866 sub slashdotLoop {
867
868     if (@_) {
869         &ScheduleThis(60, 'slashdotLoop');
870         return if ($_[0] eq '2');
871     }
872
873     my @chans = &ChanConfList('slashdotAnnounce');
874     return unless (scalar @chans);
875
876     &Forker('slashdot', sub {
877         my $line = &Slashdot::slashdotAnnounce();
878         return unless (defined $line);
879
880         foreach (@chans) {
881             next unless (&::validChan($_));
882
883             &::status("sending slashdot update to $_.");
884             &notice($_, "Slashdot: $line");
885         }
886     } );
887 }
888
889 sub plugLoop {
890
891     if (@_) {
892         &ScheduleThis(60, 'plugLoop');
893         return if ($_[0] eq '2');
894     }
895
896     my @chans = &ChanConfList('plugAnnounce');
897     return unless (scalar @chans);
898
899     &Forker('Plug', sub {
900         my $line = &Plug::plugAnnounce();
901         return unless (defined $line);
902
903         foreach (@chans) {
904             next unless (&::validChan($_));
905
906             &::status("sending plug update to $_.");
907             &notice($_, "Plug: $line");
908         }
909     } );
910 }
911
912 sub kernelLoop {
913     if (@_) {
914         &ScheduleThis(240, 'kernelLoop');
915         return if ($_[0] eq '2');
916     }
917
918     my @chans = &ChanConfList('kernelAnnounce');
919     return unless (scalar @chans);
920
921     &Forker('Kernel', sub {
922         my @data = &Kernel::kernelAnnounce();
923
924         foreach (@chans) {
925             next unless (&::validChan($_));
926
927             &::status("sending kernel update to $_.");
928             my $c = $_;
929             foreach (@data) {
930                 &notice($c, "Kernel: $_");
931             }
932         }
933     } );
934 }
935
936 sub wingateCheck {
937     return unless &IsChanConf('Wingate') > 0;
938
939     ### FILE CACHE OF OFFENDING WINGATES.
940     foreach (grep /^$host$/, @wingateBad) {
941         &status("Wingate: RUNNING ON $host BY $who");
942         &ban("*!*\@$host", '') if &IsChanConf('wingateBan') > 0;
943
944         my $reason      = &getChanConf('wingateKick');
945
946         next unless ($reason);
947         &kick($who, '', $reason)
948     }
949
950     ### RUN CACHE OF TRIED WINGATES.
951     if (grep /^$host$/, @wingateCache) {
952         push(@wingateNow, $host);       # per run.
953         push(@wingateCache, $host);     # cache per run.
954     } else {
955         &DEBUG("Already scanned $host. good.");
956     }
957
958     my $interval = &getChanConfDefault('wingateInterval', 60, $chan); # seconds.
959     return if (defined $forked{'Wingate'});
960     return if (time() - $wingaterun <= $interval);
961     return unless (scalar(keys %wingateToDo));
962
963     $wingaterun = time();
964
965     &Forker('Wingate', sub { &Wingate::Wingates(keys %wingateToDo); } );
966     undef @wingateNow;
967 }
968
969 ### TODO: ??
970 sub wingateWriteFile {
971     if (@_) {
972         &ScheduleThis(60, 'wingateWriteFile');
973         return if ($_[0] eq '2');       # defer.
974     }
975
976     return unless (scalar @wingateCache);
977
978     my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
979     if ($bot_pid != $$) {
980         &DEBUG('wingateWriteFile: Reorganising!');
981
982         open(IN, $file);
983         while (<IN>) {
984             chop;
985             push(@wingateNow, $_);
986         }
987         close IN;
988
989         # very lame hack.
990         my %hash = map { $_ => 1 } @wingateNow;
991         @wingateNow = sort keys %hash;
992     }
993
994     &DEBUG('wingateWF: writing...');
995     open(OUT, ">$file");
996     foreach (@wingateNow) {
997         print OUT "$_\n";
998     }
999     close OUT;
1000 }
1001
1002 sub factoidCheck {
1003     if (@_) {
1004         &ScheduleThis(720, 'factoidCheck');
1005         return if ($_[0] eq '2');       # defer.
1006     }
1007
1008     my @list    = &searchTable('factoids', 'factoid_key', 'factoid_key', " #DEL#");
1009     my $stale   = &getChanConfDefault('factoidDeleteDelay', 14, $chan) *60*60*24;
1010     if ($stale < 1) {
1011         # disable it since it's 'illegal'.
1012         return;
1013     }
1014
1015     my $time    = time();
1016
1017     foreach (@list) {
1018         my $age = &getFactInfo($_, 'modified_time');
1019
1020         if (!defined $age or $age !~ /^\d+$/) {
1021             if (scalar @list > 50) {
1022                 if (!$cache{warnDel}) {
1023                     &WARN("list is over 50 (".scalar(@list)."... giving it a miss.");
1024                     $cache{warnDel} = 1;
1025                     last;
1026                 }
1027             }
1028
1029             &WARN("del factoid: old cruft (no time): $_");
1030             &delFactoid($_);
1031             next;
1032         }
1033
1034         next unless ($time - $age > $stale);
1035
1036         my $fix = $_;
1037         $fix =~ s/ #DEL#$//g;
1038         my $agestr = &Time2String($time - $age);
1039         &status("safedel: Removing '$_' for good. [$agestr old]");
1040
1041         &delFactoid($_);
1042     }
1043 }
1044
1045 sub dccStatus {
1046     return unless (scalar keys %{ $dcc{CHAT} });
1047
1048     if (@_) {
1049         &ScheduleThis(10, 'dccStatus');
1050         return if ($_[0] eq '2');       # defer.
1051     }
1052
1053     my $time = strftime("%H:%M", gmtime(time()) );
1054
1055     my $c;
1056     foreach (keys %channels) {
1057         my $c           = $_;
1058         my $users       = keys %{ $channels{$c}{''} };
1059         my $chops       = keys %{ $channels{$c}{o}  };
1060         my $bans        = keys %{ $channels{$c}{b}  };
1061
1062         my $txt = "[$time] $c: $users members ($chops chops), $bans bans";
1063         foreach (keys %{ $dcc{'CHAT'} }) {
1064             next unless (exists $channels{$c}{''}{lc $_});
1065             $conn->privmsg($dcc{'CHAT'}{$_}, $txt);
1066         }
1067     }
1068 }
1069
1070 sub scheduleList {
1071     ###
1072     # custom:
1073     #   a - time == now.
1074     #   b - weird time.
1075     ###
1076
1077     my $reply = "sched:";
1078     foreach (keys %{ $irc->{_queue}}) {
1079         my $q = $_;
1080         my $coderef = $irc->{_queue}->{$q}->[1];
1081         my $sched;
1082         foreach (keys %sched) {
1083             my $schedname = $_;
1084             next unless defined(\&$schedname);
1085             next unless ($coderef eq \&$schedname);
1086             $sched = $schedname;
1087             last;
1088         }
1089
1090         my $time = $irc->{_queue}->{$q}->[0] - time();
1091
1092         if (defined $sched) {
1093             $reply = "$reply, $sched($q):" . &Time2String($time);
1094         } else {
1095             $reply = "$reply, NULL($q):" . &Time2String($time);
1096         }
1097     }
1098
1099     &DEBUG("$reply");
1100 }
1101
1102 sub mkBackup {
1103     my($file, $time)    = @_;
1104     my $backup          = 0;
1105
1106     if (! -f $file) {
1107         &VERB("mkB: file '$file' does not exist.",2);
1108         return;
1109     }
1110
1111     my $age     = 'New';
1112     if ( -e "$file~" ) {
1113         $backup++       if ((stat $file)[9] - (stat "$file~")[9] > $time);
1114         my $delta       = time() - (stat "$file~")[9];
1115         $age            = &Time2String($delta);
1116     } else {
1117         $backup++;
1118     }
1119
1120     return unless ($backup);
1121
1122     ### TODO: do internal copying.
1123     &status("Backup: $file ($age)");
1124     CORE::system("/bin/cp $file $file~");
1125 }
1126
1127 1;