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{$_}{RUNNING} } keys %sched;
47 foreach (keys %sched) {
48 next unless (exists $sched{$_}{RUNNING});
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}) {
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}{$_} or defined $flood{$who}{$_}) {
361 &WARN("flood{$who}{$_} undefined?");
365 if ($time - $flood{$who}{$_} > $interval) {
366 delete $flood{$who}{$_};
371 &VERB("floodCycle: deleted $delete items.",2);
379 $stats{'count_old'} = &countKeys("seen");
384 my $interval = $param{'seenFlushInterval'} || 60;
385 &ScheduleThis($interval, "seenFlush");
386 &ScheduleChecked("seenFlush");
387 return if ($_[0] eq "2");
390 if ($param{'DBType'} =~ /^mysql|pg|postgres/i) {
391 foreach $nick (keys %seencache) {
392 my $exists = &dbGet("seen","nick", $nick, "nick");
394 if (defined $exists and $exists) {
395 &dbUpdate("seen", "nick", $nick, (
396 "time" => $seencache{$nick}{'time'},
397 "host" => $seencache{$nick}{'host'},
398 "channel" => $seencache{$nick}{'chan'},
399 "message" => $seencache{$nick}{'msg'},
403 my $retval = &dbInsert("seen", $nick, (
404 "nick" => $seencache{$nick}{'nick'},
405 "time" => $seencache{$nick}{'time'},
406 "host" => $seencache{$nick}{'host'},
407 "channel" => $seencache{$nick}{'chan'},
408 "message" => $seencache{$nick}{'msg'},
412 ### TODO: put bad nick into a list and don't do it again!
413 &FIXME("Should never happen! (nick => $nick)") if !$retval;
416 delete $seencache{$nick};
420 } elsif ($param{'DBType'} =~ /^dbm/i) {
422 foreach $nick (keys %seencache) {
423 my $retval = &dbInsert("seen", $nick, (
424 "nick" => $seencache{$nick}{'nick'},
425 "time" => $seencache{$nick}{'time'},
426 "host" => $seencache{$nick}{'host'},
427 "channel" => $seencache{$nick}{'chan'},
428 "message" => $seencache{$nick}{'msg'},
431 ### TODO: put bad nick into a list and don't do it again!
432 &FIXME("Should never happen! (nick => $nick)") if !$retval;
434 delete $seencache{$nick};
438 &DEBUG("seenFlush: NO VALID FACTOID SUPPORT?");
441 &status("Flushed $flushed seen entries.") if ($flushed);
442 &VERB(sprintf(" new seen: %03.01f%% (%d/%d)",
443 $stats{'new'}*100/$stats{'count_old'},
444 $stats{'new'}, $stats{'count_old'} ), 2) if ($stats{'new'});
445 &VERB(sprintf(" now seen: %3.1f%% (%d/%d)",
446 $stats{'old'}*100/&countKeys("seen"),
447 $stats{'old'}, &countKeys("seen") ), 2) if ($stats{'old'});
449 &WARN("scalar keys seenflush != 0!") if (scalar keys %seenflush);
458 &ScheduleThis(60, "leakCheck");
459 &ScheduleChecked("leakCheck");
460 return if ($_[0] eq "2");
464 foreach $blah1 (keys %flood) {
465 foreach $blah2 (keys %{$flood{$blah1}}) {
466 $count += scalar(keys %{$flood{$blah1}{$blah2}});
469 &VERB("\%flood has $count total keys.",2);
472 foreach $chan (grep /[A-Z]/, keys %channels) {
473 &DEBUG("leak: chan => '$chan'.");
475 foreach $i (keys %{$channels{$chan}}) {
476 foreach (keys %{$channels{$chan}{$i}}) {
477 &DEBUG("leak: \$channels{$chan}{$i}{$_} ...");
487 foreach (keys %ignore) {
490 foreach (keys %{ $ignore{$chan} }) {
491 my @array = $ignore{$chan}{$_};
498 next unless ($time > $ignore{$_});
500 delete $ignore{$chan}{$_};
501 &status("ignore: $_/$chan has expired.");
505 &VERB("ignore: $count items deleted.",2);
507 &ScheduleThis(60, "ignoreCheck") if (@_);
511 my @array = grep !/^_default$/, keys %chanconf;
512 my $iconf = scalar(@array);
513 my $inow = scalar(keys %channels);
514 if ($iconf > 2 and $inow * 2 <= $iconf) {
515 &FIXME("ircCheck: current channels * 2 <= config channels. FIXME.");
518 if (!$conn->connected and time - $msgtime > 3600) {
519 &WARN("ircCheck: no msg for 3600 and disco'd! reconnecting!");
520 $msgtime = time(); # just in case.
524 if ($ident !~ /^\Q$param{ircNick}\E$/) {
525 &WARN("ircCheck: ident($ident) != param{ircNick}($param{IrcNick}).");
529 # if scalar @joinnext => join more channels
530 # else check for chanserv.
532 if (grep /^\s*$/, keys %channels) {
533 &WARN("we have a NULL chan in hash channels? removing!");
534 delete $channels{''};
535 &status("channels now:");
536 foreach (keys %channels) {
542 if ($utime_userfile > $wtime_userfile and time() - $wtime_userfile > 3600) {
544 $wtime_userfile = time();
547 if ($utime_chanfile > $wtime_chanfile and time() - $wtime_chanfile > 3600) {
549 $wtime_chanfile = time();
552 &ScheduleThis(240, "ircCheck") if (@_);
556 &ScheduleThis(240, "miscCheck") if (@_);
560 if ( -x "/usr/bin/ipcs") {
561 @ipcs = `/usr/bin/ipcs`;
563 &WARN("ircCheck: no 'ipcs' binary.");
567 # shmid stale remove.
571 # key, shmid, owner, perms, bytes, nattch
572 next unless (/^(0x\d+) (\d+)\s+(\S+)\s+(\d+)\s+(\d+)\s+/);
574 my ($shmid, $size) = ($2,$5);
575 next unless ($shmid != $shm and $size == 2000);
577 ### &status("SHM: nuking shmid $shmid");
578 ### system("/usr/bin/ipcrm shm $shmid >/dev/null");
581 ### check modules if they've been modified. might be evil.
587 &ScheduleThis(5, "shmFlush");
588 &ScheduleChecked("shmFlush");
589 return if ($_[0] eq "2");
592 my $shmmsg = &shmRead($shm);
593 $shmmsg =~ s/\0//g; # remove padded \0's.
595 return if ($$ != $::bot_pid); # fork protection.
597 foreach (split '\|\|', $shmmsg) {
598 &VERB("shm: Processing '$_'.",2);
600 if (/^DCC SEND (\S+) (\S+)$/) {
601 my ($nick,$file) = ($1,$2);
602 if (exists $dcc{'SEND'}{$who}) {
603 &msg($nick,"DCC already active.");
605 &DEBUG("shm: dcc sending $2 to $1.");
606 $conn->new_send($1,$2);
607 $dcc{'SEND'}{$who} = time();
609 } elsif (/^SET FORKPID (\S+) (\S+)/) {
610 $forked{$1}{PID} = $2;
611 } elsif (/^DELETE FORK (\S+)$/) {
613 } elsif (/^EVAL (.*)$/) {
614 &DEBUG("evaling '$1'.");
617 &DEBUG("shm: unknown msg. ($_)");
621 &shmWrite($shm,"") if ($shmmsg ne "");
624 ### this is semi-scheduled
626 if ($ident eq $param{'ircNick'}) {
627 &status("okay, got my nick back.");
631 &status("Trying to get my nick back.");
632 &nick($param{'ircNick'});
634 &ScheduleThis(5, "getNickInUse") if (@_);
640 &ScheduleThis(60, "uptimeCycle") if (@_);
644 &ScheduleThis(60, "slashdotCycle") if (@_);
645 &ScheduleChecked("slashdotCycle");
646 return if ($_[0] eq "2");
648 my @chans = &ChanConfList("slashdotAnnounce");
649 return unless (scalar @chans);
651 &Forker("slashdot", sub {
652 my @data = &Slashdot::slashdotAnnounce();
655 next unless (&::validChan($_));
657 &::status("sending slashdot update to $_.");
660 ¬ice($c, "Slashdot: $_");
667 &ScheduleThis(60, "freshmeatCycle") if (@_);
668 &ScheduleChecked("freshmeatCycle");
669 return if ($_[0] eq "2");
671 my @chans = &ChanConfList("freshmeatAnnounce");
672 return unless (scalar @chans);
674 &Forker("freshmeat", sub {
675 my $data = &Freshmeat::freshmeatAnnounce();
678 next unless (&::validChan($_));
680 &::status("sending freshmeat update to $_.");
687 &ScheduleThis(240, "kernelCycle") if (@_);
688 &ScheduleChecked("kernelCycle");
689 return if ($_[0] eq "2");
691 my @chans = &ChanConfList("kernelAnnounce");
692 return unless (scalar @chans);
694 &Forker("kernel", sub {
695 my @data = &Kernel::kernelAnnounce();
698 next unless (&::validChan($_));
700 &::status("sending kernel update to $_.");
703 ¬ice($c, "Kernel: $_");
710 return unless &IsParam("wingate");
711 return unless ($param{'wingate'} =~ /^(.*\s+)?$chan(\s+.*)?$/i);
713 ### FILE CACHE OF OFFENDING WINGATES.
714 foreach (grep /^$host$/, @wingateBad) {
715 &status("Wingate: RUNNING ON $host BY $who");
716 &ban("*!*\@$host", "") if &IsParam("wingateBan");
718 next unless (&IsParam("wingateKick"));
719 &kick($who, "", $param{'wingateKick'})
722 ### RUN CACHE OF TRIED WINGATES.
723 if (grep /^$host$/, @wingateCache) {
724 push(@wingateNow, $host); # per run.
725 push(@wingateCache, $host); # cache per run.
727 &DEBUG("Already scanned $host. good.");
730 my $interval = $param{'wingateInterval'} || 60; # seconds.
731 return if (defined $forked{'wingate'});
732 return if (time() - $wingaterun <= $interval);
733 return unless (scalar(keys %wingateToDo));
735 $wingaterun = time();
737 &Forker("wingate", sub { &Wingate::Wingates(keys %wingateToDo); } );
742 sub wingateWriteFile {
743 return unless (scalar @wingateCache);
745 my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
746 if ($bot_pid != $$) {
747 &DEBUG("wingateWriteFile: Reorganising!");
752 push(@wingateNow, $_);
757 my %hash = map { $_ => 1 } @wingateNow;
758 @wingateNow = sort keys %hash;
761 &DEBUG("wingateWF: writing...");
763 foreach (@wingateNow) {
768 &ScheduleThis(60, "wingateWriteFile") if (@_);
772 my @list = &searchTable("factoids", "factoid_key", "factoid_key", " #DEL#");
773 my $stale = ($param{'factoidDeleteDelay'} || 7)*60*60*24;
776 my $age = &getFactInfo($_, "modified_time");
777 next unless (time() - $age > $stale);
780 $fix =~ s/ #DEL#$//g;
781 &VERB("safedel: Removing $fix for good.",2);
785 &ScheduleThis(1440, "factoidCheck") if (@_);
789 my $time = strftime("%H:%M", localtime(time()) );
791 return unless (scalar keys %{ $DCC{CHAT} });
793 foreach (keys %channels) {
794 &DCCBroadcast("[$time] $_: $users members ($chops chops), $bans bans","+o");
797 &ScheduleThis(10, "dccStatus") if (@_);
802 &ScheduleThis(TIME_IN_MINUTES, "FUNCTION") if (@_);
813 foreach (keys %{ $irc->{_queue} }) {
817 foreach (keys %sched) {
818 next unless ($q eq $sched{$_});
823 my $time = $irc->{_queue}->{$q}->[0] - time();
825 if (defined $sched) {
826 &DEBUG(" $sched($q): ".&Time2String($time) );
828 &DEBUG(" NULL($q): ".&Time2String($time) );
832 &DEBUG("end of sList.");
835 sub getChanConfDefault {
836 my($what, $chan, $default) = @_;
838 if (exists $param{$what}) {
839 return $param{$what};
842 my $val = &getChanConf($what, $chan);
846 &DEBUG("returning default $default for $what");
847 ### TODO: set some vars?