PageRenderTime 30ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/branches/don/dpkg/src/IRC/Schedulers.pl

#
Perl | 1232 lines | 947 code | 200 blank | 85 comment | 144 complexity | e5f2884fdf2b75b2a07284bfb90d7cff MD5 | raw file
Possible License(s): LGPL-2.0
  1. #
  2. # ProcessExtra.pl: Extensions to Process.pl
  3. # Author: dms
  4. # Version: v0.5 (20010124)
  5. # Created: 20000117
  6. #
  7. # use strict; # TODO
  8. use POSIX qw(strftime);
  9. use vars qw(%sched %schedule);
  10. # format: function name = (
  11. # str chanconfdefault,
  12. # int internaldefault,
  13. # bool deferred,
  14. # int next run, (optional)
  15. # )
  16. #%schedule = {
  17. # uptimeLoop => ('', 60, 1),
  18. #};
  19. sub setupSchedulersII {
  20. foreach (keys %schedule) {
  21. &queueTask($_, @{ $schedule{$_} });
  22. }
  23. }
  24. sub queueTask {
  25. my($codename, $chanconfdef, $intervaldef, $defer) = @_;
  26. my $t = &getChanConfDefault($chanconfdef, $intervaldef, $chan);
  27. my $waittime = &getRandomInt($t);
  28. if (!defined $waittime) {
  29. &WARN("interval == waittime == UNDEF for $codename.");
  30. return;
  31. }
  32. my $time = $schedule{$codename}[3];
  33. if (defined $time and $time > time()) {
  34. &WARN("Sched for $codename already exists in " . &Time2String(time() - $time) . ".");
  35. return;
  36. }
  37. #&VERB("Scheduling \&$codename() for " . &Time2String($waittime),3);
  38. my $retval = $conn->schedule($waittime, sub {
  39. \&$codename;
  40. }, @args );
  41. }
  42. sub setupSchedulers {
  43. &VERB( 'Starting schedulers...', 2 );
  44. # ONCE OFF.
  45. # REPETITIVE.
  46. # 2 for on next-run.
  47. &randomQuote(2);
  48. &randomFactoid(2);
  49. &seenFlush(2);
  50. &leakCheck(2); # mandatory
  51. &seenFlushOld(2);
  52. &miscCheck2(2); # mandatory
  53. &slashdotLoop(2);
  54. &plugLoop(2);
  55. &kernelLoop(2);
  56. &wingateWriteFile(2);
  57. &factoidCheck(2); # takes a couple of seconds on a 486. defer it
  58. # TODO: convert to new format... or nuke altogether.
  59. &newsFlush(2);
  60. &rssFeeds(2);
  61. # 1 for run straight away
  62. &uptimeLoop(1);
  63. &logLoop(1);
  64. &chanlimitCheck(1);
  65. &netsplitCheck(1); # mandatory
  66. &floodLoop(1); # mandatory
  67. &ignoreCheck(1); # mandatory
  68. &miscCheck(1); # mandatory
  69. &shmFlush(1); # mandatory
  70. sleep 1;
  71. &ircCheck(1); # mandatory
  72. # TODO: squeeze this into a one-liner.
  73. # my $count = map { exists $sched{$_}{TIME} } keys %sched;
  74. my $count = 0;
  75. foreach ( keys %sched ) {
  76. my $time = $sched{$_}{TIME};
  77. next unless ( defined $time and $time > time() );
  78. $count++;
  79. }
  80. &status("Schedulers: $count will be running.");
  81. &scheduleList();
  82. }
  83. sub ScheduleThis {
  84. my ( $interval, $codename, @args ) = @_;
  85. # Set to supllied value plus a random 0-60 seconds to avoid simultaneous runs
  86. my $waittime =
  87. &getRandomInt( "$interval-" . ( $interval + &getRandomInt(60) ) );
  88. if ( !defined $waittime ) {
  89. &WARN("interval == waittime == UNDEF for $codename.");
  90. return;
  91. }
  92. my $time = $sched{$codename}{TIME};
  93. if ( defined $time and $time > time() ) {
  94. &WARN( "Sched for $codename already exists in "
  95. . &Time2String( time() - $time )
  96. . '.' );
  97. return;
  98. }
  99. &DEBUG(
  100. "Scheduling \&$codename() "
  101. . \&$codename . ' for '
  102. . &Time2String($waittime),
  103. 3
  104. );
  105. my $retval = $conn->schedule( $waittime, \&$codename, @args );
  106. $sched{$codename}{LABEL} = $retval;
  107. $sched{$codename}{TIME} = time() + $waittime;
  108. $sched{$codename}{LOOP} = 1;
  109. }
  110. ####
  111. #### LET THE FUN BEGIN.
  112. ####
  113. sub rssFeeds {
  114. my $interval = $param{'rssFeedTime'} || 30;
  115. if (@_) {
  116. &ScheduleThis( $interval * 60, 'rssFeeds' ); # minutes
  117. return if ( $_[0] eq '2' ); # defer.
  118. }
  119. &Forker(
  120. 'RSSFeeds',
  121. sub {
  122. my $line = &RSSFeeds::RSS();
  123. return unless ( defined $line );
  124. }
  125. );
  126. }
  127. sub randomQuote {
  128. my $interval = &getChanConfDefault( 'randomQuoteInterval', 60, $chan );
  129. if (@_) {
  130. &ScheduleThis( $interval * 60, 'randomQuote' ); # every hour
  131. return if ( $_[0] eq '2' ); # defer.
  132. }
  133. foreach ( &ChanConfList('randomQuote') ) {
  134. next unless ( &validChan($_) );
  135. my $line =
  136. &getRandomLineFromFile( $bot_data_dir . '/infobot.randtext' );
  137. if ( !defined $line ) {
  138. &ERROR('random Quote: weird error?');
  139. return;
  140. }
  141. &status("sending random Quote to $_.");
  142. &action( $_, 'Ponders: ' . $line );
  143. }
  144. ### TODO: if there were no channels, don't reschedule until channel
  145. ### configuration is modified.
  146. }
  147. sub randomFactoid {
  148. my ( $key, $val );
  149. my $error = 0;
  150. my $interval = &getChanConfDefault( 'randomFactoidInterval', 60, $chan );
  151. if (@_) {
  152. &ScheduleThis( $interval * 60, 'randomFactoid' ); # minutes
  153. return if ( $_[0] eq '2' ); # defer.
  154. }
  155. foreach ( &ChanConfList('randomFactoid') ) {
  156. next unless ( &validChan($_) );
  157. &status("sending random Factoid to $_.");
  158. while (1) {
  159. ( $key, $val ) =
  160. &randKey( 'factoids', 'factoid_key,factoid_value' );
  161. &DEBUG("rF: $key, $val");
  162. ### $val =~ tr/^[A-Z]/[a-z]/; # blah is Good => blah is good.
  163. last
  164. if ( ( defined $val )
  165. and ( $val !~ /^</ )
  166. and ( $key !~ /\#DEL\#/ )
  167. and ( $key !~ /^cmd:/ ) );
  168. $error++;
  169. if ( $error == 5 ) {
  170. &ERROR('rF: tried 5 times but failed.');
  171. return;
  172. }
  173. }
  174. &action( $_, "Thinks: \037$key\037 is $val" );
  175. ### FIXME: Use &getReply() on above to format factoid properly?
  176. $good++;
  177. }
  178. }
  179. sub logLoop {
  180. if (@_) {
  181. &ScheduleThis( 3600, 'logLoop' ); # 1 hour
  182. return if ( $_[0] eq '2' ); # defer.
  183. }
  184. return unless ( defined fileno LOG );
  185. return unless ( &IsParam('logfile') );
  186. return unless ( &IsParam('maxLogSize') );
  187. ### check if current size is too large.
  188. if ( -s $file{log} > $param{'maxLogSize'} ) {
  189. my $date = sprintf( '%04d%02d%02d', (gmtime)[ 5, 4, 3 ] );
  190. $file{log} = $param{'logfile'} . '-' . $date;
  191. &status('cycling log file.');
  192. if ( -e $file{log} ) {
  193. my $i = 1;
  194. my $newlog;
  195. while () {
  196. $newlog = $file{log} . '-' . $i;
  197. last if ( !-e $newlog );
  198. $i++;
  199. }
  200. $file{log} = $newlog;
  201. }
  202. &closeLog();
  203. CORE::system("/bin/mv '$param{'logfile'}' '$file{log}'");
  204. &compress( $file{log} );
  205. &openLog();
  206. &status('cycling log file.');
  207. }
  208. ### check if all the logs exceed size.
  209. if ( !opendir( LOGS, $bot_log_dir ) ) {
  210. &WARN("logLoop: could not open dir '$bot_log_dir'");
  211. return;
  212. }
  213. my $tsize = 0;
  214. my ( %age, %size );
  215. while ( defined( $_ = readdir LOGS ) ) {
  216. my $logfile = "$bot_log_dir/$_";
  217. next unless ( -f $logfile );
  218. my $size = -s $logfile;
  219. my $age = ( stat $logfile )[9];
  220. $age{$age} = $logfile;
  221. $size{$logfile} = $size;
  222. $tsize += $size;
  223. }
  224. closedir LOGS;
  225. my $delete = 0;
  226. while ( $tsize > $param{'maxLogSize'} ) {
  227. &status("LOG: current size > max ($tsize > $param{'maxLogSize'})");
  228. my $oldest = ( sort { $a <=> $b } keys %age )[0];
  229. &status("LOG: unlinking $age{$oldest}.");
  230. unlink $age{$oldest};
  231. $tsize -= $oldest;
  232. $delete++;
  233. }
  234. ### TODO: add how many b,kb,mb removed?
  235. &status("LOG: removed $delete logs.") if ($delete);
  236. }
  237. sub seenFlushOld {
  238. if (@_) {
  239. &ScheduleThis( 86400, 'seenFlushOld' ); # 1 day
  240. return if ( $_[0] eq '2' ); # defer.
  241. }
  242. # is this global-only?
  243. return unless ( &IsChanConf('seen') > 0 );
  244. return unless ( &IsChanConf('seenFlushInterval') > 0 );
  245. # global setting. does not make sense for per-channel.
  246. my $max_time =
  247. &getChanConfDefault( 'seenMaxDays', 30, $chan ) * 60 * 60 * 24;
  248. my $delete = 0;
  249. if ( $param{'DBType'} =~ /^(pgsql|mysql|sqlite(2)?)$/i ) {
  250. my $query;
  251. if ( $param{'DBType'} =~ /^mysql$/i ) {
  252. $query =
  253. 'SELECT nick,time FROM seen GROUP BY nick HAVING '
  254. . "UNIX_TIMESTAMP() - time > $max_time";
  255. }
  256. elsif ( $param{'DBType'} =~ /^sqlite(2)?$/i ) {
  257. $query =
  258. 'SELECT nick,time FROM seen GROUP BY nick HAVING '
  259. . "strftime('%s','now','localtime') - time > $max_time";
  260. }
  261. else { # pgsql.
  262. $query =
  263. 'SELECT nick,time FROM seen WHERE '
  264. . "extract(epoch from timestamp 'now') - time > $max_time";
  265. }
  266. my $sth = $dbh->prepare($query);
  267. if ( $sth->execute ) {
  268. while ( my @row = $sth->fetchrow_array ) {
  269. my ( $nick, $time ) = @row;
  270. &sqlDelete( 'seen', { nick => $nick } );
  271. $delete++;
  272. }
  273. $sth->finish;
  274. }
  275. }
  276. else {
  277. &FIXME( 'seenFlushOld: for bad DBType:' . $param{'DBType'} . '.' );
  278. }
  279. &VERB( "SEEN deleted $delete seen entries.", 2 );
  280. }
  281. sub newsFlush {
  282. if (@_) {
  283. &ScheduleThis( 3600, 'newsFlush' ); # 1 hour
  284. return if ( $_[0] eq '2' ); # defer.
  285. }
  286. if ( !&ChanConfList('News') ) {
  287. &DEBUG("newsFlush: news disabled? (chan => $chan)");
  288. return;
  289. }
  290. my $delete = 0;
  291. my $oldest = time();
  292. my %none;
  293. foreach $chan ( keys %::news ) {
  294. my $i = 0;
  295. my $total = scalar( keys %{ $::news{$chan} } );
  296. if ( !$total ) {
  297. delete $::news{$chan};
  298. next;
  299. }
  300. foreach $item ( keys %{ $::news{$chan} } ) {
  301. my $t = $::news{$chan}{$item}{Expire};
  302. my $tadd = $::news{$chan}{$item}{Time};
  303. $oldest = $tadd if ( $oldest > $tadd );
  304. next if ( $t == 0 or $t == -1 );
  305. if ( $t < 1000 ) {
  306. &status(
  307. "newsFlush: Fixed Expire time for $chan/$item, should not happen anyway."
  308. );
  309. $::news{$chan}{$item}{Expire} = time() + $t * 60 * 60 * 24;
  310. next;
  311. }
  312. my $delta = $t - time();
  313. next unless ( time() > $t );
  314. # TODO: show how old it was.
  315. delete $::news{$chan}{$item};
  316. &status("NEWS: (newsflush) deleted '$item'");
  317. $delete++;
  318. $i++;
  319. }
  320. &status("NEWS (newsflush) {$chan}: deleted [$i/$total] news entries.")
  321. if ($i);
  322. $none{$chan} = 1 if ( $total == $i );
  323. }
  324. # TODO: flush users aswell.
  325. my $duser = 0;
  326. foreach $chan ( keys %::newsuser ) {
  327. next if ( exists $none{$chan} );
  328. foreach ( keys %{ $::newsuser{$chan} } ) {
  329. my $t = $::newsuser{$chan}{$_};
  330. if ( !defined $t or ( $t > 2 and $t < 1000 ) ) {
  331. &DEBUG("something wrong with newsuser{$chan}{$_} => $t");
  332. next;
  333. }
  334. next unless ( $oldest > $t );
  335. delete $::newsuser{$chan}{$_};
  336. $duser++;
  337. }
  338. my $i = scalar( keys %{ $::newsuser{$chan} } );
  339. delete $::newsuser{$chan} unless ($i);
  340. }
  341. if ( $delete or $duser ) {
  342. &status("NewsFlush: deleted: $delete news entries; $duser user cache.");
  343. }
  344. }
  345. sub chanlimitCheck {
  346. my $interval = &getChanConfDefault( 'chanlimitcheckInterval', 10, $chan );
  347. my $mynick = $conn->nick();
  348. if (@_) {
  349. &ScheduleThis( $interval * 60, 'chanlimitCheck' ); # default 10 minutes
  350. return if ( $_[0] eq '2' );
  351. }
  352. my $str = join( ' ', &ChanConfList('chanlimitcheck') );
  353. foreach $chan ( &ChanConfList('chanlimitcheck') ) {
  354. next unless ( &validChan($chan) );
  355. if ( $chan eq '_default' ) {
  356. &WARN("chanlimit: we're doing $chan!! HELP ME!");
  357. next;
  358. }
  359. my $limitplus = &getChanConfDefault( 'chanlimitcheckPlus', 5, $chan );
  360. my $newlimit = scalar( keys %{ $channels{$chan}{''} } ) + $limitplus;
  361. my $limit = $channels{$chan}{'l'};
  362. if ( scalar keys %netsplitservers ) {
  363. if ( defined $limit ) {
  364. &status("chanlimit: netsplit; removing it for $chan.");
  365. $conn->mode( $chan, '-l' );
  366. $cache{chanlimitChange}{$chan} = time();
  367. &status('chanlimit: netsplit; removed.');
  368. }
  369. next;
  370. }
  371. if ( defined $limit and scalar keys %{ $channels{$chan}{''} } > $limit )
  372. {
  373. &FIXME('LIMIT: set too low!!!');
  374. ### run NAMES again and flush it.
  375. }
  376. if ( defined $limit and $limit == $newlimit ) {
  377. $cache{chanlimitChange}{$chan} = time();
  378. next;
  379. }
  380. if ( !exists $channels{$chan}{'o'}{$mynick} ) {
  381. &status("chanlimit: dont have ops on $chan.")
  382. unless ( exists $cache{warn}{chanlimit}{$chan} );
  383. $cache{warn}{chanlimit}{$chan} = 1;
  384. &chanServCheck($chan);
  385. next;
  386. }
  387. delete $cache{warn}{chanlimit}{$chan};
  388. if ( !defined $limit ) {
  389. &status(
  390. "chanlimit: $chan: setting for first time or from netsplit.");
  391. }
  392. if ( exists $cache{chanlimitChange}{$chan} ) {
  393. my $delta = time() - $cache{chanlimitChange}{$chan};
  394. if ( $delta < $interval * 60 ) {
  395. &DEBUG(
  396. "chanlimit: not going to change chanlimit! ($delta<$interval*60)"
  397. );
  398. return;
  399. }
  400. }
  401. $conn->mode( $chan, '+l', $newlimit );
  402. $cache{chanlimitChange}{$chan} = time();
  403. }
  404. }
  405. sub netsplitCheck {
  406. my ( $s1, $s2 );
  407. if (@_) {
  408. &ScheduleThis( 300, 'netsplitCheck' ); # every 5 minutes
  409. return if ( $_[0] eq '2' );
  410. }
  411. $cache{'netsplitCache'}++;
  412. # &DEBUG("running netsplitCheck... $cache{netsplitCache}");
  413. if ( !scalar %netsplit and scalar %netsplitservers ) {
  414. &DEBUG('nsC: !hash netsplit but hash netsplitservers <- removing!');
  415. undef %netsplitservers;
  416. return;
  417. }
  418. # well... this shouldn't happen since %netsplit code does it anyway.
  419. foreach $s1 ( keys %netsplitservers ) {
  420. foreach $s2 ( keys %{ $netsplitservers{$s1} } ) {
  421. my $delta = time() - $netsplitservers{$s1}{$s2};
  422. if ( $delta > 60 * 30 ) {
  423. &status("netsplit between $s1 and $s2 appears to be stale.");
  424. delete $netsplitservers{$s1}{$s2};
  425. &chanlimitCheck();
  426. }
  427. }
  428. my $i = scalar( keys %{ $netsplitservers{$s1} } );
  429. delete $netsplitservers{$s1} unless ($i);
  430. }
  431. # %netsplit hash checker.
  432. my $count = scalar keys %netsplit;
  433. my $delete = 0;
  434. foreach ( keys %netsplit ) {
  435. if ( &IsNickInAnyChan($_) ) { # why would this happen?
  436. # &DEBUG("nsC: $_ is in some chan; removing from netsplit list.");
  437. delete $netsplit{$_};
  438. $delete++;
  439. next;
  440. }
  441. next unless ( time() - $netsplit{$_} > 60 * 15 );
  442. $delete++;
  443. delete $netsplit{$_};
  444. }
  445. # yet another hack.
  446. # FIXED: $ch should be used rather than $chan since it creates NULL channels in the hash
  447. foreach my $ch ( keys %channels ) {
  448. my $i = $cache{maxpeeps}{$ch} || 0;
  449. my $j = scalar( keys %{ $channels{$ch} } );
  450. next unless ( $i > 10 and 0.25 * $i > $j );
  451. &DEBUG("netsplit: 0.25*max($i) > current($j); possible netsplit?");
  452. }
  453. if ($delete) {
  454. my $j = scalar( keys %netsplit );
  455. &status("nsC: removed from netsplit list: (before: $count; after: $j)");
  456. }
  457. if ( !scalar %netsplit and scalar %netsplitservers ) {
  458. &DEBUG('nsC: ok hash netsplit is NULL; purging hash netsplitservers');
  459. undef %netsplitservers;
  460. }
  461. if ( $count and !scalar keys %netsplit ) {
  462. &DEBUG('nsC: netsplit is hopefully gone. reinstating chanlimit check.');
  463. &chanlimitCheck();
  464. }
  465. }
  466. sub floodLoop {
  467. my $delete = 0;
  468. my $who;
  469. if (@_) {
  470. &ScheduleThis( 60, 'floodLoop' ); # 1 minute
  471. return if ( $_[0] eq '2' );
  472. }
  473. my $time = time();
  474. my $interval = &getChanConfDefault( 'floodCycle', 60, $chan );
  475. foreach $who ( keys %flood ) {
  476. foreach ( keys %{ $flood{$who} } ) {
  477. if ( !exists $flood{$who}{$_} ) {
  478. &WARN("flood{$who}{$_} undefined?");
  479. next;
  480. }
  481. if ( $time - $flood{$who}{$_} > $interval ) {
  482. delete $flood{$who}{$_};
  483. $delete++;
  484. }
  485. }
  486. }
  487. &VERB( "floodLoop: deleted $delete items.", 2 );
  488. }
  489. sub seenFlush {
  490. if (@_) {
  491. my $interval = &getChanConfDefault( 'seenFlushInterval', 60, $chan );
  492. &ScheduleThis( $interval * 60, 'seenFlush' ); # minutes
  493. return if ( $_[0] eq '2' );
  494. }
  495. my %stats;
  496. my $nick;
  497. my $flushed = 0;
  498. $stats{'count_old'} = &countKeys('seen') || 0;
  499. $stats{'new'} = 0;
  500. $stats{'old'} = 0;
  501. if ( $param{'DBType'} =~ /^(mysql|pgsql|sqlite(2)?)$/i ) {
  502. foreach $nick ( keys %seencache ) {
  503. my $retval = &sqlSet(
  504. 'seen',
  505. { 'nick' => lc $seencache{$nick}{'nick'} },
  506. {
  507. time => $seencache{$nick}{'time'},
  508. host => $seencache{$nick}{'host'},
  509. channel => $seencache{$nick}{'chan'},
  510. message => $seencache{$nick}{'msg'},
  511. }
  512. );
  513. delete $seencache{$nick};
  514. $flushed++;
  515. }
  516. }
  517. else {
  518. &DEBUG('seenFlush: NO VALID FACTOID SUPPORT?');
  519. }
  520. &status("Seen: Flushed $flushed entries.") if ($flushed);
  521. &VERB(
  522. sprintf(
  523. ' new seen: %03.01f%% (%d/%d)',
  524. $stats{'new'} * 100 / ( $stats{'count_old'} || 1 ),
  525. $stats{'new'},
  526. ( $stats{'count_old'} || 1 )
  527. ),
  528. 2
  529. ) if ( $stats{'new'} );
  530. &VERB(
  531. sprintf(
  532. ' now seen: %3.1f%% (%d/%d)',
  533. $stats{'old'} * 100 / ( &countKeys('seen') || 1 ), $stats{'old'},
  534. &countKeys('seen')
  535. ),
  536. 2
  537. ) if ( $stats{'old'} );
  538. &WARN('scalar keys seenflush != 0!') if ( scalar keys %seenflush );
  539. }
  540. sub leakCheck {
  541. my ( $blah1, $blah2 );
  542. my $count = 0;
  543. if (@_) {
  544. &ScheduleThis( 14400, 'leakCheck' ); # every 4 hours
  545. return if ( $_[0] eq '2' );
  546. }
  547. # flood. this is dealt with in floodLoop()
  548. foreach $blah1 ( keys %flood ) {
  549. foreach $blah2 ( keys %{ $flood{$blah1} } ) {
  550. $count += scalar( keys %{ $flood{$blah1}{$blah2} } );
  551. }
  552. }
  553. &VERB( "leak: hash flood has $count total keys.", 2 );
  554. # floodjoin.
  555. $count = 0;
  556. foreach $blah1 ( keys %floodjoin ) {
  557. foreach $blah2 ( keys %{ $floodjoin{$blah1} } ) {
  558. $count += scalar( keys %{ $floodjoin{$blah1}{$blah2} } );
  559. }
  560. }
  561. &VERB( "leak: hash floodjoin has $count total keys.", 2 );
  562. # floodwarn.
  563. $count = scalar( keys %floodwarn );
  564. &VERB( "leak: hash floodwarn has $count total keys.", 2 );
  565. my $chan;
  566. foreach $chan ( grep /[A-Z]/, keys %channels ) {
  567. &DEBUG("leak: chan => '$chan'.");
  568. my ( $i, $j );
  569. foreach $i ( keys %{ $channels{$chan} } ) {
  570. foreach ( keys %{ $channels{$chan}{$i} } ) {
  571. &DEBUG("leak: \$channels{$chan}{$i}{$_} ...");
  572. }
  573. }
  574. }
  575. # chanstats
  576. $count = scalar( keys %chanstats );
  577. &VERB( "leak: hash chanstats has $count total keys.", 2 );
  578. # nuh.
  579. my $delete = 0;
  580. foreach ( keys %nuh ) {
  581. next if ( &IsNickInAnyChan($_) );
  582. next if ( exists $dcc{CHAT}{$_} );
  583. delete $nuh{$_};
  584. $delete++;
  585. }
  586. &status(
  587. "leak: $delete nuh{} items deleted; now have " . scalar( keys %nuh ) )
  588. if ($delete);
  589. }
  590. sub ignoreCheck {
  591. if (@_) {
  592. &ScheduleThis( 60, 'ignoreCheck' ); # once every minute
  593. return if ( $_[0] eq '2' ); # defer.
  594. }
  595. my $time = time();
  596. my $count = 0;
  597. foreach ( keys %ignore ) {
  598. my $chan = $_;
  599. foreach ( keys %{ $ignore{$chan} } ) {
  600. my @array = @{ $ignore{$chan}{$_} };
  601. next unless ( $array[0] and $time > $array[0] );
  602. delete $ignore{$chan}{$_};
  603. &status("ignore: $_/$chan has expired.");
  604. $count++;
  605. }
  606. }
  607. $cache{ignoreCheckTime} = time();
  608. &VERB( "ignore: $count items deleted.", 2 );
  609. }
  610. sub ircCheck {
  611. if (@_) {
  612. &ScheduleThis( 300, 'ircCheck' ); # every 5 minutes
  613. return if ( $_[0] eq '2' ); # defer.
  614. }
  615. $cache{statusSafe} = 1;
  616. foreach ( sort keys %conns ) {
  617. $conn = $conns{$_};
  618. my $mynick = $conn->nick();
  619. &DEBUG("ircCheck for $_");
  620. # Display with min of 900sec delay between redisplay
  621. # FIXME: should only use 900sec when we are on the LAST %conns
  622. my @join = &getJoinChans(900);
  623. if ( scalar @join ) {
  624. &FIXME( 'ircCheck: found channels to join! ' . join( ',', @join ) );
  625. &joinNextChan();
  626. }
  627. # TODO: fix on_disconnect()
  628. if ( time() - $msgtime > 3600 ) {
  629. # TODO: shouldn't we use cache{connect} somewhere?
  630. if ( exists $cache{connect} ) {
  631. &WARN("ircCheck: no msg for 3600 and disco'd! reconnecting!");
  632. $msgtime = time(); # just in case.
  633. &ircloop();
  634. delete $cache{connect};
  635. }
  636. else {
  637. &status( 'ircCheck: possible lost in space; checking.'
  638. . scalar(gmtime) );
  639. &msg( $mynick, 'TEST' );
  640. $cache{connect} = time();
  641. }
  642. }
  643. }
  644. if ( grep /^\s*$/, keys %channels ) {
  645. &WARN('ircCheck: we have a NULL chan in hash channels? removing!');
  646. if ( !exists $channels{''} ) {
  647. &DEBUG('ircCheck: this should never happen!');
  648. }
  649. }
  650. if ( $ident !~ /^\Q$param{ircNick}\E$/ ) {
  651. # this does not work unfortunately.
  652. &WARN("ircCheck: ident($ident) != param{ircNick}($param{ircNick}).");
  653. # this check is misleading... perhaps we should do a notify.
  654. if ( !&IsNickInAnyChan( $param{ircNick} ) ) {
  655. &DEBUG("$param{ircNick} not in use... changing!");
  656. &nick( $param{ircNick} );
  657. }
  658. else {
  659. &WARN("$param{ircNick} is still in use...");
  660. }
  661. }
  662. $cache{statusSafe} = 0;
  663. ### USER FILE.
  664. if ( $utime_userfile > $wtime_userfile and time() - $wtime_userfile > 3600 )
  665. {
  666. &writeUserFile();
  667. $wtime_userfile = time();
  668. }
  669. ### CHAN FILE.
  670. if ( $utime_chanfile > $wtime_chanfile and time() - $wtime_chanfile > 3600 )
  671. {
  672. &writeChanFile();
  673. $wtime_chanfile = time();
  674. }
  675. }
  676. sub miscCheck {
  677. if (@_) {
  678. &ScheduleThis( 7200, 'miscCheck' ); # every 2 hours
  679. return if ( $_[0] eq '2' ); # defer.
  680. }
  681. # SHM check.
  682. my @ipcs;
  683. if ( -x '/usr/bin/ipcs' ) {
  684. @ipcs = `/usr/bin/ipcs`;
  685. }
  686. else {
  687. &WARN("ircCheck: no 'ipcs' binary.");
  688. return;
  689. }
  690. # make backup of important files.
  691. &mkBackup( $bot_state_dir . '/infobot.chan', 60 * 60 * 24 * 3 );
  692. &mkBackup( $bot_state_dir . '/infobot.users', 60 * 60 * 24 * 3 );
  693. &mkBackup( $bot_base_dir . '/infobot-news.txt', 60 * 60 * 24 * 1 );
  694. # flush cache{lobotomy}
  695. foreach ( keys %{ $cache{lobotomy} } ) {
  696. next unless ( time() - $cache{lobotomy}{$_} > 60 * 60 );
  697. delete $cache{lobotomy}{$_};
  698. }
  699. ### check modules if they've been modified. might be evil.
  700. &reloadAllModules();
  701. # shmid stale remove.
  702. foreach (@ipcs) {
  703. chop;
  704. # key, shmid, owner, perms, bytes, nattch
  705. next unless (/^(0x\d+) (\d+)\s+(\S+)\s+(\d+)\s+(\d+)\s+/);
  706. my ( $shmid, $size ) = ( $2, $5 );
  707. next unless ( $shmid != $shm and $size == 2000 );
  708. my $z = &shmRead($shmid);
  709. if ( $z =~ /^(\S+):(\d+):(\d+): / ) {
  710. my $n = $1;
  711. my $pid = $2;
  712. my $time = $3;
  713. next if ( time() - $time < 60 * 60 );
  714. # FIXME remove not-pid shm if parent process dead
  715. next if ( $pid == $bot_pid );
  716. # don't touch other bots, if they're running.
  717. next unless ( $param{ircUser} =~ /^\Q$n\E$/ );
  718. }
  719. else {
  720. &DEBUG("shm: $shmid is not ours or old infobot => ($z)");
  721. next;
  722. }
  723. &status("SHM: nuking shmid $shmid");
  724. CORE::system("/usr/bin/ipcrm shm $shmid >/dev/null");
  725. }
  726. }
  727. sub miscCheck2 {
  728. if (@_) {
  729. &ScheduleThis( 14400, 'miscCheck2' ); # every 4 hours
  730. return if ( $_[0] eq '2' ); # defer.
  731. }
  732. # debian check.
  733. opendir( DEBIAN, "$bot_state_dir/debian" );
  734. foreach ( grep /gz$/, readdir(DEBIAN) ) {
  735. my $exit = CORE::system("gzip -t $bot_state_dir/debian/$_");
  736. next unless ($exit);
  737. &status("debian: unlinking file => $_");
  738. unlink "$bot_state_dir/debian/$_";
  739. }
  740. closedir DEBIAN;
  741. # compress logs that should have been compressed.
  742. # TODO: use strftime?
  743. my ( $day, $month, $year ) = ( gmtime( time() ) )[ 3, 4, 5 ];
  744. my $date = sprintf( '%04d%02d%02d', $year + 1900, $month + 1, $day );
  745. if ( !opendir( DIR, "$bot_log_dir" ) ) {
  746. &ERROR("misccheck2: log dir $bot_log_dir does not exist.");
  747. closedir DIR;
  748. return -1;
  749. }
  750. while ( my $f = readdir(DIR) ) {
  751. next unless ( -f "$bot_log_dir/$f" );
  752. next if ( $f =~ /gz|bz2/ );
  753. next unless ( $f =~ /(\d{8})/ );
  754. next if ( $date eq $1 );
  755. &compress("$bot_log_dir/$f");
  756. }
  757. closedir DIR;
  758. }
  759. ### this is semi-scheduled
  760. sub getNickInUse {
  761. # FIXME: broken for multiple connects
  762. # if ($ident eq $param{'ircNick'}) {
  763. # &status('okay, got my nick back.');
  764. # return;
  765. # }
  766. #
  767. # if (@_) {
  768. # &ScheduleThis(30, 'getNickInUse');
  769. # return if ($_[0] eq '2'); # defer.
  770. # }
  771. #
  772. # &nick( $param{'ircNick'} );
  773. }
  774. sub uptimeLoop {
  775. return if ( !defined &uptimeWriteFile );
  776. # return unless &IsParam('Uptime');
  777. if (@_) {
  778. &ScheduleThis( 3600, 'uptimeLoop' ); # once per hour
  779. return if ( $_[0] eq '2' ); # defer.
  780. }
  781. &uptimeWriteFile();
  782. }
  783. sub slashdotLoop {
  784. if (@_) {
  785. &ScheduleThis( 3600, 'slashdotLoop' ); # once per hour
  786. return if ( $_[0] eq '2' );
  787. }
  788. my @chans = &ChanConfList('slashdotAnnounce');
  789. return unless ( scalar @chans );
  790. &Forker(
  791. 'slashdot',
  792. sub {
  793. my $line = &Slashdot::slashdotAnnounce();
  794. return unless ( defined $line );
  795. foreach (@chans) {
  796. next unless ( &::validChan($_) );
  797. &::status("sending slashdot update to $_.");
  798. &notice( $_, "Slashdot: $line" );
  799. }
  800. }
  801. );
  802. }
  803. sub plugLoop {
  804. if (@_) {
  805. &ScheduleThis( 3600, 'plugLoop' ); # once per hour
  806. return if ( $_[0] eq '2' );
  807. }
  808. my @chans = &ChanConfList('plugAnnounce');
  809. return unless ( scalar @chans );
  810. &Forker(
  811. 'Plug',
  812. sub {
  813. my $line = &Plug::plugAnnounce();
  814. return unless ( defined $line );
  815. foreach (@chans) {
  816. next unless ( &::validChan($_) );
  817. &::status("sending plug update to $_.");
  818. &notice( $_, "Plug: $line" );
  819. }
  820. }
  821. );
  822. }
  823. sub kernelLoop {
  824. if (@_) {
  825. &ScheduleThis( 14400, 'kernelLoop' ); # once every 4 hours
  826. return if ( $_[0] eq '2' );
  827. }
  828. my @chans = &ChanConfList('kernelAnnounce');
  829. return unless ( scalar @chans );
  830. &Forker(
  831. 'Kernel',
  832. sub {
  833. my @data = &Kernel::kernelAnnounce();
  834. foreach (@chans) {
  835. next unless ( &::validChan($_) );
  836. &::status("sending kernel update to $_.");
  837. my $c = $_;
  838. foreach (@data) {
  839. &notice( $c, "Kernel: $_" );
  840. }
  841. }
  842. }
  843. );
  844. }
  845. sub wingateCheck {
  846. return unless &IsChanConf('Wingate') > 0;
  847. ### FILE CACHE OF OFFENDING WINGATES.
  848. foreach ( grep /^$host$/, @wingateBad ) {
  849. &status("Wingate: RUNNING ON $host BY $who");
  850. &ban( "*!*\@$host", '' ) if &IsChanConf('wingateBan') > 0;
  851. my $reason = &getChanConf('wingateKick');
  852. next unless ($reason);
  853. &kick( $who, '', $reason );
  854. }
  855. ### RUN CACHE OF TRIED WINGATES.
  856. if ( grep /^$host$/, @wingateCache ) {
  857. push( @wingateNow, $host ); # per run.
  858. push( @wingateCache, $host ); # cache per run.
  859. }
  860. else {
  861. &DEBUG("Already scanned $host. good.");
  862. }
  863. my $interval =
  864. &getChanConfDefault( 'wingateInterval', 60, $chan ); # seconds.
  865. return if ( defined $forked{'Wingate'} );
  866. return if ( time() - $wingaterun <= $interval );
  867. return unless ( scalar( keys %wingateToDo ) );
  868. $wingaterun = time();
  869. &Forker( 'Wingate', sub { &Wingate::Wingates( keys %wingateToDo ); } );
  870. undef @wingateNow;
  871. }
  872. ### TODO: ??
  873. sub wingateWriteFile {
  874. if (@_) {
  875. &ScheduleThis( 3600, 'wingateWriteFile' ); # once per hour
  876. return if ( $_[0] eq '2' ); # defer.
  877. }
  878. return unless ( scalar @wingateCache );
  879. my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
  880. if ( $bot_pid != $$ ) {
  881. &DEBUG('wingateWriteFile: Reorganising!');
  882. open( IN, $file );
  883. while (<IN>) {
  884. chop;
  885. push( @wingateNow, $_ );
  886. }
  887. close IN;
  888. # very lame hack.
  889. my %hash = map { $_ => 1 } @wingateNow;
  890. @wingateNow = sort keys %hash;
  891. }
  892. &DEBUG('wingateWF: writing...');
  893. open( OUT, ">$file" );
  894. foreach (@wingateNow) {
  895. print OUT "$_\n";
  896. }
  897. close OUT;
  898. }
  899. sub factoidCheck {
  900. if (@_) {
  901. &ScheduleThis( 43200, 'factoidCheck' ); # ever 12 hours
  902. return if ( $_[0] eq '2' ); # defer.
  903. }
  904. my @list =
  905. &searchTable( 'factoids', 'factoid_key', 'factoid_key', ' #DEL#' );
  906. my $stale =
  907. &getChanConfDefault( 'factoidDeleteDelay', 14, $chan ) * 60 * 60 * 24;
  908. if ( $stale < 1 ) {
  909. # disable it since it's 'illegal'.
  910. return;
  911. }
  912. my $time = time();
  913. foreach (@list) {
  914. my $age = &getFactInfo( $_, 'modified_time' );
  915. if ( !defined $age or $age !~ /^\d+$/ ) {
  916. if ( scalar @list > 50 ) {
  917. if ( !$cache{warnDel} ) {
  918. &WARN( 'list is over 50 ('
  919. . scalar(@list)
  920. . '... giving it a miss.' );
  921. $cache{warnDel} = 1;
  922. last;
  923. }
  924. }
  925. &WARN("del factoid: old cruft (no time): $_");
  926. &delFactoid($_);
  927. next;
  928. }
  929. next unless ( $time - $age > $stale );
  930. my $fix = $_;
  931. $fix =~ s/ #DEL#$//g;
  932. my $agestr = &Time2String( $time - $age );
  933. &status("safedel: Removing '$_' for good. [$agestr old]");
  934. &delFactoid($_);
  935. }
  936. }
  937. sub dccStatus {
  938. return unless ( scalar keys %{ $dcc{CHAT} } );
  939. if (@_) {
  940. &ScheduleThis( 600, 'dccStatus' ); # every 10 minutes
  941. return if ( $_[0] eq '2' ); # defer.
  942. }
  943. my $time = strftime( '%H:%M', gmtime( time() ) );
  944. my $c;
  945. foreach ( keys %channels ) {
  946. my $c = $_;
  947. my $users = keys %{ $channels{$c}{''} };
  948. my $chops = keys %{ $channels{$c}{o} };
  949. my $bans = keys %{ $channels{$c}{b} };
  950. my $txt = "[$time] $c: $users members ($chops chops), $bans bans";
  951. foreach ( keys %{ $dcc{'CHAT'} } ) {
  952. next unless ( exists $channels{$c}{''}{ lc $_ } );
  953. $conn->privmsg( $dcc{'CHAT'}{$_}, $txt );
  954. }
  955. }
  956. }
  957. sub scheduleList {
  958. ###
  959. # custom:
  960. # a - time == now.
  961. # b - weird time.
  962. ###
  963. my $reply = 'sched:';
  964. foreach ( keys %{ $irc->{_queue} } ) {
  965. my $q = $_;
  966. my $coderef = $irc->{_queue}->{$q}->[1];
  967. my $sched;
  968. foreach ( keys %sched ) {
  969. my $schedname = $_;
  970. next unless defined( \&$schedname );
  971. next unless ( $coderef eq \&$schedname );
  972. $sched = $schedname;
  973. last;
  974. }
  975. my $time = $irc->{_queue}->{$q}->[0] - time();
  976. if ( defined $sched ) {
  977. $reply = "$reply, $sched($q):" . &Time2String($time);
  978. }
  979. else {
  980. $reply = "$reply, NULL($q):" . &Time2String($time);
  981. }
  982. }
  983. &DEBUG("$reply");
  984. }
  985. sub mkBackup {
  986. my ( $file, $time ) = @_;
  987. my $backup = 0;
  988. if ( !-f $file ) {
  989. &VERB( "mkB: file '$file' does not exist.", 2 );
  990. return;
  991. }
  992. my $age = 'New';
  993. if ( -e "$file~" ) {
  994. $backup++ if ( ( stat $file )[9] - ( stat "$file~" )[9] > $time );
  995. my $delta = time() - ( stat "$file~" )[9];
  996. $age = &Time2String($delta);
  997. }
  998. else {
  999. $backup++;
  1000. }
  1001. return unless ($backup);
  1002. ### TODO: do internal copying.
  1003. &status("Backup: $file ($age)");
  1004. CORE::system("/bin/cp $file $file~");
  1005. }
  1006. 1;
  1007. # vim:ts=4:sw=4:expandtab:tw=80