2 # ProcessExtra.pl: Extensions to Process.pl
4 # Version: v0.5 (20010124)
8 if (&IsParam("useStrict")) { use strict; }
10 use POSIX qw(strftime);
14 # is there a point in ScheduleChecked()?
15 # not yet... not unless we run setupSchedulers more than once.
19 &VERB("Starting schedulers...",2);
30 &netsplitCheck(1); # mandatory
31 &floodCycle(1); # mandatory
33 &leakCheck(1); # mandatory
34 &ignoreCheck(1); # mandatory
36 &ircCheck(1); # mandatory
37 &miscCheck(1); # mandatory
38 &shmFlush(1); # mandatory
45 # my $count = map { exists $sched{$_}{TIME} } keys %sched;
47 foreach (keys %sched) {
48 next unless (exists $sched{$_}{TIME});
52 &status("Schedulers: $count will be running.");
57 my ($interval, $codename, @args) = @_;
58 my $waittime = &getRandomInt($interval);
60 if (!defined $waittime) {
61 &WARN("interval == waittime == UNDEF for $codename.");
65 if (exists $sched{$codename}{RUNNING}) {
66 &WARN("Sched for $codename already exists.");
70 &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 my ($codename) = shift;
80 # what the hell is this for?
81 if (exists $sched{$codename}{RUNNING}) {
82 ### &DEBUG("SC: Removed $codename.");
83 delete $sched{$codename}{RUNNING};
85 ### &WARN("sched $codename already removed.");
90 #### LET THE FUN BEGIN.
94 my $interval = $param{'randomQuoteInterval'} || 60;
95 &ScheduleThis($interval, "randomQuote") if (@_);
96 &ScheduleChecked("randomQuote");
97 return if ($_[0] eq "2"); # defer.
99 my $line = &getRandomLineFromFile($bot_misc_dir. "/blootbot.randtext");
100 if (!defined $line) {
101 &ERROR("random Quote: weird error?");
105 foreach ( &ChanConfList("randomQuote") ) {
106 next unless (&validChan($_)); # ???
108 &status("sending random Quote to $_.");
109 &action($_, "Ponders: ".$line);
111 ### TODO: if there were no channels, don't reschedule until channel
112 ### configuration is modified.
119 my $interval = $param{'randomFactoidInterval'} || 60; # FIXME.
120 &ScheduleThis($interval, "randomFactoid") if (@_);
121 &ScheduleChecked("randomFactoid");
122 return if ($_[0] eq "2"); # defer.
125 ($key,$val) = &randKey("factoids","factoid_key,factoid_value");
126 ### $val =~ tr/^[A-Z]/[a-z]/; # blah is Good => blah is good.
127 last if ($val !~ /^</);
130 &ERROR("rF: tried 5 times but failed.");
135 foreach ( &ChanConfList("randomFactoid") ) {
136 next unless (&validChan($_)); # ???
138 &status("sending random Factoid to $_.");
139 &action($_, "Thinks: \037$key\037 is $val");
140 ### FIXME: Use &getReply() on above to format factoid properly?
145 sub randomFreshmeat {
146 my $interval = $param{'randomFresheatInterval'} || 60;
147 &ScheduleThis($interval, "randomFreshmeat") if (@_);
148 &ScheduleChecked("randomFreshmeat");
149 return if ($_[0] eq "2"); # defer.
151 my @chans = &ChanConfList("randomFreshmeat");
152 return unless (scalar @chans);
154 &Forker("freshmeat", sub {
155 my $retval = &Freshmeat::randPackage();
158 next unless (&validChan($_)); # ???
160 &status("sending random Freshmeat to $_.");
168 &ScheduleThis(60, "logCycle");
169 &ScheduleChecked("logCycle");
170 return if ($_[0] eq "2"); # defer.
173 return unless (defined fileno LOG);
174 return unless (&IsParam("logfile"));
175 return unless (&IsParam("maxLogSize"));
177 ### check if current size is too large.
178 if ( -s $file{log} > $param{'maxLogSize'}) {
179 my $date = sprintf("%04d%02d%02d", (localtime)[5,4,3]);
180 $file{log} = $param{'logfile'} ."-". $date;
181 &status("cycling log file.");
183 if ( -e $file{log}) {
187 $newlog = $file{log}."-".$i;
188 last if (! -e $newlog);
191 $file{log} = $newlog;
195 system("/bin/mv '$param{'logfile'}' '$file{log}'");
196 &compress($file{log});
198 &status("cycling log file.");
201 ### check if all the logs exceed size.
202 my $logdir = "$bot_base_dir/log/";
203 if (opendir(LOGS, $logdir)) {
207 while (defined($_ = readdir LOGS)) {
208 my $logfile = "$logdir/$_";
210 next unless ( -f $logfile);
211 my $size = -s $logfile;
212 my $age = (stat $logfile)[9];
214 $age{$age} = $logfile;
215 $size{$logfile} = $size;
222 while ($tsize > $param{'maxLogSize'}) {
223 &status("LOG: current size > max ($tsize > $param{'maxLogSize'})");
224 my $oldest = (sort {$a <=> $b} keys %age)[0];
225 &status("LOG: unlinking $age{$oldest}.");
226 unlink $age{$oldest};
231 ### TODO: add how many b,kb,mb removed?
232 &status("LOG: removed $delete logs.") if ($delete);
234 &WARN("could not open dir $logdir");
241 &ScheduleThis(1440, "seenFlushOld");
242 &ScheduleChecked("seenFlushOld");
243 return if ($_[0] eq "2"); # defer.
246 # is this global-only?
247 return unless (&IsChanConf("seen") > 0);
248 return unless (&IsChanConf("seenFlushInterval") > 0);
250 my $max_time = ($chanconf{_default}{'seenMaxDays'} || 30)
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);
286 my $interval = &getChanConf("chanlimitcheckInterval") || 10;
287 &ScheduleThis($interval, "chanlimitCheck");
288 &ScheduleChecked("chanlimitCheck");
289 return if ($_[0] eq "2");
292 foreach ( &ChanConfList("chanlimitcheck") ) {
293 next unless (&validChan($_)); # ???
295 my $limitplus = &getChanConf("chanlimitcheckPlus",$_) || 5;
296 my $newlimit = scalar(keys %{$channels{$_}{''}}) + $limitplus;
297 my $limit = $channels{$_}{'l'};
299 if (scalar keys %{$channels{$_}{''}} > $limit) {
300 &status("LIMIT: set too low!!! FIXME");
301 ### run NAMES again and flush it.
304 next unless (!defined $limit or $limit != $newlimit);
306 if (!exists $channels{$_}{'o'}{$ident}) {
307 &ERROR("chanlimitcheck: dont have ops on $_.");
310 &rawout("MODE $_ +l $newlimit");
319 &ScheduleThis(30, "netsplitCheck");
320 &ScheduleChecked("netsplitCheck");
321 return if ($_[0] eq "2");
324 foreach $s1 (keys %netsplitservers) {
325 foreach $s2 (keys %{$netsplitservers{$s1}}) {
326 if (time() - $netsplitservers{$s1}{$s2} > 3600) {
327 &status("netsplit between $s1 and $s2 appears to be stale.");
328 delete $netsplitservers{$s1}{$s2};
333 # %netsplit hash checker.
334 foreach (keys %netsplit) {
335 if (&IsNickInAnyChan($_)) {
336 &DEBUG("netsplitC: $_ is in some chan; removing from netsplit list.");
337 delete $netsplit{$_};
339 next unless (time() - $netsplit{$_} > 60*60*2); # 2 hours.
340 next if (&IsNickInAnyChan($_));
342 &DEBUG("netsplitC: $_ didn't come back from netsplit in 2 hours; removing from netsplit list.");
343 delete $netsplit{$_};
352 &ScheduleThis(60, "floodCycle"); # minutes.
353 &ScheduleChecked("floodCycle");
354 return if ($_[0] eq "2");
358 foreach $who (keys %flood) {
359 foreach (keys %{$flood{$who}}) {
360 if (!exists $flood{$who}{$_}) {
361 # or !defined $flood{$who}{$_}) {
362 &WARN("flood{$who}{$_} undefined?");
366 if ($time - $flood{$who}{$_} > $interval) {
367 delete $flood{$who}{$_};
372 &VERB("floodCycle: deleted $delete items.",2);
380 $stats{'count_old'} = &countKeys("seen");
385 my $interval = $param{'seenFlushInterval'} || 60;
386 &ScheduleThis($interval, "seenFlush");
387 &ScheduleChecked("seenFlush");
388 return if ($_[0] eq "2");
391 if ($param{'DBType'} =~ /^mysql|pg|postgres/i) {
392 foreach $nick (keys %seencache) {
393 my $exists = &dbGet("seen","nick", $nick, "nick");
395 if (defined $exists and $exists) {
396 &dbUpdate("seen", "nick", $nick, (
397 "time" => $seencache{$nick}{'time'},
398 "host" => $seencache{$nick}{'host'},
399 "channel" => $seencache{$nick}{'chan'},
400 "message" => $seencache{$nick}{'msg'},
404 my $retval = &dbInsert("seen", $nick, (
405 "nick" => $seencache{$nick}{'nick'},
406 "time" => $seencache{$nick}{'time'},
407 "host" => $seencache{$nick}{'host'},
408 "channel" => $seencache{$nick}{'chan'},
409 "message" => $seencache{$nick}{'msg'},
413 ### TODO: put bad nick into a list and don't do it again!
414 &FIXME("Should never happen! (nick => $nick)") if !$retval;
417 delete $seencache{$nick};
421 } elsif ($param{'DBType'} =~ /^dbm/i) {
423 foreach $nick (keys %seencache) {
424 my $retval = &dbInsert("seen", $nick, (
425 "nick" => $seencache{$nick}{'nick'},
426 "time" => $seencache{$nick}{'time'},
427 "host" => $seencache{$nick}{'host'},
428 "channel" => $seencache{$nick}{'chan'},
429 "message" => $seencache{$nick}{'msg'},
432 ### TODO: put bad nick into a list and don't do it again!
433 &FIXME("Should never happen! (nick => $nick)") if !$retval;
435 delete $seencache{$nick};
439 &DEBUG("seenFlush: NO VALID FACTOID SUPPORT?");
442 &status("Flushed $flushed seen entries.") if ($flushed);
443 &VERB(sprintf(" new seen: %03.01f%% (%d/%d)",
444 $stats{'new'}*100/$stats{'count_old'},
445 $stats{'new'}, $stats{'count_old'} ), 2) if ($stats{'new'});
446 &VERB(sprintf(" now seen: %3.1f%% (%d/%d)",
447 $stats{'old'}*100/&countKeys("seen"),
448 $stats{'old'}, &countKeys("seen") ), 2) if ($stats{'old'});
450 &WARN("scalar keys seenflush != 0!") if (scalar keys %seenflush);
459 &ScheduleThis(60, "leakCheck");
460 &ScheduleChecked("leakCheck");
461 return if ($_[0] eq "2");
465 foreach $blah1 (keys %flood) {
466 foreach $blah2 (keys %{$flood{$blah1}}) {
467 $count += scalar(keys %{$flood{$blah1}{$blah2}});
470 &VERB("\%flood has $count total keys.",2);
473 foreach $chan (grep /[A-Z]/, keys %channels) {
474 &DEBUG("leak: chan => '$chan'.");
476 foreach $i (keys %{$channels{$chan}}) {
477 foreach (keys %{$channels{$chan}{$i}}) {
478 &DEBUG("leak: \$channels{$chan}{$i}{$_} ...");
488 foreach (keys %ignore) {
491 foreach (keys %{ $ignore{$chan} }) {
492 my @array = $ignore{$chan}{$_};
499 next unless ($time > $ignore{$_});
501 delete $ignore{$chan}{$_};
502 &status("ignore: $_/$chan has expired.");
506 &VERB("ignore: $count items deleted.",2);
508 &ScheduleThis(60, "ignoreCheck") if (@_);
512 my @array = grep !/^_default$/, keys %chanconf;
513 my $iconf = scalar(@array);
514 my $inow = scalar(keys %channels);
515 if ($iconf > 2 and $inow * 2 <= $iconf) {
516 &FIXME("ircCheck: current channels * 2 <= config channels. FIXME.");
519 if (!$conn->connected and time - $msgtime > 3600) {
520 &WARN("ircCheck: no msg for 3600 and disco'd! reconnecting!");
521 $msgtime = time(); # just in case.
525 if ($ident !~ /^\Q$param{ircNick}\E$/) {
526 &WARN("ircCheck: ident($ident) != param{ircNick}($param{IrcNick}).");
530 # if scalar @joinnext => join more channels
531 # else check for chanserv.
533 if (grep /^\s*$/, keys %channels) {
534 &WARN("we have a NULL chan in hash channels? removing!");
535 delete $channels{''};
536 &status("channels now:");
537 foreach (keys %channels) {
543 if ($utime_userfile > $wtime_userfile and time() - $wtime_userfile > 3600) {
545 $wtime_userfile = time();
548 if ($utime_chanfile > $wtime_chanfile and time() - $wtime_chanfile > 3600) {
550 $wtime_chanfile = time();
553 &ScheduleThis(240, "ircCheck") if (@_);
557 &ScheduleThis(240, "miscCheck") if (@_);
561 if ( -x "/usr/bin/ipcs") {
562 @ipcs = `/usr/bin/ipcs`;
564 &WARN("ircCheck: no 'ipcs' binary.");
568 # shmid stale remove.
572 # key, shmid, owner, perms, bytes, nattch
573 next unless (/^(0x\d+) (\d+)\s+(\S+)\s+(\d+)\s+(\d+)\s+/);
575 my ($shmid, $size) = ($2,$5);
576 next unless ($shmid != $shm and $size == 2000);
578 ### &status("SHM: nuking shmid $shmid");
579 ### system("/usr/bin/ipcrm shm $shmid >/dev/null");
582 ### check modules if they've been modified. might be evil.
588 &ScheduleThis(5, "shmFlush");
589 &ScheduleChecked("shmFlush");
590 return if ($_[0] eq "2");
593 my $shmmsg = &shmRead($shm);
594 $shmmsg =~ s/\0//g; # remove padded \0's.
596 return if ($$ != $::bot_pid); # fork protection.
598 foreach (split '\|\|', $shmmsg) {
599 &VERB("shm: Processing '$_'.",2);
601 if (/^DCC SEND (\S+) (\S+)$/) {
602 my ($nick,$file) = ($1,$2);
603 if (exists $dcc{'SEND'}{$who}) {
604 &msg($nick,"DCC already active.");
606 &DEBUG("shm: dcc sending $2 to $1.");
607 $conn->new_send($1,$2);
608 $dcc{'SEND'}{$who} = time();
610 } elsif (/^SET FORKPID (\S+) (\S+)/) {
611 $forked{$1}{PID} = $2;
612 } elsif (/^DELETE FORK (\S+)$/) {
614 } elsif (/^EVAL (.*)$/) {
615 &DEBUG("evaling '$1'.");
618 &DEBUG("shm: unknown msg. ($_)");
622 &shmWrite($shm,"") if ($shmmsg ne "");
625 ### this is semi-scheduled
627 if ($ident eq $param{'ircNick'}) {
628 &status("okay, got my nick back.");
632 &status("Trying to get my nick back.");
633 &nick($param{'ircNick'});
635 &ScheduleThis(5, "getNickInUse") if (@_);
641 &ScheduleThis(60, "uptimeCycle") if (@_);
645 &ScheduleThis(60, "slashdotCycle") if (@_);
646 &ScheduleChecked("slashdotCycle");
647 return if ($_[0] eq "2");
649 my @chans = &ChanConfList("slashdotAnnounce");
650 return unless (scalar @chans);
652 &Forker("slashdot", sub {
653 my @data = &Slashdot::slashdotAnnounce();
656 next unless (&::validChan($_));
658 &::status("sending slashdot update to $_.");
661 ¬ice($c, "Slashdot: $_");
668 &ScheduleThis(60, "freshmeatCycle") if (@_);
669 &ScheduleChecked("freshmeatCycle");
670 return if ($_[0] eq "2");
672 my @chans = &ChanConfList("freshmeatAnnounce");
673 return unless (scalar @chans);
675 &Forker("freshmeat", sub {
676 my $data = &Freshmeat::freshmeatAnnounce();
679 next unless (&::validChan($_));
681 &::status("sending freshmeat update to $_.");
688 &ScheduleThis(240, "kernelCycle") if (@_);
689 &ScheduleChecked("kernelCycle");
690 return if ($_[0] eq "2");
692 my @chans = &ChanConfList("kernelAnnounce");
693 return unless (scalar @chans);
695 &Forker("kernel", sub {
696 my @data = &Kernel::kernelAnnounce();
699 next unless (&::validChan($_));
701 &::status("sending kernel update to $_.");
704 ¬ice($c, "Kernel: $_");
711 return unless &IsParam("wingate");
712 return unless ($param{'wingate'} =~ /^(.*\s+)?$chan(\s+.*)?$/i);
714 ### FILE CACHE OF OFFENDING WINGATES.
715 foreach (grep /^$host$/, @wingateBad) {
716 &status("Wingate: RUNNING ON $host BY $who");
717 &ban("*!*\@$host", "") if &IsParam("wingateBan");
719 next unless (&IsParam("wingateKick"));
720 &kick($who, "", $param{'wingateKick'})
723 ### RUN CACHE OF TRIED WINGATES.
724 if (grep /^$host$/, @wingateCache) {
725 push(@wingateNow, $host); # per run.
726 push(@wingateCache, $host); # cache per run.
728 &DEBUG("Already scanned $host. good.");
731 my $interval = $param{'wingateInterval'} || 60; # seconds.
732 return if (defined $forked{'wingate'});
733 return if (time() - $wingaterun <= $interval);
734 return unless (scalar(keys %wingateToDo));
736 $wingaterun = time();
738 &Forker("wingate", sub { &Wingate::Wingates(keys %wingateToDo); } );
743 sub wingateWriteFile {
744 return unless (scalar @wingateCache);
746 my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
747 if ($bot_pid != $$) {
748 &DEBUG("wingateWriteFile: Reorganising!");
753 push(@wingateNow, $_);
758 my %hash = map { $_ => 1 } @wingateNow;
759 @wingateNow = sort keys %hash;
762 &DEBUG("wingateWF: writing...");
764 foreach (@wingateNow) {
769 &ScheduleThis(60, "wingateWriteFile") if (@_);
773 my @list = &searchTable("factoids", "factoid_key", "factoid_key", " #DEL#");
774 my $stale = ($param{'factoidDeleteDelay'} || 7)*60*60*24;
777 my $age = &getFactInfo($_, "modified_time");
778 next unless (time() - $age > $stale);
781 $fix =~ s/ #DEL#$//g;
782 &VERB("safedel: Removing $fix for good.",2);
786 &ScheduleThis(1440, "factoidCheck") if (@_);
790 my $time = strftime("%H:%M", localtime(time()) );
792 return unless (scalar keys %{ $DCC{CHAT} });
794 foreach (keys %channels) {
795 &DCCBroadcast("[$time] $_: $users members ($chops chops), $bans bans","+o");
798 &ScheduleThis(10, "dccStatus") if (@_);
803 &ScheduleThis(TIME_IN_MINUTES, "FUNCTION") if (@_);
814 foreach (keys %{ $irc->{_queue} }) {
818 foreach (keys %sched) {
819 next unless ($q eq $sched{$_});
824 my $time = $irc->{_queue}->{$q}->[0] - time();
826 if (defined $sched) {
827 &DEBUG(" $sched($q): ".&Time2String($time) );
829 &DEBUG(" NULL($q): ".&Time2String($time) );
833 &DEBUG("end of sList.");
836 sub getChanConfDefault {
837 my($what, $chan, $default) = @_;
839 if (exists $param{$what}) {
840 return $param{$what};
843 my $val = &getChanConf($what, $chan);
847 &DEBUG("returning default $default for $what");
848 ### TODO: set some vars?