#!/usr/bin/perl use IPC::Run3; use Digest::SHA1; use File::Spec; # config # $mode: 0 = normal cleardir/wget/hash using $tmpBase # 1 = calc hash of $htdocsBase $mode = 0; $url = 'http://10.0.0.253:81'; $tmpBase = '/mnt/fs2'; $htdocsBase = '/var/www/port81/htdocs'; $cmpHash = '04e28506af6a4d00f308647dac7c5842bfa79f80'; $sleepSec = 5; # global vars $tmpPath = File::Spec->catfile($tmpBase, "wget"); %hashes = (); sub ensureEmptyDir { my ($dir) = @_; die if ($dir eq "" or $dir eq "/"); if (-d $dir) { recursiveEmpty($dir, 0); } else { mkdir $dir; } } sub recursiveEmpty { my ($dir, $level) = @_; local *DIR; opendir DIR, $dir or die "opendir $dir: $!"; my $found = 0; while ($_ = readdir DIR) { next if /^\.{1,2}$/; my $path = File::Spec->catfile($dir, $_); unlink $path if -f $path; recursiveEmpty($path, $level + 1) if -d $path; } closedir DIR; if ($level >= 1) { rmdir $dir or print "error - $!"; } } sub recursiveHash { my ($dir, $level, $relDir) = @_; local *DIR; local *FILE; opendir DIR, $dir or die "opendir $dir: $!"; my $found = 0; while ($_ = readdir DIR) { next if /^\.{1,2}$/; next if m/^index\.html?$/im; my $path = File::Spec->catfile($dir, $_); my $newRelDir = ""; $newRelDir = $relDir . "/" . $_ if $level >= 1; if (-f $path && $level >= 1) { open(FILE, "<", $path) or die "cannot hash file"; binmode FILE; my $sha1 = Digest::SHA1->new; $sha1->addfile(FILE); close FILE; #print "$newRelDir\n" if ($mode); $hashes{$newRelDir} = $sha1->hexdigest; } recursiveHash($path, $level + 1, $newRelDir) if -d $path; } closedir DIR; } sub runWget() { my ($stdout, $stderr); my @args = ("wget", "-nv", "-P", $tmpPath, "-r", $url); IPC::Run3::run3(\@args, undef, \$stdout, \$stderr); $r = $?; open FILE, ">last-stdout" or die; print FILE $stdout; close FILE; open FILE, ">last-stderr" or die; print FILE $stderr; close FILE; return $r; } sub runHash() { my ($dir, $level); if ($mode) { $dir = $htdocsBase; $level = 1; } else { $dir = $tmpPath; $level = 0; } %hashes = (); recursiveHash($dir, $level, ""); my $sha1 = Digest::SHA1->new; foreach my $path (sort keys %hashes) { my $d = $hashes{$path}; $sha1->add($d); } return $sha1->hexdigest; } sub printFlush { my ($txt) = @_; print $txt; STDOUT->flush; } $iter = 1; if ($mode) { my $r; $r = runHash(); print "calculated hash: $r\n"; exit 0; } while(1) { my ($r); printFlush("iteration #$iter: cleardir... "); ensureEmptyDir($tmpPath); printFlush("wget..."); $r = runWget; if ($r) { print "\nwget returned an error!\n"; exit 1; } if (length($cmpHash) >= 1) { printFlush(" hashing..."); $r = runHash; if (! ((lc $r) eq (lc $cmpHash))) { print ": SHA1 hash verification failed!\n"; print " expected: $cmpHash\n"; print "calculated: $r\n"; exit 1; } } print ": OK\n"; $iter++; sleep($sleepSec); }