2 # ProcessExtra.pl: Extensions to Process.pl
4 # Version: v0.5 (20010124)
8 if (&IsParam("useStrict")) { use strict; }
10 use POSIX qw(strftime);
14 &VERB("Starting schedulers...",2);
25 &netsplitCheck(1); # mandatory
26 &floodLoop(1); # mandatory
28 &leakCheck(1); # mandatory
29 &ignoreCheck(1); # mandatory
31 &ircCheck(1); # mandatory
32 &miscCheck(2); # mandatory
33 &shmFlush(1); # mandatory
40 # my $count = map { exists $sched{$_}{TIME} } keys %sched;
42 foreach (keys %sched) {
43 # next unless (exists $sched{$_}{TIME});
44 my $time = $sched{$_}{TIME};
45 next unless (defined $time and $time > time());
50 &status("Schedulers: $count will be running.");
55 my ($interval, $codename, @args) = @_;
56 my $waittime = &getRandomInt($interval);
58 if (!defined $waittime) {
59 &WARN("interval == waittime == UNDEF for $codename.");
63 my $time = $sched{$codename}{TIME};
64 if (defined $time and $time > time()) {
65 &WARN("Sched for $codename already exists.");
69 # &VERB("Scheduling \&$codename() for ".&Time2String($waittime),3);
71 my $retval = $conn->schedule($waittime, \&$codename, @args);
72 $sched{$codename}{LABEL} = $retval;
73 $sched{$codename}{TIME} = time()+$waittime;
74 $sched{$codename}{RUNNING} = 1;
78 #### LET THE FUN BEGIN.
82 my $interval = &getChanConfDefault("randomQuoteInterval", 60);
84 &ScheduleThis($interval, "randomQuote");
85 return if ($_[0] eq "2"); # defer.
87 delete $sched{"randomQuote"}{RUNNING};
90 my $line = &getRandomLineFromFile($bot_misc_dir. "/blootbot.randtext");
92 &ERROR("random Quote: weird error?");
96 foreach ( &ChanConfList("randomQuote") ) {
97 next unless (&validChan($_)); # ???
99 &status("sending random Quote to $_.");
100 &action($_, "Ponders: ".$line);
102 ### TODO: if there were no channels, don't reschedule until channel
103 ### configuration is modified.
110 my $interval = &getChanConfDefault("randomFactoidInterval", 60);
112 &ScheduleThis($interval, "randomFactoid");
113 return if ($_[0] eq "2"); # defer.
115 delete $sched{"randomFactoid"}{RUNNING};
119 ($key,$val) = &randKey("factoids","factoid_key,factoid_value");
120 ### $val =~ tr/^[A-Z]/[a-z]/; # blah is Good => blah is good.
121 last if ($val !~ /^</);
124 &ERROR("rF: tried 5 times but failed.");
129 foreach ( &ChanConfList("randomFactoid") ) {
130 next unless (&validChan($_)); # ???
132 &status("sending random Factoid to $_.");
133 &action($_, "Thinks: \037$key\037 is $val");
134 ### FIXME: Use &getReply() on above to format factoid properly?
139 sub randomFreshmeat {
140 my $interval = &getChanConfDefault("randomFresheatInterval", 60);
143 &ScheduleThis($interval, "randomFreshmeat");
144 return if ($_[0] eq "2"); # defer.
146 delete $sched{"randomFreshmeat"}{RUNNING};
149 my @chans = &ChanConfList("randomFreshmeat");
150 return unless (scalar @chans);
152 &Forker("freshmeat", sub {
153 my $retval = &Freshmeat::randPackage();
156 next unless (&validChan($_)); # ???
158 &status("sending random Freshmeat to $_.");
166 &ScheduleThis(60, "logLoop");
167 return if ($_[0] eq "2"); # defer.
169 delete $sched{"logLoop"}{RUNNING};
172 return unless (defined fileno LOG);
173 return unless (&IsParam("logfile"));
174 return unless (&IsParam("maxLogSize"));
176 ### check if current size is too large.
177 if ( -s $file{log} > $param{'maxLogSize'}) {
178 my $date = sprintf("%04d%02d%02d", (localtime)[5,4,3]);
179 $file{log} = $param{'logfile'} ."-". $date;
180 &status("cycling log file.");
182 if ( -e $file{log}) {
186 $newlog = $file{log}."-".$i;
187 last if (! -e $newlog);
190 $file{log} = $newlog;
194 system("/bin/mv '$param{'logfile'}' '$file{log}'");
195 &compress($file{log});
197 &status("cycling log file.");
200 ### check if all the logs exceed size.
201 my $logdir = "$bot_base_dir/log/";
202 if (opendir(LOGS, $logdir)) {
206 while (defined($_ = readdir LOGS)) {
207 my $logfile = "$logdir/$_";
209 next unless ( -f $logfile);
210 my $size = -s $logfile;
211 my $age = (stat $logfile)[9];
213 $age{$age} = $logfile;
214 $size{$logfile} = $size;
221 while ($tsize > $param{'maxLogSize'}) {
222 &status("LOG: current size > max ($tsize > $param{'maxLogSize'})");
223 my $oldest = (sort {$a <=> $b} keys %age)[0];
224 &status("LOG: unlinking $age{$oldest}.");
225 unlink $age{$oldest};
230 ### TODO: add how many b,kb,mb removed?
231 &status("LOG: removed $delete logs.") if ($delete);
233 &WARN("could not open dir $logdir");
240 &ScheduleThis(1440, "seenFlushOld");
241 return if ($_[0] eq "2"); # defer.
243 delete $sched{"seenFlushOld"}{RUNNING};
246 # is this global-only?
247 return unless (&IsChanConf("seen") > 0);
248 return unless (&IsChanConf("seenFlushInterval") > 0);
250 # global setting. does not make sense for per-channel.
251 my $max_time = &getChanConfDefault("seenMaxDays", 30) *60*60*24;
254 if ($param{'DBType'} =~ /^pg|postgres|mysql/i) {
255 my $query = "SELECT nick,time FROM seen GROUP BY nick HAVING UNIX_TIMESTAMP() - time > $max_time";
256 my $sth = $dbh->prepare($query);
259 while (my @row = $sth->fetchrow_array) {
260 my ($nick,$time) = @row;
262 &dbDel("seen","nick",$nick);
266 } elsif ($param{'DBType'} =~ /^dbm/i) {
269 foreach (keys %seen) {
270 my $delta_time = $time - &dbGet("seen", "NULL", $_, "time");
271 next unless ($delta_time > $max_time);
273 &DEBUG("seenFlushOld: ".&Time2String($delta_time) );
278 &FIXME("seenFlushOld: for PG/NO-DB.");
280 &VERB("SEEN deleted $delete seen entries.",2);
285 my $interval = &getChanConfDefault("chanlimitcheckInterval", 10);
288 &ScheduleThis($interval, "chanlimitCheck");
289 return if ($_[0] eq "2");
291 delete $sched{"chanlimitCheck"}{RUNNING};
294 foreach ( &ChanConfList("chanlimitcheck") ) {
295 next unless (&validChan($_)); # ???
297 my $limitplus = &getChanConfDefault("chanlimitcheckPlus", 5, $_);
298 my $newlimit = scalar(keys %{$channels{$_}{''}}) + $limitplus;
299 my $limit = $channels{$_}{'l'};
301 if (scalar keys %{$channels{$_}{''}} > $limit) {
302 &status("LIMIT: set too low!!! FIXME");
303 ### run NAMES again and flush it.
306 next unless (!defined $limit or $limit != $newlimit);
308 if (!exists $channels{$_}{'o'}{$ident}) {
309 &ERROR("chanlimitcheck: dont have ops on $_.");
312 &rawout("MODE $_ +l $newlimit");
321 &ScheduleThis(30, "netsplitCheck");
322 return if ($_[0] eq "2");
324 delete $sched{"netsplitCheck"}{RUNNING};
327 foreach $s1 (keys %netsplitservers) {
328 foreach $s2 (keys %{$netsplitservers{$s1}}) {
329 if (time() - $netsplitservers{$s1}{$s2} > 3600) {
330 &status("netsplit between $s1 and $s2 appears to be stale.");
331 delete $netsplitservers{$s1}{$s2};
336 # %netsplit hash checker.
337 foreach (keys %netsplit) {
338 if (&IsNickInAnyChan($_)) {
339 &DEBUG("netsplitC: $_ is in some chan; removing from netsplit list.");
340 delete $netsplit{$_};
342 next unless (time() - $netsplit{$_} > 60*60*2); # 2 hours.
343 next if (&IsNickInAnyChan($_));
345 &DEBUG("netsplitC: $_ didn't come back from netsplit in 2 hours; removing from netsplit list.");
346 delete $netsplit{$_};
355 &ScheduleThis(60, "floodLoop"); # minutes.
356 return if ($_[0] eq "2");
358 delete $sched{"floodLoop"}{RUNNING};
362 my $interval = &getChanConfDefault("floodCycle",60);
364 foreach $who (keys %flood) {
365 foreach (keys %{$flood{$who}}) {
366 if (!exists $flood{$who}{$_}) {
367 &WARN("flood{$who}{$_} undefined?");
371 if ($time - $flood{$who}{$_} > $interval) {
372 delete $flood{$who}{$_};
377 &VERB("floodLoop: deleted $delete items.",2);
384 $stats{'count_old'} = &countKeys("seen") || 0;
389 my $interval = &getChanConfDefault("seenFlushInterval", 60);
390 &ScheduleThis($interval, "seenFlush");
391 return if ($_[0] eq "2");
393 delete $sched{"seenFlush"}{RUNNING};
396 if ($param{'DBType'} =~ /^mysql|pg|postgres/i) {
397 foreach $nick (keys %seencache) {
398 my $exists = &dbGet("seen","nick", $nick, "nick");
400 if (defined $exists and $exists) {
401 &dbUpdate("seen", "nick", $nick, (
402 "time" => $seencache{$nick}{'time'},
403 "host" => $seencache{$nick}{'host'},
404 "channel" => $seencache{$nick}{'chan'},
405 "message" => $seencache{$nick}{'msg'},
409 my $retval = &dbInsert("seen", $nick, (
410 "nick" => $seencache{$nick}{'nick'},
411 "time" => $seencache{$nick}{'time'},
412 "host" => $seencache{$nick}{'host'},
413 "channel" => $seencache{$nick}{'chan'},
414 "message" => $seencache{$nick}{'msg'},
418 ### TODO: put bad nick into a list and don't do it again!
419 &FIXME("Should never happen! (nick => $nick)") if !$retval;
422 delete $seencache{$nick};
426 } elsif ($param{'DBType'} =~ /^dbm/i) {
428 foreach $nick (keys %seencache) {
429 my $retval = &dbInsert("seen", $nick, (
430 "nick" => $seencache{$nick}{'nick'},
431 "time" => $seencache{$nick}{'time'},
432 "host" => $seencache{$nick}{'host'},
433 "channel" => $seencache{$nick}{'chan'},
434 "message" => $seencache{$nick}{'msg'},
437 ### TODO: put bad nick into a list and don't do it again!
438 &FIXME("Should never happen! (nick => $nick)") if !$retval;
440 delete $seencache{$nick};
444 &DEBUG("seenFlush: NO VALID FACTOID SUPPORT?");
447 &status("Flushed $flushed seen entries.") if ($flushed);
448 &VERB(sprintf(" new seen: %03.01f%% (%d/%d)",
449 $stats{'new'}*100/$stats{'count_old'},
450 $stats{'new'}, $stats{'count_old'} ), 2) if ($stats{'new'});
451 &VERB(sprintf(" now seen: %3.1f%% (%d/%d)",
452 $stats{'old'}*100/&countKeys("seen"),
453 $stats{'old'}, &countKeys("seen") ), 2) if ($stats{'old'});
455 &WARN("scalar keys seenflush != 0!") if (scalar keys %seenflush);
464 &ScheduleThis(60, "leakCheck");
465 return if ($_[0] eq "2");
467 delete $sched{"leakCheck"}{RUNNING};
471 foreach $blah1 (keys %flood) {
472 foreach $blah2 (keys %{$flood{$blah1}}) {
473 $count += scalar(keys %{$flood{$blah1}{$blah2}});
476 &VERB("\%flood has $count total keys.",2);
479 foreach $chan (grep /[A-Z]/, keys %channels) {
480 &DEBUG("leak: chan => '$chan'.");
482 foreach $i (keys %{$channels{$chan}}) {
483 foreach (keys %{$channels{$chan}{$i}}) {
484 &DEBUG("leak: \$channels{$chan}{$i}{$_} ...");
490 foreach (keys %nuh) {
491 next if (&IsNickInAnyChan($_));
496 &DEBUG("$delete nuh{} items deleted; now have ".
497 scalar(keys %nuh) ) if ($delete);
502 &ScheduleThis(60, "ignoreCheck");
503 return if ($_[0] eq "2"); # defer.
505 delete $sched{"ignoreCheck"}{RUNNING};
511 foreach (keys %ignore) {
514 foreach (keys %{ $ignore{$chan} }) {
515 my @array = @{ $ignore{$chan}{$_} };
517 next unless ($array[0] and $time > $array[0]);
519 delete $ignore{$chan}{$_};
520 &status("ignore: $_/$chan has expired.");
524 &VERB("ignore: $count items deleted.",2);
530 &ScheduleThis(240, "ircCheck");
531 return if ($_[0] eq "2"); # defer.
533 delete $sched{"ircCheck"}{RUNNING};
536 my @array = grep !/^_default$/, keys %chanconf;
537 my $iconf = scalar(@array);
538 my $inow = scalar(keys %channels);
539 if ($iconf > 2 and $inow * 2 <= $iconf) {
540 &FIXME("ircCheck: current channels * 2 <= config channels. FIXME.");
544 foreach ( &ChanConfList("chanServ_ops") ) {
545 next if (exists $channels{$chan}{'o'}{$ident});
547 &status("ChanServ ==> Requesting ops for $chan.");
548 &rawout("PRIVMSG ChanServ :OP $chan $ident");
551 if (!$conn->connected and time - $msgtime > 3600) {
552 &WARN("ircCheck: no msg for 3600 and disco'd! reconnecting!");
553 $msgtime = time(); # just in case.
557 if ($ident !~ /^\Q$param{ircNick}\E$/) {
558 &WARN("ircCheck: ident($ident) != param{ircNick}($param{IrcNick}).");
559 ### TODO: schedule check for own nick if taken?
563 # if scalar @joinnext => join more channels
564 # else check for chanserv.
566 if (grep /^\s*$/, keys %channels) {
567 &WARN("we have a NULL chan in hash channels? removing!");
568 delete $channels{''}; # ???
569 &DEBUG("channels now:");
570 foreach (keys %channels) {
573 &DEBUG("channels END");
577 if ($utime_userfile > $wtime_userfile and time() - $wtime_userfile > 3600) {
579 $wtime_userfile = time();
582 if ($utime_chanfile > $wtime_chanfile and time() - $wtime_chanfile > 3600) {
584 $wtime_chanfile = time();
590 &ScheduleThis(240, "miscCheck");
591 return if ($_[0] eq "2"); # defer.
593 delete $sched{"miscCheck"}{RUNNING};
598 if ( -x "/usr/bin/ipcs") {
599 @ipcs = `/usr/bin/ipcs`;
601 &WARN("ircCheck: no 'ipcs' binary.");
605 # shmid stale remove.
609 # key, shmid, owner, perms, bytes, nattch
610 next unless (/^(0x\d+) (\d+)\s+(\S+)\s+(\d+)\s+(\d+)\s+/);
612 my ($shmid, $size) = ($2,$5);
613 next unless ($shmid != $shm and $size == 2000);
614 my $z = &shmRead($shmid);
615 if ($z =~ /^(\d+): /) {
617 next if (time() - $time < 60*60);
620 &DEBUG("shm: $shmid is not ours or old blootbot => ($z)");
624 &status("SHM: nuking shmid $shmid");
625 system("/usr/bin/ipcrm shm $shmid >/dev/null");
629 opendir(DEBIAN, "$bot_base_dir/debian");
630 foreach ( grep /gz$/, readdir(DEBIAN) ) {
631 my $exit = system("gzip -t $bot_base_dir/debian/$_");
634 &status("debian: unlinking file => $_");
635 unlink "$bot_base_dir/debian/$_";
639 ### check modules if they've been modified. might be evil.
644 return if ($$ != $::bot_pid); # fork protection.
647 &ScheduleThis(5, "shmFlush");
648 return if ($_[0] eq "2");
650 delete $sched{"shmFlush"}{RUNNING};
654 my $shmmsg = &shmRead($shm);
655 $shmmsg =~ s/\0//g; # remove padded \0's.
656 if ($shmmsg =~ s/^(\d+): //) {
660 foreach (split '\|\|', $shmmsg) {
662 &VERB("shm: Processing '$_'.",2);
664 if (/^DCC SEND (\S+) (\S+)$/) {
665 my ($nick,$file) = ($1,$2);
666 if (exists $dcc{'SEND'}{$who}) {
667 &msg($nick, "DCC already active.");
669 &DEBUG("shm: dcc sending $2 to $1.");
670 $conn->new_send($1,$2);
671 $dcc{'SEND'}{$who} = time();
673 } elsif (/^SET FORKPID (\S+) (\S+)/) {
674 $forked{$1}{PID} = $2;
675 } elsif (/^DELETE FORK (\S+)$/) {
677 } elsif (/^EVAL (.*)$/) {
678 &DEBUG("evaling '$1'.");
681 &DEBUG("shm: unknown msg. ($_)");
685 &shmWrite($shm,"") if ($shmmsg ne "");
688 ### this is semi-scheduled
691 &ScheduleThis(30, "getNickInUse");
692 return if ($_[0] eq "2"); # defer.
694 delete $sched{"getNickInUse"}{RUNNING};
697 if ($ident eq $param{'ircNick'}) {
698 &status("okay, got my nick back.");
702 &status("Trying to get my nick back.");
703 &nick( $param{'ircNick'} );
708 &ScheduleThis(60, "uptimeLoop");
709 return if ($_[0] eq "2"); # defer.
711 delete $sched{"uptimeLoop"}{RUNNING};
720 &ScheduleThis(60, "slashdotLoop");
721 return if ($_[0] eq "2");
723 delete $sched{"slashdotLoop"}{RUNNING};
726 my @chans = &ChanConfList("slashdotAnnounce");
727 return unless (scalar @chans);
729 &Forker("slashdot", sub {
730 my $line = &Slashdot::slashdotAnnounce();
731 return unless (defined $line);
734 next unless (&::validChan($_));
736 &::status("sending slashdot update to $_.");
737 ¬ice($_, "Slashdot: $line");
744 &ScheduleThis(60, "freshmeatLoop");
745 return if ($_[0] eq "2");
747 delete $sched{"freshmeatLoop"}{RUNNING};
750 my @chans = &ChanConfList("freshmeatAnnounce");
751 return unless (scalar @chans);
753 &Forker("freshmeat", sub {
754 my $data = &Freshmeat::freshmeatAnnounce();
757 next unless (&::validChan($_));
759 &::status("sending freshmeat update to $_.");
767 &ScheduleThis(240, "kernelLoop");
768 return if ($_[0] eq "2");
770 delete $sched{"kernelLoop"}{RUNNING};
773 my @chans = &ChanConfList("kernelAnnounce");
774 return unless (scalar @chans);
776 &Forker("kernel", sub {
777 my @data = &Kernel::kernelAnnounce();
780 next unless (&::validChan($_));
782 &::status("sending kernel update to $_.");
785 ¬ice($c, "Kernel: $_");
792 return unless &IsChanConf("wingate");
794 ### FILE CACHE OF OFFENDING WINGATES.
795 foreach (grep /^$host$/, @wingateBad) {
796 &status("Wingate: RUNNING ON $host BY $who");
797 &ban("*!*\@$host", "") if &IsChanConf("wingateBan");
799 my $reason = &getChanConf("wingateKick");
801 next unless ($reason);
802 &kick($who, "", $reason)
805 ### RUN CACHE OF TRIED WINGATES.
806 if (grep /^$host$/, @wingateCache) {
807 push(@wingateNow, $host); # per run.
808 push(@wingateCache, $host); # cache per run.
810 &DEBUG("Already scanned $host. good.");
813 my $interval = &getChanConfDefault("wingateInterval", 60); # seconds.
814 return if (defined $forked{'wingate'});
815 return if (time() - $wingaterun <= $interval);
816 return unless (scalar(keys %wingateToDo));
818 $wingaterun = time();
820 &Forker("wingate", sub { &Wingate::Wingates(keys %wingateToDo); } );
825 sub wingateWriteFile {
827 &ScheduleThis(60, "wingateWriteFile");
828 return if ($_[0] eq "2"); # defer.
830 delete $sched{"wingateWriteFile"}{RUNNING};
833 return unless (scalar @wingateCache);
835 my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
836 if ($bot_pid != $$) {
837 &DEBUG("wingateWriteFile: Reorganising!");
842 push(@wingateNow, $_);
847 my %hash = map { $_ => 1 } @wingateNow;
848 @wingateNow = sort keys %hash;
851 &DEBUG("wingateWF: writing...");
853 foreach (@wingateNow) {
862 &ScheduleThis(1440, "factoidCheck");
863 return if ($_[0] eq "2"); # defer.
865 delete $sched{"factoidCheck"}{RUNNING};
868 my @list = &searchTable("factoids", "factoid_key", "factoid_key", " #DEL#");
869 my $stale = &getChanConfDefault("factoidDeleteDelay", 7)*60*60*24;
872 my $age = &getFactInfo($_, "modified_time");
873 next unless (time() - $age > $stale);
876 $fix =~ s/ #DEL#$//g;
877 &VERB("safedel: Removing $fix for good.",2);
884 return unless (scalar keys %{ $dcc{CHAT} });
887 &ScheduleThis(10, "dccStatus");
888 return if ($_[0] eq "2"); # defer.
890 delete $sched{"dccStatus"}{RUNNING};
893 my $time = strftime("%H:%M", localtime(time()) );
895 foreach (keys %channels) {
896 my $users = keys %{ $channels{$_}{''} };
897 my $chops = keys %{ $channels{$_}{o} };
898 my $bans = keys %{ $channels{$_}{b} };
899 &DCCBroadcast("[$time] $_: $users members ($chops chops), $bans bans","+o");
911 foreach (keys %{ $irc->{_queue} }) {
915 foreach (keys %sched) {
916 next unless ($q eq $sched{$_});
921 my $time = $irc->{_queue}->{$q}->[0] - time();
923 if (defined $sched) {
924 &DEBUG(" $sched($q): ".&Time2String($time) );
926 &DEBUG(" NULL($q): ".&Time2String($time) );
930 &DEBUG("end of sList.");
933 sub getChanConfDefault {
934 my($what, $default, $chan) = @_;
936 if (exists $param{$what}) {
937 if (!exists $cache{config}{$what}) {
938 &status("gCCD: backward-compat: found param{$what} ($param{$what}) instead.");
939 $cache{config}{$what} = 1;
942 return $param{$what};
945 my $val = &getChanConf($what, $chan);
950 $param{$what} = $default;
951 &status("gCCD: setting default for param{$what} = $default");
952 $cache{config}{$what} = 1;