3 # This script is to get the changes needed to update the
4 # files on a mir mirror.
6 # Full details (among other stuff) at
7 # http://lists.indymedia.org/pipermail/imc-uk-tech/2006-May/0531-ib.html
11 # Mir will simply publish a list of file changes. It will produce one
12 # file per day. The file will be publicly viewable on the web at
14 # /changes/changesYYYYMMDD.txt
16 # So on May 28th, 2006, the file name would be
18 # /changes/changes20060528.txt
20 # The format of the file will also be simple. There will be three
21 # columns. First will be the time, then (add/change/delete) depending
22 # whether the file is new, has been updated or deleted, and then the full
23 # relative path of the file. So an example line would be
25 # 2006:01:24T09:08:17 add /en/2006/05/341547.html
27 # This will have to be done for HTML files, media files and the include
41 # This has name conflicts with Date::Parse and
42 # Date::Format; don't import its names.
49 # by default, this is not a test
52 # by default, this is the working directory
55 # get the time and date - using UTC
58 # if this is 1, we only list the change files that are needed and stop
59 # otherwise we do our normal processing
60 my $listchangefiles = 0;
62 # The root URL to fetch files from
65 ################################
66 # process command line arguments
67 ################################
71 Usage: update.pl [options]
73 --remoteroot=url Set the remote root URL to mirror from (mandatory)
74 --workingdir=path Set the root of the local mirror (default ".")
75 --now=timestring Pretend it's currently the specified time
76 --list-change-files Just list the change files we would fetch
77 --verbose Run in verbose mode
78 --help Output this help
85 GetOptions( "verbose!" => \$verbose,
86 "workingdir=s" => \$workingdir,
87 "now=s" => sub($) { $timenow = str2time($_[0]); },
88 "remoteroot=s" => \$remoteroot,
89 "list-change-files!" => \$listchangefiles,
90 "help" => sub() { usage(); } );
92 usage() if not defined $remoteroot;
94 # the directory where all files with state are kept
95 my $statedir = "$workingdir/state";
97 mkdir $statedir or die "Can't create $statedir";
100 # the directory where changes files are kept
101 my $changesdir = "$workingdir/changes";
103 # the file we want with the last time in it is
104 my $lastupdatefile = "$statedir/lastupdate.txt";
106 # where we get changes files from
107 my $changesroot = "$remoteroot/changes";
109 # LWP user agent for fetching files
110 # keep_alive is important, to avoid the overhead of
111 # establishing a new connection for each file we fetch
112 my $ua = new LWP::UserAgent( agent => "MirMirror/0.1",
120 # find the last update time
121 # if the file with the update time has disappeared, alert the admin
122 # and use the datestamp on the startpage file ( /en/index.html )
123 sub findLastUpdateTime() {
124 open (UPDATETIME, "<", $lastupdatefile) or return $timenow;
125 my $lastupdatetimestr = <UPDATETIME>;
128 chomp ($lastupdatetimestr);
129 return str2time ($lastupdatetimestr);
132 # convert the date into a correctly formatted string
134 return time2str ("%Y:%m:%dT%T", $_[0]);
137 # convert the date into RFC2616 format
138 sub date2HTTPstr($) {
139 return time2str ("%Y:%m:%dT%T", $_[0]);
142 # write the time now into the last update file
143 sub saveLastUpdateTime() {
144 open (UPDATETIME, ">", $lastupdatefile) or die "Can't open $lastupdatefile for writing ($!)";
145 print UPDATETIME date2ISOstr($timenow);
149 # return an array of filename
150 sub getChangesFileList($$)
152 my ($fromtime, $totime) = @_;
154 for (my $time = str2time(time2str("%Y:%m:%dT00:00:00", $fromtime));
157 push @files, time2str("changes%Y%m%d.txt", $time);
162 # get the directory part of a filename
165 $dir =~ s{/+[^/]*$}{};
169 # ensure the given directory exists (like mkdir -p)
173 my $parent = dirPart($dir);
174 &ensureDir($parent) if ($parent);
175 mkdir $dir or die "Can't create directory $dir ($!)";
179 # get a file, optionally saving it locally
181 my ($remotefile, $localfile) = @_;
184 print STDERR "fetching $remotefile";
185 print STDERR " as $localfile" if $localfile;
188 my $req = new HTTP::Request(GET => "$remotefile");
190 if ($localfile and -e $localfile) {
191 # Don't fetch unless more recent than local copy
192 my $stat = stat($localfile);
193 $req->header("If-Modified-Since" => HTTP::Date::time2str($stat->mtime));
195 my $resp = $ua->request($req);
196 if ($resp->is_success) { # 2xx codes
197 my $mtime = HTTP::Date::str2time($resp->header("Last-Modified"));
200 print STDERR " -> success";
201 print STDERR "; mtime ".time2str("%c", $mtime) if $mtime;
204 ensureDir(dirPart($localfile));
206 open (LOCAL, ">", "$localfile") or die "Can't open $localfile for writing ($!)";
207 print LOCAL $resp->content or die "Error writing $localfile ($!)";
208 close LOCAL or die "Error writing $localfile ($!)";
211 utime $mtime, $mtime, $localfile;
214 return $resp->content;
216 elsif ($resp->is_redirect) { # 3xx codes
217 if ($resp->code == RC_NOT_MODIFIED) { # 304
218 print STDERR " -> not modified\n" if $verbose;
219 open (LOCAL, "<", "$localfile") or die "Can't open $localfile ($!)";
220 local $/; # slurp whole file
221 my $content = <LOCAL>;
225 print STDERR " -> redirect (".$resp->code.")\n" if $verbose;
226 die "Can't fetch $remotefile (got redirect, not yet handled)";
229 print STDERR " -> failed (".$resp->code.")\n" if $verbose;
230 die "Can't fetch $remotefile (".$resp->status_line.")";
235 sub getChangesFile($) {
236 return fetchFile($changesroot."/".$_[0], $changesdir."/".$_[0]);
245 # first work out when the last time we were up to date is and
247 my $timeoflastupdate = findLastUpdateTime();
250 print STDERR "timenow is ".time2str("%c",$timenow)." \n";
251 print STDERR "timeoflastupdate is ".time2str("%c",$timeoflastupdate)." \n\n";
254 # Now we know which days' changes we need to get from the server
255 my @changesfiles = getChangesFileList($timeoflastupdate, $timenow);
256 if ($verbose or $listchangefiles) {
257 foreach my $file (@changesfiles) { print STDERR "using changes file $file\n"; }
258 exit 0 if $listchangefiles;
261 # get the changes files
262 my %changesfilecontent;
263 foreach my $file (@changesfiles) { $changesfilecontent{$file} = getChangesFile($file); }
265 # if the file has not changed (response code 304) then ignore it
267 # iterate over all the fetched files, building up a list of files
270 foreach my $changes (@changesfiles) {
272 $date =~ s{^(?:.*/)?changes([0-9]+)\.txt$}{$1} or die "Can't extract date from changes filename $changes";
274 my @changes = split /[\r\n]+/, $changesfilecontent{$changes};
275 foreach my $change (@changes) {
276 my ($time, $op, $path) = split ' ', $change;
278 # Ignore malformed lines, especially wacky paths that could be malicious
279 if ($time =~ /[^0-9:]/) {
280 die "Invalid time $time in $changes";
283 if ($path =~ m{(?:^|/)\.\.(?:/|$)}) {
284 die "Invalid path $path (contains ..) in $changes";
287 # Strip scheme and host from absolute URLs
288 $path =~ s{^[a-z]+://[a-z0-9\-\.]+/}{/};
290 # Combine time with date and parse
291 $time = str2time("$date $time");
292 if (not defined $time) {
293 die "Failed to parse datetime '$date $time'";
296 # Ignore changes prior to $timeoflastupdate
297 next if $time < $timeoflastupdate;
300 print STDERR "Marked $path as '$op'\n" if $verbose;
304 # Fetch all files whose last operation was "add" or "change"
305 # Delete all files whose last operation was "delete"
306 while (my ($file, $op) = each %files) {
307 if ($op eq "delete") {
308 if (-e "$workingdir/$file") {
309 # delete: if the file exists, remove it
310 print STDERR "deleting $workingdir/$file\n" if $verbose;
311 unlink "$workingdir/$file" or die "Can't delete $workingdir/$file ($!)";
314 print STDERR "not deleting $workingdir/$file beacuse it doesn't exist\n" if $verbose;
317 elsif ($op eq "add" or $op eq "change" or $op eq "Modification") {
318 # add/change: re-fetch the file
319 my $content = fetchFile("$remoteroot/$file","$workingdir/$file");
322 die "Unknown operation '$op'";
327 # update the last "up-to-date" time
328 saveLastUpdateTime();