]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/Schedulers.pl
chanlimitcheck: removed netsplit check
[infobot.git] / src / IRC / Schedulers.pl
1 #
2 # ProcessExtra.pl: Extensions to Process.pl
3 #          Author: dms
4 #         Version: v0.4b (20000923)
5 #         Created: 20000117
6 #
7
8 if (&IsParam("useStrict")) { use strict; }
9
10 sub setupSchedulers {
11     &VERB("Starting schedulers...",2);
12
13     # ONCE OFF.
14
15     # REPETITIVE.
16     &uptimeCycle(1)     if (&IsParam("uptime"));
17     &randomQuote(1)     if (&IsParam("randomQuote"));
18     &randomFactoid(1)   if (&IsParam("randomFactoid"));
19     &logCycle(1)        if (defined fileno LOG and &IsParam("logfile") and &IsParam("maxLogSize"));
20     &chanlimitCheck(1)  if (&IsParam("chanlimitcheck"));
21     &netsplitCheck(1);  # mandatory
22     &floodCycle(1);     # mandatory
23     &seenFlush(1)       if (&IsParam("seen") and &IsParam("seenFlushInterval"));
24     &leakCheck(1);      # mandatory
25     &ignoreListCheck(1);# mandatory
26     &seenFlushOld(1)    if (&IsParam("seen"));
27     &ircCheck(1);       # mandatory
28     &miscCheck(1);      # mandatory
29     &shmFlush(1);       # mandatory
30     &slashdotCycle(1)   if (&IsParam("slashdot") and &IsParam("slashdotAnnounce"));
31     &freshmeatCycle(1)  if (&IsParam("freshmeat") and &IsParam("freshmeatAnnounce"));
32     &kernelCycle(1)     if (&IsParam("kernel") and &IsParam("kernelAnnounce"));
33     &wingateWriteFile(1) if (&IsParam("wingate"));
34     &factoidCheck(1)    if (&IsParam("factoidDeleteDelay"));
35 }
36
37 sub ScheduleThis {
38     my ($interval, $codename, @args) = @_;
39     my $waittime = &getRandomInt($interval);
40
41     &VERB("Scheduling \&$codename() for ".&Time2String($waittime),3);
42     $conn->schedule($waittime, \&$codename, @args);
43 }
44
45 sub randomQuote {
46     my $line = &getRandomLineFromFile($bot_misc_dir. "/blootbot.randtext");
47     if (!defined $line) {
48         &ERROR("random Quote: weird error?");
49         return;
50     }
51
52     my @channels = split(/[\s\t]+/, lc $param{'randomQuoteChannels'});
53     @channels    = keys(%channels) unless (scalar @channels);
54
55     my $good = 0;
56     foreach (@channels) {
57         next unless (&validChan($_));
58
59         &status("sending random Quote to $_.");
60         &action($_, "Ponders: ".$line);
61         $good++;
62     }
63
64     if (!$good and scalar @channels) {
65         &WARN("randomQuote: no valid channels?");
66     }
67
68     my $interval = $param{'randomQuoteInterval'} || 60;
69     &ScheduleThis($interval, "randomQuote") if (@_);
70 }
71
72 sub randomFactoid {
73     my ($key,$val);
74     my $error = 0;
75     while (1) {
76         ($key,$val) = &randKey("factoids","factoid_key,factoid_value");
77 ###     $val =~ tr/^[A-Z]/[a-z]/;       # blah is Good => blah is good.
78         last if ($val !~ /^</);
79         $error++;
80         if ($error == 5) {
81             &ERROR("rF: tried 5 times but failed.");
82             return;
83         }
84     }
85
86     my @channels = split(/[\s\t]+/, lc $param{'randomFactoidChannels'});
87     @channels    = keys(%channels) unless (scalar @channels);
88
89     my $good = 0;
90     foreach (@channels) {
91         next unless (&validChan($_));
92
93         &status("sending random Factoid to $_.");
94 ###     &msg($_, "$key is $val");
95         &action($_, "Thinks: \037$key\037 is $val");
96         ### FIXME: Use &getReply() on above to format factoid properly?
97         $good++;
98     }
99
100     if (!$good and scalar @channels) {
101         &WARN("randomFactoid: no valid channels?");
102     }
103
104     my $interval = $param{'randomFactoidInterval'} || 60;
105     &ScheduleThis($interval, "randomFactoid") if (@_);
106 }
107
108 sub logCycle {
109
110     ### check if current size is too large.
111     if ( -s $file{log} > $param{'maxLogSize'}) {
112         my $date = sprintf("%04d%02d%02d", (localtime)[5,4,3]);
113         $file{log} = $param{'logfile'} ."-". $date;
114         &status("cycling log file.");
115
116         if ( -e $file{log}) {
117             my $i = 1;
118             my $newlog;
119             while () {
120                 $newlog = $file{log}."-".$i;
121                 last if (! -e $newlog);
122                 $i++;
123             }
124             $file{log} = $newlog;
125         }
126
127         &closeLog();
128         system("/bin/mv '$param{'logfile'}' '$file{log}'");
129         &compress($file{log});
130         &openLog();
131         &status("cycling log file.");
132     }
133
134     ### check if all the logs exceed size.
135     my $logdir = "$bot_base_dir/log/";
136     if (opendir(LOGS, $logdir)) {
137         my $tsize = 0;
138         my (%age, %size);
139
140         while (defined($_ = readdir LOGS)) {
141             my $logfile         = "$logdir/$_";
142
143             next unless ( -f $logfile);
144             my $size            = -s $logfile;
145             my $age             = (stat $logfile)[9];
146
147             $age{$age}          = $logfile;
148             $size{$logfile}     = $size;
149
150             $tsize              += $size;
151         }
152         closedir LOGS;
153
154         my $delete      = 0;
155         while ($tsize > $param{'maxLogSize'}) {
156             &status("LOG: current size > max ($tsize > $param{'maxLogSize'})");
157             my $oldest  = (sort {$a <=> $b} keys %age)[0];
158             &status("LOG: unlinking $age{$oldest}.");
159             unlink $age{$oldest};
160             $tsize      -= $oldest;
161             $delete++;
162         }
163
164         ### TODO: add how many b,kb,mb removed?
165         &status("LOG: removed $delete logs.") if ($delete);
166     } else {
167         &WARN("could not open dir $logdir");
168     }
169
170     &ScheduleThis(60, "logCycle") if (@_);
171 }
172
173 sub seenFlushOld {
174     my $max_time = $param{'seenMaxDays'}*60*60*24;
175     my $delete   = 0;
176
177     if ($param{'DBType'} =~ /^pg|postgres|mysql/i) {
178         my $query = "SELECT nick,time FROM seen GROUP BY nick HAVING UNIX_TIMESTAMP() - time > $max_time";
179         my $sth = $dbh->prepare($query);
180         $sth->execute;
181
182         while (my @row = $sth->fetchrow_array) {
183             my ($nick,$time) = @row;
184
185             &dbDel("seen","nick",$nick);
186             $delete++;
187         }
188         $sth->finish;
189     } elsif ($param{'DBType'} =~ /^dbm/i) {
190         my $time = time();
191
192         foreach (keys %seen) {
193             my $delta_time = $time - &dbGet("seen", "NULL", $_, "time");
194             next unless ($delta_time > $max_time);
195
196             &DEBUG("seenFlushOld: ".&Time2String($delta_time) );
197             delete $seen{$_};
198             $delete++;
199         }
200     } else {
201         &FIXME("seenFlushOld: for PG/NO-DB.");
202     }
203     &VERB("SEEN deleted $delete seen entries.",2);
204
205     &ScheduleThis(1440, "seenFlushOld") if (@_);
206 }
207
208 sub chanlimitCheck {
209     my $limitplus = $param{'chanlimitcheckPlus'} || 5;
210     my @channels = split(/[\s\t]+/, lc $param{'chanlimitcheck'});
211
212     foreach (@channels) {
213         next unless (&validChan($_));
214
215         my $newlimit    = scalar(keys %{$channels{$_}{''}}) + $limitplus;
216         my $limit       = $channels{$_}{'l'};
217
218         if (scalar keys %{$channels{$_}{''}} > $limit) {
219             &status("LIMIT: set too low!!! FIXME");
220         }
221
222         next unless (!defined $limit or $limit != $newlimit);
223
224         if (!exists $channels{$_}{'o'}{$ident}) {
225             &ERROR("chanlimitcheck: dont have ops on $_.");
226             next;
227         }
228         &rawout("MODE $_ +l $newlimit");
229     }
230
231     my $interval = $param{'chanlimitcheckInterval'} || 10;
232     &ScheduleThis($interval, "chanlimitCheck") if (@_);
233 }
234
235 sub netsplitCheck {
236     my ($s1,$s2);
237
238     foreach $s1 (keys %netsplitservers) {
239         foreach $s2 (keys %{$netsplitservers{$s1}}) {
240             if (time() - $netsplitservers{$s1}{$s2} > 3600) {
241                 &status("netsplit between $s1 and $s2 appears to be stale.");
242                 delete $netsplitservers{$s1}{$s2};
243             }
244         }
245     }
246
247     # %netsplit hash checker.
248     foreach (keys %netsplit) {
249         if (&IsNickInAnyChan($_)) {
250             &DEBUG("netsplitC: $_ is in some chan; removing from netsplit list.");
251             delete $netsplit{$_};
252         }
253         next unless (time() - $netsplit{$_} > 60*60*2); # 2 hours.
254         next if (&IsNickInAnyChan($_));
255
256         &DEBUG("netsplitC: $_ didn't come back from netsplit in 2 hours; removing from netsplit list.");
257         delete $netsplit{$_};
258     }
259
260     &ScheduleThis(30, "netsplitCheck") if (@_);
261 }
262
263 sub floodCycle {
264     my $interval = $param{'floodInterval'} || 60;       # seconds.
265     my $delete   = 0;
266
267     my $who;
268     foreach $who (keys %flood) {
269         foreach (keys %{$flood{$who}}) {
270             if (time() - $flood{$who}{$_} > $interval) {
271                 delete $flood{$who}{$_};
272                 $delete++;
273             }
274         }
275     }
276     &VERB("floodCycle: deleted $delete items.",2);
277
278     &ScheduleThis($interval, "floodCycle") if (@_);     # minutes.
279 }
280
281 sub seenFlush {
282     my %stats;
283     my $nick;
284     my $flushed         = 0;
285     $stats{'count_old'} = &countKeys("seen");
286     $stats{'new'}       = 0;
287     $stats{'old'}       = 0;
288
289     if ($param{'DBType'} =~ /^mysql|pg|postgres/i) {
290         foreach $nick (keys %seencache) {
291             my $exists = &dbGet("seen","nick", $nick, "nick");
292
293             if (defined $exists and $exists) {
294                 &dbUpdate("seen", "nick", $nick, (
295                         "time" => $seencache{$nick}{'time'},
296                         "host" => $seencache{$nick}{'host'},
297                         "channel" => $seencache{$nick}{'chan'},
298                         "message" => $seencache{$nick}{'msg'},
299                 ) );
300                 $stats{'old'}++;
301             } else {
302                 my $retval = &dbInsert("seen", $nick, (
303                         "nick" => $seencache{$nick}{'nick'},
304                         "time" => $seencache{$nick}{'time'},
305                         "host" => $seencache{$nick}{'host'},
306                         "channel" => $seencache{$nick}{'chan'},
307                         "message" => $seencache{$nick}{'msg'},
308                 ) );
309                 $stats{'new'}++;
310
311                 ### TODO: put bad nick into a list and don't do it again!
312                 &FIXME("Should never happen! (nick => $nick)") if !$retval;
313             }
314
315             delete $seencache{$nick};
316             $flushed++;
317         }
318
319     } elsif ($param{'DBType'} =~ /^dbm/i) {
320
321         foreach $nick (keys %seencache) {
322             my $retval = &dbInsert("seen", $nick, (
323                 "nick" => $seencache{$nick}{'nick'},
324                 "time" => $seencache{$nick}{'time'},
325                 "host" => $seencache{$nick}{'host'},
326                 "channel" => $seencache{$nick}{'chan'},
327                 "message" => $seencache{$nick}{'msg'},
328             ) );
329
330             ### TODO: put bad nick into a list and don't do it again!
331             &FIXME("Should never happen! (nick => $nick)") if !$retval;
332
333             delete $seencache{$nick};
334             $flushed++;
335         }
336     } else {
337         &DEBUG("seenFlush: NO VALID FACTOID SUPPORT?");
338     }
339
340     &status("Flushed $flushed seen entries.")           if ($flushed);
341     &VERB(sprintf("  new seen: %03.01f%% (%d/%d)",
342         $stats{'new'}*100/$stats{'count_old'},
343         $stats{'new'}, $stats{'count_old'} ), 2)        if ($stats{'new'});
344     &VERB(sprintf("  now seen: %3.1f%% (%d/%d)",
345         $stats{'old'}*100/&countKeys("seen"),
346         $stats{'old'}, &countKeys("seen") ), 2)         if ($stats{'old'});
347
348     &WARN("scalar keys seenflush != 0!")        if (scalar keys %seenflush);
349
350     my $interval = $param{'seenFlushInterval'} || 60;
351     &ScheduleThis($interval, "seenFlush") if (@_);
352 }
353
354 sub leakCheck {
355     my ($blah1,$blah2);
356     my $count = 0;
357
358     # flood.
359     foreach $blah1 (keys %flood) {
360         foreach $blah2 (keys %{$flood{$blah1}}) {
361             $count += scalar(keys %{$flood{$blah1}{$blah2}});
362         }
363     }
364     &VERB("\%flood has $count total keys.",2);
365
366     my $chan;
367     foreach $chan (grep /[A-Z]/, keys %channels) {
368         &DEBUG("leak: chan => '$chan'.");
369         my ($i,$j);
370         foreach $i (keys %{$channels{$chan}}) {
371             foreach (keys %{$channels{$chan}{$i}}) {
372                 &DEBUG("leak:   \$channels{$chan}{$i}{$_} ...");
373             }
374         }
375     }
376
377     &ScheduleThis(60, "leakCheck") if (@_);
378 }
379
380 sub ignoreListCheck {
381     my $time = time();
382     my $count = 0;
383
384     foreach (keys %ignoreList) {
385         next if ($ignoreList{$_} == 1);
386         next unless ($time > $ignoreList{$_});
387
388         delete $ignoreList{$_};
389         &status("ignore: $_ has expired.");
390         $count++;
391     }
392     &VERB("ignore: $count items deleted.",2);
393
394     &ScheduleThis(30, "ignoreListCheck") if (@_);
395 }
396
397 sub ircCheck {
398     my @array = split /[\t\s]+/, $param{'join_channels'};
399     my $iconf = scalar(@array);
400     my $inow  = scalar(keys %channels);
401     if ($iconf > 2 and $inow * 2 <= $iconf) {
402         &FIXME("ircCheck: current channels * 2 <= config channels. FIXME.");
403     }
404
405     if (!$conn->connected and time - $msgtime > 3600) {
406         &WARN("ircCheck: no msg for 3600 and disco'd! reconnecting!");
407         $msgtime = time();      # just in case.
408         &ircloop();
409     }
410
411     if ($ident !~ /^\Q$param{ircNick}\E$/) {
412         &WARN("ircCheck: ident($ident) != param{ircNick}($param{IrcNick}).");
413     }
414
415     &joinNextChan();
416         # if scalar @joinnext => join more channels
417         # else check for chanserv.
418
419     if (grep /^\s*$/, keys %channels) {
420         &WARN("we have a NULL chan in hash channels? removing!");
421         delete $channels{''};
422         &status("channels now:");
423         foreach (keys %channels) {
424             &status("  $_");
425         }
426     }
427
428
429     &ScheduleThis(240, "ircCheck") if (@_);
430 }
431
432 sub miscCheck {
433     # SHM check.
434     my @ipcs;
435     if ( -x "/usr/bin/ipcs") {
436         @ipcs = `/usr/bin/ipcs`;
437     } else {
438         &WARN("ircCheck: no 'ipcs' binary.");
439     }
440
441     # shmid stale remove.
442     foreach (@ipcs) {
443         chop;
444
445         # key, shmid, owner, perms, bytes, nattch
446         next unless (/^(0x\d+) (\d+)\s+(\S+)\s+(\d+)\s+(\d+)\s+/);
447
448         my ($shmid, $size) = ($2,$5);
449         next unless ($shmid != $shm and $size == 2000);
450
451         &status("SHM: nuking shmid $shmid");
452         system("/usr/bin/ipcrm shm $shmid >/dev/null");
453     }
454
455     ### check modules if they've been modified. might be evil.
456     &reloadAllModules();
457
458     &ScheduleThis(240, "miscCheck") if (@_);
459 }
460
461 sub shmFlush {
462     my $shmmsg = &shmRead($shm);
463     $shmmsg =~ s/\0//g;         # remove padded \0's.
464
465     return if ($$ != $main::bot_pid); # fork protection.
466
467     foreach (split '\|\|', $shmmsg) {
468         &VERB("shm: Processing '$_'.",2);
469
470         if (/^DCC SEND (\S+) (\S+)$/) {
471             my ($nick,$file) = ($1,$2);
472             if (exists $dcc{'SEND'}{$who}) {
473                 &msg($nick,"DCC already active.");
474             } else {
475                 &DEBUG("shm: dcc sending $2 to $1.");
476                 $conn->new_send($1,$2);
477                 $dcc{'SEND'}{$who} = time();
478             }
479         } elsif (/^SET FORKPID (\S+) (\S+)/) {
480             $forked{$1}{PID} = $2;
481         } elsif (/^DELETE FORK (\S+)$/) {
482             delete $forked{$1};
483         } elsif (/^EVAL (.*)$/) {
484             &DEBUG("evaling '$1'.");
485             eval $1;
486         } else {
487             &DEBUG("shm: unknown msg. ($_)");
488         }
489     }
490
491     &shmWrite($shm,"") if ($shmmsg ne "");
492
493     &ScheduleThis(5, "shmFlush") if (@_);
494 }
495
496 ### this is semi-scheduled
497 sub getNickInUse {
498     if ($ident eq $param{'ircNick'}) {
499         &status("okay, got my nick back.");
500         return;
501     }
502
503     &status("Trying to get my nick back.");
504     &nick($param{'ircNick'});
505
506     &ScheduleThis(5, "getNickInUse") if (@_);
507 }
508
509 sub uptimeCycle {
510     &uptimeWriteFile();
511
512     &ScheduleThis(60, "uptimeCycle") if (@_);
513 }
514
515 sub slashdotCycle {
516     &Forker("slashdot", sub { &Slashdot::slashdotAnnounce(); } );
517
518     &ScheduleThis(60, "slashdotCycle") if (@_);
519 }
520
521 sub freshmeatCycle {
522     &Forker("freshmeat", sub { &Freshmeat::freshmeatAnnounce(); } );
523
524     &ScheduleThis(60, "freshmeatCycle") if (@_);
525 }
526
527 sub kernelCycle {
528     &Forker("kernel", sub { &Kernel::kernelAnnounce(); } );
529
530     &ScheduleThis(240, "kernelCycle") if (@_);
531 }
532
533 sub wingateCheck {
534     return unless &IsParam("wingate");
535     return unless ($param{'wingate'} =~ /^(.*\s+)?$chan(\s+.*)?$/i);
536
537     ### FILE CACHE OF OFFENDING WINGATES.
538     foreach (grep /^$host$/, @wingateBad) {
539         &status("Wingate: RUNNING ON $host BY $who");
540         &ban("*!*\@$host", "") if &IsParam("wingateBan");
541
542         next unless (&IsParam("wingateKick"));
543         &kick($who, "", $param{'wingateKick'})
544     }
545
546     ### RUN CACHE OF TRIED WINGATES.
547     if (grep /^$host$/, @wingateCache) {
548         push(@wingateNow, $host);       # per run.
549         push(@wingateCache, $host);     # cache per run.
550     } else {
551         &DEBUG("Already scanned $host. good.");
552     }
553
554     my $interval = $param{'wingateInterval'} || 60;     # seconds.
555     return if (defined $forked{'wingate'});
556     return if (time() - $wingaterun <= $interval);
557     return unless (scalar(keys %wingateToDo));
558
559     $wingaterun = time();
560
561     &Forker("wingate", sub { &Wingate::Wingates(keys %wingateToDo); } );
562     undef @wingateNow;
563 }
564
565 ### TODO.
566 sub wingateWriteFile {
567     return unless (scalar @wingateCache);
568
569     my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
570     if ($bot_pid != $$) {
571         &DEBUG("wingateWriteFile: Reorganising!");
572
573         open(IN, $file);
574         while (<IN>) {
575             chop;
576             push(@wingateNow, $_);
577         }
578         close IN;
579
580         # very lame hack.
581         my %hash = map { $_ => 1 } @wingateNow;
582         @wingateNow = sort keys %hash;
583     }
584
585     &DEBUG("wingateWF: writing...");
586     open(OUT, ">$file");
587     foreach (@wingateNow) {
588         print OUT "$_\n";
589     }
590     close OUT;
591
592     &ScheduleThis(60, "wingateWriteFile") if (@_);
593 }
594
595 sub factoidCheck {
596     my @list = &searchTable("factoids", "factoid_key", "factoid_key", " #DEL#");
597     my $stale = $param{'factoidDeleteDelay'}*60*60*24;
598
599     foreach (@list) {
600         my $age = &getFactInfo($_, "modified_time");    
601         next unless (time() - $age > $stale);
602
603         my $fix = $_;
604         $fix =~ s/ #DEL#$//g;
605         &VERB("safedel: Removing $fix for good.",2);
606         &delFactoid($_);
607     }
608
609     &ScheduleThis(1440, "factoidCheck") if (@_);
610 }
611
612 sub schedulerSTUB {
613
614     &ScheduleThis(TIME_IN_MINUTES, "FUNCTION") if (@_);
615 }
616
617 1;