OMatic/maintenance.pm untested

filter: Statementstmt 0.0% 0 / 556 Branchbran 0.0% 0 / 184 Conditioncond 0.0% 0 / 163 MC/DCmcdc 0.0% 0 / 89 Subroutinesub 0.0% 0 / 45 Podpod 0.0% 0 / 32 totaltotal 0.0% 0 / 1069 CC 93 SCAR 42.7
CC
93
Cov
0%
mirrorClient
272.0
periodicTasks
156.0
fsck
110.0
CRAP 71.3
1 ##############################################################################
2 # The Faq-O-Matic is Copyright 1997 by Jon Howell, all rights reserved. #
3 # #
4 # This program is free software; you can redistribute it and/or #
5 # modify it under the terms of the GNU General Public License #
6 # as published by the Free Software Foundation; either version 2 #
7 # of the License, or (at your option) any later version. #
8 # #
9 # This program is distributed in the hope that it will be useful, #
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
12 # GNU General Public License for more details. #
13 # #
14 # You should have received a copy of the GNU General Public License #
15 # along with this program; if not, write to the Free Software #
16 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.#
17 # #
18 # Jon Howell can be contacted at: #
19 # 6211 Sudikoff Lab, Dartmouth College #
20 # Hanover, NH 03755-3510 #
21 # jonh@cs.dartmouth.edu #
22 # #
23 # An electronic copy of the GPL is available at: #
24 # http://www.gnu.org/copyleft/gpl.html #
25 # #
26 ##############################################################################
27  
28 use strict;
29  
30 ##
31 ## maintenance.pm
32 ##
33 ## This module should be invoked periodically by cron.
34 ## It can be given an argument to run a specific task, or it will
35 ## automatically determine which tasks to run.
36 ##
37 ## FAQ::OMatic::maintenance::main() (via the dispatch.pm CGI mechanism) will
38 ## make this script do its thing.
39 ##
40 ## FAQ::OMatic::maintenance::invoke(host, port, url) will request the url from the host.
41 ## Cron scripts should invoke me that way, which will cause the above
42 ## invocation (and make maintenance do its thing).
43  
44 package FAQ::OMatic::maintenance;
45  
46 use CGI;
47 use Socket;
48  
49 use FAQ::OMatic;
50 use FAQ::OMatic::Log;
51 use FAQ::OMatic::Auth;
52 use FAQ::OMatic::buildSearchDB;
53 use FAQ::OMatic::Versions;
54 use FAQ::OMatic::ImageRef;
55 use FAQ::OMatic::Slow;
56 use FAQ::OMatic::I18N;
57  
58 my $badKeyMessage = 'Bad maintenance key.';
59  
60 sub main {
61 my $cgi = FAQ::OMatic::dispatch::cgi();
62  
63 ## Demand a secret key from the caller, so that we don't have
64 ## Joe Q. Random firing up umpteen copies of the mainenance script
65 ## and slowing things down. With the hints that keep it from doing
66 ## much very often, this probably doesn't matter, but anyway.
67 if ($cgi->param('secret') ne $FAQ::OMatic::Config::maintenanceSecret) {
68 print FAQ::OMatic::header($cgi, '-type'=>"text/plain");
69 print "$badKeyMessage\n";
70 return;
71 }
72  
73 my $slow = '';
74 my $tasks = $cgi->param('tasks') || '';
75 # if ($tasks ne 'mirrorClient'
76 # and $tasks ne 'rebuildCache') {
77 # # (don't force out the header for Slow processes, which need
78 # # to be able to redirect.)
79 # hprint(FAQ::OMatic::header($cgi, '-type'=>'text/html'));
80 # hprint("<title>FAQ-O-Matic Maintenance</title>\n");
81 # hflush();
82 # # just in case some other junk sneaks out on the fd
83 # } else {
84 # $slow = '-slow'; # tell task to run interactively
85 # }
86  
87 # do everything in "slow" mode -- fork a process (so the web
88 # server won't kill it), and redirect all output to a Slow file.
89 my $fh = FAQ::OMatic::Slow::split();
90 hSetFilehandle($fh);
91 hprint("This is process ID ".$$."<p>\n");
92 hflush();
93  
94 my %schedules = ('month'=>1,'week'=>1,'day'=>1,'hour'=>1);
95 my @tasks = split(',', ($cgi->param('tasks')||''));
96 if ((@tasks == 0) or ((@tasks == 1) and $schedules{$tasks[0]})) {
97 @tasks = periodicTasks($tasks[0] || '');
98 }
99  
100 my %taskUntaint = map {$_=>$_}
101 ( 'writeMaintenanceHint', 'trimUHDB', 'trimSubmitTmps',
102 'buildSearchDB', 'trim', 'cookies', 'errors', 'logSummary',
103 'rebuildAllSummaries', 'rebuildCache', 'expireBags', 'bagAllImages',
104 'mirrorClient', 'trimSlowOutput', 'emptyTrash', 'fsck');
105  
106 #hprint("<pre>\n");
107 foreach my $i (sort @tasks) {
108 $i =~ s/\d+ //;
109 if (defined $taskUntaint{$i}) {
110 $i = $taskUntaint{$i};
111 hprint("--- $i\n");
112 hflush();
113 if (not eval "$i(); return 1;") {
114 FAQ::OMatic::gripe('problem',
115 "*** Task $i failed\n Error: $@\n");
116 hprint("*** Task $i failed\n Error: $@\n");
117 hprint(FAQ::OMatic::stackTrace('html'));
118 hflush();
119 }
120 hflush();
121 } else {
122 hprint("*** Task $i undefined\n");
123 hflush();
124 }
125 }
126  
127 # output results
128 hprint("\n</pre>\n");
129  
130 # provide a link to the install page, just for kicks
131 FAQ::OMatic::getParams($cgi);
132 hprint(FAQ::OMatic::button(
133 FAQ::OMatic::makeAref('install', {}, ''),
134 gettext("Go To Install/Configuration Page")));
135  
136 hflush();
137 }
138  
139 sub hSetFilehandle {
140 my $filehandle = shift;
141 FAQ::OMatic::setLocal('maintenance-fh', $filehandle);
142 }
143  
144 sub hprint {
145 # I have no idea why I thought this should be a separate
146 # function. I think because I wanted to have the output appear
147 # as it was generated, but didn't want to have 'print' calls to
148 # weed out if I ever changed how I did printing.
149 my $html = FAQ::OMatic::getLocal('maintenance-html') || '';
150 $html .= join('', @_);
151 FAQ::OMatic::setLocal('maintenance-html', $html);
152 # we don't flush until explicitly asked to. That way, if a routine
153 # decides to Slow::split, it can get its redirect out before we
154 # send out a header.
155 }
156  
157 sub hflush {
158 my $html = FAQ::OMatic::getLocal('maintenance-html') || '';
159 my $filehandle = FAQ::OMatic::getLocal('maintenance-fh') || \*STDOUT;
160 print $filehandle $html;
161 FAQ::OMatic::flush($filehandle);
162 FAQ::OMatic::setLocal('maintenance-html', '');
163 }
164  
165 sub periodicTasks {
166 my $arg = shift || '';
167 my $lastMaintenance = readMaintenanceHint();
168  
169 my @thenTime = localtime($lastMaintenance);
170 my @nowTime = localtime($^T);
171  
172 my $newYear = ($thenTime[5] != $nowTime[5])?1:0;
173 my $newMonth = (!defined($thenTime[4])
174 or !defined($nowTime[4])
175 or ($thenTime[4] != $nowTime[4])
176 or $newYear
177 or ($arg eq 'month'))
178 ?1:0;
179  
180 # a tricky case:
181 my $newWeek = (($thenTime[6] > $nowTime[6])
182 # it's now "earlier" in the week than then
183 or ($lastMaintenance<($^T-(86400*7)))
184 or ($arg eq 'week')) ? 1 : 0;
185 # or it's at least a week later
186  
187 my $newDay = (($thenTime[3] != $nowTime[3]) or $newMonth
188 or ($arg eq 'day'))?1:0;
189 my $newHour = (($thenTime[2] != $nowTime[2]) or $newDay
190 or ($arg eq 'hour'))?1:0;
191  
192 my @tasks = ();
193  
194 # The number in front of the task is the sort order
195 push @tasks, (
196 '10 buildSearchDB'
197 ) if $newHour;
198 push @tasks, (
199 '40 mirrorClient', # if we're a mirror, this will do an update.
200 '50 cookies',
201 '60 logSummary',
202 '80 trimUHDB', # turns on a flag so trim() will trim uhdbs
203 '81 trimSubmitTmps',# turns on a flag so trim() will trim submitTmps
204 '82 trimSlowOutput',# turns on a flag so trim() will trim slow-outputs
205 '89 trim', # traverse metadir (needed for trim() to do anything)
206 '90 fsck',
207 '91 emptyTrash'
208 ) if $newDay;
209 push @tasks, (
210 '55 errors'
211 ) if $newWeek;
212 push @tasks, '98 writeMaintenanceHint';
213  
214 hprint('Executing schedules:'
215 .($newHour ? ' Hourly' :'')
216 .($newDay ? ' Daily' :'')
217 .($newWeek ? ' Weekly' :'')
218 ."\n\n");
219  
220 my %tasks = map { ($_,1) } @tasks;
221 return keys %tasks;
222 }
223  
224 # sub runScript {
225 # my $script = shift;
226 # $html.= " Executing $script...\n";
227 # if (system("$script")) {
228 # $html.= " ...failed because $!\n";
229 # }
230 # }
231  
232 sub readMaintenanceHint {
233 my $lastMaintenance;
234 if (open LMHINT, "$FAQ::OMatic::Config::metaDir/lastMaintenance") {
235 <LMHINT> =~ m/^(\d+)/;
236 $lastMaintenance = defined($1) ? int($1) : 0;
237 # THANKS Michael Gerdts <gerdts@cae.wisc.edu> for the defined() test
238 close LMHINT;
239 } else {
240 $lastMaintenance = 0;
241 }
242 return $lastMaintenance;
243 }
244  
245 ############################################################################
246 ######## Task definitions ################################################
247 ############################################################################
248  
249 sub writeMaintenanceHint {
250 if (open LMHINT, ">$FAQ::OMatic::Config::metaDir/lastMaintenance") {
251 print LMHINT $^T." ".scalar localtime($^T)."\n";
252 close LMHINT;
253 }
254 FAQ::OMatic::Versions::setVersion('MaintenanceInvoked');
255 }
256  
257 sub trimUHDB {
258 my $trimset = FAQ::OMatic::getLocal('trimset') || {};
259 $trimset->{'uhdb'} = 1;
260 FAQ::OMatic::setLocal('trimset', $trimset);
261 }
262  
263 sub trimSubmitTmps {
264 my $trimset = FAQ::OMatic::getLocal('trimset') || {};
265 $trimset->{'submitTmp'} = 1;
266 FAQ::OMatic::setLocal('trimset', $trimset);
267 }
268  
269 sub trimSlowOutput {
270 my $trimset = FAQ::OMatic::getLocal('trimset') || {};
271 $trimset->{'slow'} = 1;
272 FAQ::OMatic::setLocal('trimset', $trimset);
273 }
274  
275 sub buildSearchDB {
276 my $cgi = FAQ::OMatic::dispatch::cgi();
277 my $force = $cgi->param('force') || '';
278 # FORCE feature requested by
279 # "Dameon D. Welch-Abernathy" <dwelch@phoneboy.com>
280 if ($force
281 or (not -f "$FAQ::OMatic::Config::metaDir/freshSearchDBHint")
282 or (-M "$FAQ::OMatic::Config::metaDir/freshSearchDBHint" > 1/24)) {
283 FAQ::OMatic::buildSearchDB::build();
284 } else {
285 hprint(" (not needed)\n");
286 }
287 }
288  
289 sub rebuildAllSummaries {
290 FAQ::OMatic::Log::rebuildAllSummaries();
291 }
292  
293 sub trim {
294 if (not opendir NEWLOGDIR, $FAQ::OMatic::Config::metaDir) {
295 hprint("*** Couldn't scan $FAQ::OMatic::Config::metaDir.");
296 return;
297 }
298  
299 my $trimset = FAQ::OMatic::getLocal('trimset') || {};
300 hprint("trimming: ".join(' ', sort keys %{$trimset})."\n");
301  
302 my $daybefore = FAQ::OMatic::Log::adddays(FAQ::OMatic::Log::numericToday(), -2);
303 while (defined(my $file = readdir(NEWLOGDIR))) {
304 # untaint file -- we should be able to trust the operating system
305 # to provide only reasonable filenames from a readdir().
306 $file =~ m/^(.*)$/;
307 $file = $1;
308  
309 # uhdb's (unique host databases, part of the access log)
310 if ($trimset->{'uhdb'} and ($file =~ m/^[\d-]+.uhdb./)) {
311 my @dates = ($file =~ m/^([\d-]+)/);
312 my $date = $dates[0];
313  
314 # Delete all uhdb files before yesterday to save
315 # space. we save the day-before's log, since
316 # we need it if we summarize yesterday's log (which
317 # is another task on the maintenance agenda).
318 # (uhdb = Unique Host Database files. Since no
319 # "new" unique hosts will be joining logs from the
320 # past, having the files around doesn't help
321 # anymore.)
322 # Notice we do these tests based on the name of the
323 # file, not the mod date, since it could have been
324 # generated today by a regenerateSmrys.
325 if ($date lt $daybefore) {
326 hprint("removing $file\n");
327 unlink "$FAQ::OMatic::Config::metaDir/$file";
328 }
329 }
330  
331 # submitTmp
332 if ($trimset->{'submitTmp'} and ($file =~ m/^submitTmp\./)) {
333 # only trim files older than a day
334 if (-M "$FAQ::OMatic::Config::metaDir/$file" > 1.0) {
335 hprint("removing $file\n");
336 unlink "$FAQ::OMatic::Config::metaDir/$file";
337 }
338 }
339  
340 # slow
341 if ($trimset->{'slow'} and ($file =~ m/^slow-output\./)) {
342 # only trim files older than a day
343 if (-M "$FAQ::OMatic::Config::metaDir/$file" > 1.0) {
344 hprint("removing $file\n");
345 unlink "$FAQ::OMatic::Config::metaDir/$file";
346 }
347 }
348 }
349 close NEWLOGDIR;
350 }
351  
352 sub cookies {
353 # throw away old cookies
354 if (not open COOKIES, "$FAQ::OMatic::Config::metaDir/cookies") {
355 hprint("no cookie file.\n");
356 return;
357 }
358 my $cookiesNewFile = "$FAQ::OMatic::Config::metaDir/cookies.new";
359 if (not open NEWCOOKIES, ">$cookiesNewFile") {
360 hprint("can't create $FAQ::OMatic::Config::metaDir/cookies.new.\n");
361 return;
362 }
363 while (defined($_=<COOKIES>)) {
364 my ($cookie,$id,$time) = split(' ');
365 if ($time
366 +($FAQ::OMatic::Config::cookieLife||3600)
367 +$FAQ::OMatic::Auth::cookieExtra
368 > $^T) {
369 # TODO: that 3600 default should be encoded somewhere,
370 # rather than being a magic number. It also appears in Auth.pm.
371 print NEWCOOKIES $_;
372 }
373 }
374 close COOKIES;
375 close NEWCOOKIES;
376 if (not chmod(0600, "$cookiesNewFile")) {
377 FAQ::OMatic::gripe('problem', "chmod failed on $cookiesNewFile");
378 }
379 unlink "$FAQ::OMatic::Config::metaDir/cookies";
380 if (not rename("$FAQ::OMatic::Config::metaDir/cookies.new","$FAQ::OMatic::Config::metaDir/cookies")) {
381 hprint ("Couldn't rename $FAQ::OMatic::Config::metaDir/cookies.new "
382 ."to $FAQ::OMatic::Config::metaDir/cookies\n"
383 ."because $!\n");
384 }
385 }
386  
387 sub errors {
388 if (not $FAQ::OMatic::Config::maintSendErrors) {
389 hprint(" Config says don't mail errors.\n");
390 return;
391 }
392  
393 my $size = (-s "$FAQ::OMatic::Config::metaDir/errors") || 0;
394 if ($size == 0) {
395 hprint(" No ($size) errors to mail.\n");
396 return;
397 }
398  
399 my $msg = "Errors from ".FAQ::OMatic::fomTitle()
400 ." (v. $FAQ::OMatic::VERSION):\n\n";
401 if (not open(ERRORS, "$FAQ::OMatic::Config::metaDir/errors")) {
402 hprint(" Couldn't read $FAQ::OMatic::Config::metaDir/errors "
403 ."because $!; not truncating\n");
404 } else {
405 hprint(" Sending errors...\n");
406 my @errs = <ERRORS>;
407 close ERRORS;
408 FAQ::OMatic::sendEmail($FAQ::OMatic::Config::adminEmail,
409 "Faq-O-Matic Error Log",
410 $msg.join('', @errs));
411  
412 # truncate errorfile
413 open ERRORS, ">$FAQ::OMatic::Config::metaDir/errors";
414 close ERRORS;
415 }
416 }
417  
418 sub logSummary {
419 my $yesterday = FAQ::OMatic::Log::adddays(FAQ::OMatic::Log::numericToday(), -1);
420  
421 FAQ::OMatic::Log::summarizeDay($yesterday);
422 }
423  
424 sub cronInvoke {
425 # special version to be called from cron to alert user to errors
426 my @reply = invoke(@_);
427 my $reply = join('', @reply);
428  
429 # if the cron job fails to run, we should print a message out,
430 # so that the user knows to fix it. (most crons mail the message
431 # to the user.)
432 my ($proto,$code,@rest) = split(' ', $reply[0]);
433  
434 # THANKS to Andrew W. Nosenko <awn@bcs.zp.ua>
435 # for this patch to ignore 'Moved Temporarily' response.
436 # TODO: I'm not sure 302 guarantees that it actually worked,
437 # but it's something. Why do we return the 'slow' URL to cron?
438 # That seems buggy.
439 if ($code != '200' && $code != '302') {
440 print "Unable to invoke maintenance task; HTTP reply follows:\n\n";
441 print $reply;
442 }
443 if ($reply =~ m/$badKeyMessage/) {
444 print "$badKeyMessage\n";
445 print "Admin must access the install page and\n"
446 ."click \"Set up the maintenance cron job.\"\n";
447 }
448 }
449  
450 sub invoke {
451 my $host = shift;
452 my $port = shift;
453 my $url = shift;
454 my $verbose = shift;
455  
456 my $proto = getprotobyname('tcp');
457 socket(HTTPSOCK, PF_INET, SOCK_STREAM, $proto);
458 my $httpsock = \*HTTPSOCK; # filehandles are such a nasty legacy in Perl
459 my $sin = sockaddr_in($port, inet_aton($host));
460 if (not connect(HTTPSOCK, $sin)) {
461 die "maintenance::invoke can't connect(): $!, $@!\n"
462 }
463 print $httpsock "GET $url HTTP/1.0\nHost: ${host}\n\n";
464 # Thanks to Gabor Melis <gabor.melis@essnet.se> for the "Host:"
465 # header, which makes virtually hosted sites work right.
466 FAQ::OMatic::flush($httpsock);
467 # Thanks to Miro Jurisic <meeroh@MIT.EDU> for this fix.
468  
469 my @reply = <$httpsock>;
470 close $httpsock;
471  
472 if ($verbose) {
473 hprint(join('', @reply));
474 }
475 return @reply if wantarray();
476 }
477  
478 # We used to have a verifyCache task that rebuilt cached files if
479 # they were older than their item file (or the config file).
480 # The former condition wasn't very useful, since caches are rewritten
481 # whenever items are. The latter shouldn't really have happened
482 # automatically, because it can be verrrry slow on a big FAQ.
483 # And in neither case could you refresh *every* item in the cache.
484 # The new task simply reads and writes every item in the item/ directory,
485 # which ensures that its cache and dependencies are up-to-date.
486 # (note also the 'updateAllDependencies' flag to saveToFile().)
487 #
488 sub rebuildCache {
489 my $slow = shift || '';
490  
491 return if ((not defined $FAQ::OMatic::Config::cacheDir)
492 or ($FAQ::OMatic::Config::cacheDir eq ''));
493
494 if ($slow) {
495 my $fh = FAQ::OMatic::Slow::split();
496 hSetFilehandle($fh);
497 # from now on, our output goes into the slow-output file
498 # to be periodically loaded by the browser.
499 }
500  
501 my $itemName;
502 foreach $itemName (FAQ::OMatic::getAllItemNames()) {
503 hprint( "<br>Updating $itemName\n");
504 my $item = new FAQ::OMatic::Item($itemName);
505 if ($item->isEmptyStub()) {
506 # skip stubs
507 next;
508 }
509 if (not eval {
510 $item->saveToFile('', '', 'noChange', 'updateAllDependencies');
511 1;
512 }) {
513 FAQ::OMatic::gripe('note', "save failed for ".$itemName);
514 }
515  
516  
517 # flush stdout
518 hflush();
519 }
520  
521 FAQ::OMatic::Versions::setVersion('CacheRebuild');
522 }
523  
524 sub expireBags {
525 return if ((not defined $FAQ::OMatic::Config::cacheDir)
526 or ($FAQ::OMatic::Config::cacheDir eq '')
527 or (not defined $FAQ::OMatic::Config::bagsDir)
528 or ($FAQ::OMatic::Config::bagsDir eq ''));
529
530 my $anyMessages = 0;
531 my @bagList = grep { not m/\.desc$/ }
532 FAQ::OMatic::getAllItemNames($FAQ::OMatic::Config::bagsDir);
533 my $bagName;
534 foreach $bagName (@bagList) {
535 #hprint("<br>Checking $bagName\n");
536 my @dependents = FAQ::OMatic::Item::getDependencies("bags.".$bagName);
537 if (scalar(@dependents) == 0) {
538 # don't declare system-supplied bags invalid
539 # THANKS: to John Goerzen for pointing this out
540 my ($prefix) = ($bagName =~ m/^(.*)\.[^\.]+$/);
541 # THANKS: Edwin Chiu <edwinc@s-scape.ca> for fixing an
542 # uninitialized value warning coming from here.
543 next if (defined($prefix)
544 && FAQ::OMatic::ImageRef::validImage($prefix));
545  
546 if (not $anyMessages) {
547 hprint("The following suggestion(s) are based on "
548 ."dependency files.\n You might run rebuildCache first "
549 ."if you want to be certain that they are valid.\n\n");
550 }
551 $anyMessages = 1;
552 my $msg = "Consider removing bag $bagName; it is not linked from "
553 ."any item in the FAQ.";
554 hprint "<br>$msg\n";
555 # TODO: in a future version, we could actually just unlink
556 # TODO: the unreferenced bags. (garbage collection).
557 # The comment above about rebuildCache would apply.
558 # Dependencies should stay current, but I'd sure hate
559 # to accidentally blast your bag.
560 }
561 }
562 }
563  
564 sub bagAllImages {
565 return if ((not defined $FAQ::OMatic::Config::bagsDir)
566 or ($FAQ::OMatic::Config::bagsDir eq ''));
567  
568 require FAQ::OMatic::ImageRef;
569 FAQ::OMatic::ImageRef::bagAllImages();
570  
571 FAQ::OMatic::Versions::setVersion('SystemBags');
572 }
573  
574 sub mirrorClient {
575 my $slow = shift || '';
576 my $url = $FAQ::OMatic::Config::mirrorURL;
577  
578 if ((not defined $url)
579 or ($url eq '')) {
580 hprint("mirrorClient() exiting silently because this is "
581 ."not a mirror.\n");
582 return;
583 }
584  
585 if ($slow) {
586 my $fh = FAQ::OMatic::Slow::split();
587 hSetFilehandle($fh);
588 # from now on, our output goes into the slow-output file
589 # to be periodically loaded by the browser.
590 }
591  
592 hprint("<p>Querying master site for item and bag modification times.<p>\n");
593 hflush();
594  
595 my $limit = -1; # Set to a small number for debugging, so you don't
596 # have to wait for the whole mirror to complete.
597 # Set to -1 for normal operation.
598  
599 require FAQ::OMatic::install;
600  
601 # cheesily parse the URL. This seemed better than use'ing the
602 # whole URL.pm kit. I had bad luck with it once. Maybe I'm irrational.
603 my ($host, $port, $path) =
604 $url =~ m#http://([^/:]+)(:\d+)?/(.*)$#;
605 if (defined $port) {
606 $port =~ s/^://;
607 } else {
608 $port = 80;
609 }
610 $path = "/$path?cmd=mirrorServer";
611  
612 my @reply = invoke($host, $port, $path);
613  
614 # chew HTTP headers until a blank line
615 while (not $reply[0] =~ m/^[\r\n]*$/) {
616 shift @reply;
617 }
618 shift @reply; # chew off that blank line
619 @reply = grep { not m/^#/ } @reply; # chew off comment lines
620 @reply = map { chomp $_; $_ } @reply; # chomp LFs
621  
622 # first line of remaining content must be version number
623 my $version = shift @reply;
624 if ($version ne 'version 1.0') {
625 die "This FAQ-O-Matic version $FAQ::OMatic::VERSION only understands "
626 ."mirrorServer data version 1.0; received $version.";
627 }
628  
629 #hprint join("\n", @reply);
630  
631 my @itemURL = grep { m/^itemURL\s/ } @reply;
632 my $itemURL = ($itemURL[0] =~ m/^itemURL\s+(.*)$/)[0];
633 if (not defined $itemURL) {
634 die "master didn't send itemURL line.";
635 }
636  
637 my @configs = grep { m/^config\s/ } @reply;
638 my $config;
639 my $map = FAQ::OMatic::install::readConfig();
640 hprint("configs supplied: ".scalar(@configs)."\n");
641 foreach $config (@configs) {
642 my ($left,$right) =
643 ($config =~ m/config (\$\S+) = (.+)$/);
644 if (defined $left and defined $right) {
645 # unless the config line is buggy, as can happen when
646 # the mirrorServer FAQ is running 2.618 :v(, update our config
647 $map->{$left} = $right;
648 hprint("<br>$left => $right\n");
649 }
650 }
651 FAQ::OMatic::install::writeConfig($map);
652 # now make sure that config takes effect for all the cache
653 # files we're about to write
654 FAQ::OMatic::install::rereadConfig();
655 hflush();
656  
657 my $count = 0;
658 my @items = grep { m/^item\s/ } @reply;
659 my $line;
660 foreach $line (@items) {
661 my ($file,$lms) =
662 ($line =~ m/item\s+(\S+)\s+(\S+)/);
663 if (not defined $file || $file eq '') {
664 hprint("<br>Can't parse: $line\n");
665 next;
666 }
667 my $item = new FAQ::OMatic::Item($file);
668 my $existingLms = $item->{'LastModifiedSecs'} || -1;
669 if ($lms != $existingLms) {
670 hprint("<br>$file ".$item->getTitle().": item needs update\n");
671 mirrorItem($host, $port, $itemURL."$file", $file, '');
672 $count++; # each net access counts 1, whether or not it takes
673 } else {
674 # hprint "<br>Already have: $file ".$item->getTitle()."\n";
675 # Benign output supressed so you can see which items you
676 # don't have.
677 }
678  
679 if ($limit>=0 && $count >= $limit) {
680 hprint("<p>stopping because count = limit ($limit)\n");
681 return;
682 }
683 # flush output
684 hflush();
685 }
686  
687 my @bagsURL = grep { m/^bagsURL\s/ } @reply;
688 my $bagsURL = ($bagsURL[0] =~ m/^bagsURL\s+(.*)$/)[0];
689 if (not defined $bagsURL) {
690 die "master didn't send bagsURL line.";
691 }
692  
693 my @bags = grep { m/^bag\s/ } @reply;
694 foreach $line (@bags) {
695 my ($bagword,$file,$lms) = split(/\s+/, $line);
696 if (not defined($bagword)
697 || ($bagword ne 'bag')
698 || not defined($file)) {
699 hprint("bad line: $line");
700 #continue; LEFT OFF
701 }
702 if ((not defined($lms)) || ($lms eq '')) {
703 # some old mirrorServer forgot to send a date --- assume the
704 # file is recently modified.
705 $lms = time();
706 }
707 $file = FAQ::OMatic::Bags::untaintBagName($file);
708 if ($file eq '') {
709 hprint("<br>Tainted bag name in '$line'\n");
710 next;
711 }
712  
713 my $descFile = $file.".desc";
714 my $descItem = new FAQ::OMatic::Item($descFile,
715 $FAQ::OMatic::Config::bagsDir);
716 my $existingLms = $descItem->{'LastModifiedSecs'} || -1;
717  
718 if ($lms != $existingLms) {
719 hprint("<br>${file}: bag needs update\n");
720 # transfer bag byte-for-byte to my bags dir
721 mirrorBag($host, $port, $bagsURL."$file", $file);
722 # transfer the .desc file, using same item mirroring code as above
723 mirrorItem($host, $port, $bagsURL.$descFile,
724 $descFile, $FAQ::OMatic::Config::bagsDir);
725 # update the link in any items that point to this bag
726 FAQ::OMatic::Bags::updateDependents($file);
727 $count += 2;
728 } else {
729 # hprint "<br>Already have: $file\n";
730 }
731  
732 if ($limit>=0 && $count >= $limit) {
733 hprint("<p>stopping because count = limit ($limit)\n");
734 return;
735 }
736 # flush output
737 hflush();
738 }
739 }
740  
741 # a close relative of previous function invoke().
742 sub mirrorItem {
743 my $host = shift;
744 my $port = shift;
745 my $path = shift;
746 my $itemFilename = shift;
747 my $itemDir = shift;
748  
749 my $proto = getprotobyname('tcp');
750 my $sin = sockaddr_in($port, inet_aton($host));
751  
752 socket(HTTPSOCK, PF_INET, SOCK_STREAM, $proto);
753 my $httpsock = \*HTTPSOCK;
754  
755 if (not connect($httpsock, $sin)) {
756 die "mirrorItem can't connect(): $!, $@!\n"
757 }
758 my $request = "GET $path HTTP/1.0\nHost: ${host}";
759 # THANKS to Stefan Stidl <sti@austromail.at> for the
760 # Host: header, to fix mirroring from virtual hosts
761 print $httpsock "$request\n\n";
762 FAQ::OMatic::flush($httpsock);
763 # Thanks to Miro Jurisic <meeroh@MIT.EDU> for this fix.
764 my $httpstatus = <$httpsock>; # get initial result
765 chomp $httpstatus;
766 my ($statusNum) = ($httpstatus =~ m/\s(\d+)\s/);
767 if ($statusNum != 200) {
768 hprint("<br>Request '$request' for $itemFilename from "
769 ."$host:$port failed: ($statusNum) $httpstatus\n");
770 close($httpsock);
771 return;
772 }
773 while (defined($_=<$httpsock>)) { # blow past HTTP headers
774 last if ($_ =~ m/^[\r\n]*$/);
775 }
776  
777 my $item = new FAQ::OMatic::Item();
778 $item->{'filename'} = $itemFilename;
779 $item->loadFromFileHandle($httpsock);
780 close($httpsock);
781  
782 $item->{'titleChanged'} = 'true';
783 # since we just mirrored this guy, the title may very well
784 # have changed, so we need to be sure to rewrite dependent items.
785 $item->saveToFile($itemFilename, $itemDir, 'noChange', 'updateAllDeps',
786 'noRecomputeDependencies');
787 # notice we're passing in a filename we got from that
788 # web server -- an insidious master might try to pass
789 # off bogus item filenames with '..'s in them. But saveToFile()
790 # has a taint-check to prevent that sort of thing.
791 # 'noChange' keeps lastModified date intact, so we won't keep
792 # re-mirroring this item.
793 # 'updateAllDependencies' is necessary, because otherwise
794 # saveToFile only adds those dependencies that are "new" to
795 # this item -- but we only have the item, not the .dep file,
796 # so we need to always regenerate all deps.
797 # 'noRecomputeDependencies' prevents Item.pm from trying to
798 # resolve forward references to nonexistent items. For example, an
799 # item can have a parent that hasn't been reached yet in the
800 # mirroring.
801 hprint("<br>$itemFilename (".$item->getTitle()."): "
802 ."item mirrored successfully\n");
803 }
804  
805 sub mirrorBag {
806 my $host = shift;
807 my $port = shift;
808 my $path = shift;
809 my $bagFilename = shift; # already untainted by caller
810  
811 my $proto = getprotobyname('tcp');
812 my $sin = sockaddr_in($port, inet_aton($host));
813  
814 socket(HTTPSOCK, PF_INET, SOCK_STREAM, $proto);
815 my $httpsock = \*HTTPSOCK; # filehandles are such a nasty legacy in Perl
816  
817 if (not connect($httpsock, $sin)) {
818 die "mirrorBag can't connect(): $!, $@!\n"
819 }
820 my $request = "GET $path HTTP/1.0\nHost: ${host}";
821 print $httpsock "$request\n\n";
822 FAQ::OMatic::flush($httpsock);
823 # Thanks to Miro Jurisic <meeroh@MIT.EDU> for this fix.
824 my $httpstatus = <$httpsock>; # get initial result
825 chomp $httpstatus;
826 my ($statusNum) = ($httpstatus =~ m/\s(\d+)\s/);
827 if ($statusNum != 200) {
828 hprint("<br>Request '$request' for $bagFilename from "
829 ."$host:$port failed: ($statusNum) $httpstatus\n");
830 close($httpsock);
831 return;
832 }
833 while (defined($_=<$httpsock>)) { # blow past HTTP headers
834 last if ($_ =~ m/^[\r\n]*$/);
835 }
836  
837 # input looks good at this point -- open output bag file
838 if (not open(BAGFILE, ">".$FAQ::OMatic::Config::bagsDir.$bagFilename)) {
839 hprint("<br>open of $bagFilename failed: $!\n");
840 close $httpsock;
841 return;
842 }
843  
844 my $sizeBytes = 0;
845 my $buf;
846 while (read($httpsock, $buf, 4096)) {
847 print BAGFILE $buf;
848 $sizeBytes += length($buf);
849 # TODO: maybe have (mirror-site-admin)-configurable length limit here
850 }
851 close(BAGFILE);
852 close($httpsock);
853  
854 if (not chmod(0644, $FAQ::OMatic::Config::bagsDir.$bagFilename)) {
855 FAQ::OMatic::gripe('problem', "chmod("
856 .$FAQ::OMatic::Config::bagsDir.$bagFilename
857 ." failed: $!");
858 }
859  
860 if ($sizeBytes == 0) {
861 hprint("<br><b>Uh oh, I read no bytes for $bagFilename.</b>\n");
862 return;
863 }
864  
865 hprint("<br>${bagFilename}: bag mirrored successfully\n");
866 }
867  
868 sub mtime {
869 my $filename = shift;
870 return (stat($filename))[9] || 0;
871 }
872  
873 sub emptyTrash {
874 my $slow = shift || '';
875  
876 if ($slow) {
877 my $fh = FAQ::OMatic::Slow::split();
878 hSetFilehandle($fh);
879 # from now on, our output goes into the slow-output file
880 # to be periodically loaded by the browser.
881 }
882  
883 my $trashExpirationDays = $FAQ::OMatic::Config::trashTime || 0;
884 if ($trashExpirationDays == 0) {
885 hprint("\$trashTime says to never take out the trash.<br>\n");
886 return;
887 }
888  
889 my $trashItem = new FAQ::OMatic::Item('trash');
890 if ($trashItem->isBroken()) {
891 FAQ::OMatic::gripe('problem', gettext('Crud, the trash can is broken.'));
892 return;
893 }
894  
895 # walk the trash tree looking for old trash
896 hprint("<br>At top level:\n");
897 my @children = $trashItem->getChildren();
898 emptyTrashVisitChildren($trashItem, \@children, 1);
899 $trashItem->saveToFile();
900 hprint("<p>emptyTrash: Done\n");
901 }
902  
903 sub indent {
904 my $amount = shift;
905 return ("."x($amount*3))." ";
906 }
907  
908 sub emptyTrashVisitChildren {
909 my $parentItem = shift;
910 my $childList = shift;
911 my $indent = shift;
912  
913 hprint(indent($indent)."Visit children (".scalar(@$childList).")\n");
914 foreach my $childName (@$childList) {
915 #hprint(indent($indent+1)."Visit children ($childName)\n");
916 my $childItem = new FAQ::OMatic::Item($childName);
917 if ($childItem->isBroken()) {
918 # can't see into child item. Detach, and let fsck find
919 # and destroy te item file.
920 hprint(indent($indent)."detaching broken child $childName\n");
921 $parentItem->removeSubItem($childName, 'deferUpdate');
922 # deferred update okay because caller will
923 # explicitly save this guy
924 } else {
925 emptyTrashVisitItem($childName, $childItem, $indent);
926 }
927 hflush();
928 }
929 }
930  
931 sub emptyTrashVisitItem {
932 my $itemName = shift;
933 my $item = shift;
934 my $indent = shift;
935  
936 my $trashExpirationDays = $FAQ::OMatic::Config::trashTime || 0;
937 my $trashExpirationSeconds = $trashExpirationDays*24*60*60;
938  
939 my $filename = $item->{'filename'} || '[no filename]';
940 my $title = $item->getTitle() || '[no title]';
941 hprint(indent($indent)."Examining trash node $filename ($itemName) named $title\n");
942  
943 # Get (rid of) the children;
944 # if this isn't a category, it'll just get the
945 # empty list, and that's perfect.
946 my @children = $item->getChildren();
947 if (scalar(@children)>0) {
948 emptyTrashVisitChildren($item, \@children, $indent+1);
949 }
950  
951 # if there aren't any children now (either there weren't before, or
952 # we actually blasted them all), then consider blasting this guy, too.
953 my $blasted = 0;
954 @children = $item->getChildren();
955 if (scalar(@children)<=0) {
956 # found a leaf
957 hprint(indent($indent)."Found a leaf ".$item->getTitle()."\n");
958 my $lastModified = $item->{'LastModifiedSecs'} || 0;
959 my $age = time() - $lastModified;
960 if ($age > $trashExpirationSeconds) {
961 hprint(indent($indent)." ... and it's old. Should delete.\n");
962 my $filename = $item->{'filename'};
963 my $rc = $item->destroyItem('deferUpdate');
964 # deferred update is okay, because we're going to
965 # save this guy's parent anyway when we return from
966 # the recursion (if the parent isn't blasted.)
967 if ($rc) {
968 hprint(indent($indent)."removed $filename; rc = $rc");
969 $blasted = 1;
970 } else {
971 hprint(indent($indent)."couldn't remove $filename; rc = $rc");
972 }
973 } else {
974 hprint(indent($indent).sprintf("'-but it's not old. (%d sec)\n", $age));
975 }
976 }
977 if (!$blasted) {
978 # make sure changes to directory stick.
979 hprint(indent($indent).scalar(@children)." children remain. This item survives. Saving changed directory\n");
980 $item->saveToFile();
981 }
982 }
983  
984 sub fsck {
985  
986 my $reportFreq = 100;
987  
988 # check for:
989 # links to broken items -> replace link with text describing broken link
990 # items claimed by multiple parents -> rewrite as links in n-1 parents
991 # roots other than 1, trash -> connect to lost+found
992 hprint("Pass 1: detect broken files\n");
993 hflush();
994 my $count = 0;
995 foreach my $filei (FAQ::OMatic::getAllItemNames()) {
996 my $item = new FAQ::OMatic::Item($filei);
997 # if ($filei eq '1117') {
998 # hprint("1117: broken=".($item->isBroken()?'t':'f')
999 # ." emptyStub=".($item->isEmptyStub()?'t':'f')
1000 # ."\n");
1001 # }
1002 if ($item->isBroken() and not $item->isEmptyStub()) {
1003 # file is broken. disconnect it from parent; delete file
1004 fsckReport("found broken item file $filei; destroying");
1005 FAQ::OMatic::Item::destroyItemRaw($filei);
1006 }
1007 if (((++$count)%$reportFreq)==0) {
1008 hprint("checked $count items; finished $filei\n");
1009 }
1010 hflush();
1011 }
1012  
1013 my $lostAndFoundItem = undef;
1014 hprint("Pass 2: Detect incorrect ownership claims, disconnected subtrees\n");
1015 hflush();
1016 $count = 0;
1017 foreach my $filei (FAQ::OMatic::getAllItemNames()) {
1018 my $item = new FAQ::OMatic::Item($filei);
1019 if ($item->isBroken() and not $item->isEmptyStub()) {
1020 FAQ::OMatic::gripe('abort', "pass 1 failed; can't proceed to pass 2.");
1021 }
1022 my @children = $item->getChildren();
1023 my $changedChildren = 0;
1024 foreach my $childName (@children) {
1025 my $childItem = new FAQ::OMatic::Item($childName);
1026 if ($childItem->isBroken()) {
1027 fsckReport("$filei owns broken child $childName; detaching");
1028 $item->removeSubItem($childName, 'deferUpdate');
1029 $changedChildren = 1;
1030 } elsif ($childItem->{'Parent'} ne $filei) {
1031 fsckReport("$filei claims to own $childName, but ${childName}'s parent is ".$childItem->{'Parent'}."; detaching");
1032  
1033 $item->removeSubItem($childName, 'deferUpdate');
1034 $changedChildren = 1;
1035 }
1036 }
1037 if ($changedChildren) {
1038 $item->saveToFile();
1039 }
1040 hflush();
1041
1042 my $parent = $item->getParent();
1043 if ($filei eq '1' || $filei eq 'trash' || $filei eq 'help000') {
1044 # ignore these; they're okay as roots.
1045 } elsif ($parent->isBroken() or ($parent == $item)) {
1046 fsckReport("$filei is a root, but shouldn't be");
1047 $lostAndFoundItem = getLostAndFoundItem($lostAndFoundItem);
1048 $lostAndFoundItem->addSubItem($filei);
1049 $item->setProperty('Parent', $lostAndFoundItem->{'filename'});
1050 $item->saveToFile();
1051 $lostAndFoundItem->saveToFile();
1052 }
1053 if (((++$count)%$reportFreq)==0) {
1054 hprint("checked $count items; finished $filei\n");
1055 }
1056 hflush();
1057 }
1058 hprint("fsck complete\n");
1059 hflush();
1060 }
1061  
1062 sub fsckReport {
1063 my $msg = shift;
1064 hprint("$msg\n");
1065 FAQ::OMatic::gripe('note', $msg);
1066 }
1067  
1068 sub getLostAndFoundItem {
1069 my $lostAndFoundItem = shift;
1070 if (defined($lostAndFoundItem)) {
1071 return $lostAndFoundItem;
1072 }
1073 my $top = new FAQ::OMatic::Item('1');
1074 foreach my $childName ($top->getChildren) {
1075 my $childItem = new FAQ::OMatic::Item($childName);
1076 if (($childItem->{'Title'}||'') eq 'lost+found') {
1077 return $childItem;
1078 }
1079 }
1080 # have to create one.
1081 $lostAndFoundItem = new FAQ::OMatic::Item();
1082 $lostAndFoundItem->setProperty('Parent', '1');
1083 $lostAndFoundItem->setProperty('Title', 'lost+found');
1084 $lostAndFoundItem->saveToFile(FAQ::OMatic::unallocatedItemName('1'));
1085  
1086 $top->addSubItem($lostAndFoundItem->{'filename'});
1087 $top->saveToFile();
1088 return $lostAndFoundItem;
1089 }
1090  
1091 1;