chiark / gitweb /
with-lock-ex: Provide -t (timeout) option
[chiark-utils.git] / scripts / git-cache-proxy
1 #!/usr/bin/perl -w
2 #
3 # git caching proxy
4
5 # Suitable only for exposing to semi-trusted clients: clients are not
6 # supposed to be able to take over the server.  However, clients can
7 # probably deny service to each other because the current
8 # implementation is not very good at handling various out-of-course
9 # situations (notably, clients which are too slow).
10
11 # usage: run it on some port, and then clone or fetch
12 #  "git://<realhost>:<realport>/<real-git-url>[ <options>]"
13 # where <real-git-url> is http://<host>/... or git://<host>/...
14 # and <options> is zero or more (whitespace-separated) of
15 #    [<some-option>]      will be ignored if not recognised
16 #    {<some-option>}      error if not recognised
17 # options currently known:
18 #    fetch=must           fail if the fetch/clone from upstream fails
19 #    fetch=no             just use what is in the cache
20 #    fetch=try            use what is in the cache if the fetch/clone fails
21 #    timeout=<seconds>    length of time to allow for fetch/clone
22
23 # example inetd.conf line:
24 #  9419 stream tcp nowait git-cache /usr/bin/git-cache-proxy git-cache-proxy
25 # you'll need to 
26 #  adduser git-cache
27 #  mkdir /var/cache/git-cache-proxy
28 #  chown git-cache /var/cache/git-cache-proxy
29
30 # git-cache-proxy
31 # Copyright 2010 Tony Finch
32 # Copyright 2013,2014 Ian Jackson
33 # Copyright 2017 Citrix
34
35 # git-cache-proxy is free software; you can redistribute it and/or
36 # modify them under the terms of the GNU General Public License as
37 # published by the Free Software Foundation; either version 3, or (at
38 # your option) any later version.
39 #
40 # git-cache-proxy is distributed in the hope that it will be useful,
41 # but WITHOUT ANY WARRANTY; without even the implied warranty of
42 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
43 # General Public License for more details.
44
45 # You should have received a copy of the GNU General Public License along
46 # with this program; if not, consult the Free Software Foundation's
47 # website at www.fsf.org, or the GNU Project website at www.gnu.org.
48
49 # (Some code taken from userv-utils's git-daemon.in and git-service.in
50 # which were written by Tony Finch <dot@dotat.at> and subsequently
51 # heavily modified by Ian Jackson <ijackson@chiark.greenend.org.uk>
52 # and were released under CC0 1.0.  The whole program is now GPLv3+.)
53
54 use strict;
55 use warnings;
56
57 use POSIX;
58 use Socket;
59 use Sys::Syslog;
60 use Fcntl qw(:flock SEEK_SET);
61 use File::Path qw(remove_tree);
62
63 our $us = 'git-cache-proxy';
64
65 our $debug = 0;
66 our $housekeepingeverydays = 1;
67 our $treeexpiredays = 21;
68 our $fetchtimeout = 1800;
69 our $maxfetchtimeout = 3600;
70 our $cachedir = '/var/cache/git-cache-proxy';
71 our $housekeepingonly = 0;
72
73 #---------- error handling and logging ----------
74
75 # This is a bit fiddly, because we want to catch errors sent to stderr
76 # and dump them to syslog if we can, but only if we are running as an
77 # inetd service.
78
79 our $log; # filehandle (ref), or "1" meaning syslog
80
81 sub ntoa {
82     my $sockaddr = shift;
83     return ('(local)') unless defined $sockaddr;
84     my ($port,$addr) = sockaddr_in $sockaddr;
85     $addr = inet_ntoa $addr;
86     return ("[$addr]:$port",$addr,$port);
87 }
88
89 our ($client) = ntoa getpeername STDIN;
90 our ($server) = ntoa getsockname STDIN;
91
92 sub ensurelog () {
93     return if $log;
94     openlog $us, qw(pid), 'daemon';
95     $log = 1;
96 }
97
98 sub logm ($$) {
99     my ($pri, $msg) = @_;
100     return if $pri eq 'debug' && !$debug;
101     if ($client eq '(local)') {
102         print STDERR "$us: $pri: $msg\n" or die $!;
103         return;
104     }
105     ensurelog();
106     my $mainmsg = sprintf "%s-%s: %s", $server, $client, $msg;
107     if (ref $log) {
108         my $wholemsg = sprintf("%s [%d] %s: %s\n",
109                                strftime("%Y-%m-%d %H:%M:%S Z", gmtime),
110                                $$,
111                                $pri eq 'err' ? 'error' : $pri,
112                                $mainmsg);
113         print $log $wholemsg;
114     } else {
115         syslog $pri, "%s", "$pri $mainmsg";
116     }
117 }
118
119 if ($client ne '(local)') {
120     open STDERR, ">/dev/null" or exit 255;
121     open TEMPERR, "+>", undef or exit 255;
122     open STDERR, ">&TEMPERR" or exit 255;
123 }
124
125 END {
126     if ($client ne '(local)') {
127         if ($?) { logm 'crit', "crashing ($?)"; }
128         seek TEMPERR, 0, SEEK_SET;
129         while (<TEMPERR>) {
130             chomp;
131             logm 'crit', $_;
132         }
133     }
134     exit $?;
135 }
136
137 sub fail ($) {
138     my ($msg) = @_;
139     logm 'err', $msg;
140     exit 0;
141 }
142
143 sub gitfail ($) {
144     my ($msg) = @_;
145     close LOCK;
146     alarm 60;
147     logm 'notice', $msg;
148     my $gitmsg = "ERR $us: $msg";
149     $gitmsg = substr($gitmsg,0,65535); # just in case
150     printf "%04x%s", length($gitmsg)+4, $gitmsg;
151     flush STDOUT;
152     exit 0;
153 }
154
155 #---------- argument parsing ----------
156
157 for (;;) {
158     last unless @ARGV;
159     last unless $ARGV[0] =~ m/^-/;
160     $_ = shift @ARGV;
161     for (;;) {
162         last unless m/^-./;
163         if (s/^-H/-/) {
164             $housekeepingonly++;
165         } elsif (s/^-D/-/) {
166             $debug++;
167         } elsif (s/^-L(.*)$//) {
168             my $logfile = $_;
169             open STDERR, ">>", $logfile or fail "open $logfile: $!";
170             $log = \*STDERR;
171         } elsif (s/^-d(.*)$//) {
172             $cachedir = $1;
173         } elsif (s/^--( max-fetch-timeout
174                       | fetch-timeout
175                       | tree-expire-days
176                       | housekeeping-interval-days
177                       )=(\d+)$//x) {
178             my $vn = $1;
179             $vn =~ y/-//d;
180             die $vn unless defined ${ $::{$vn} };
181             ${ $::{$vn} } = $2;
182         } else {
183             fail "bad usage: unknown option `$_'";
184         }
185     }
186 }
187
188 !@ARGV or fail "bad usage: no non-option arguments permitted";
189
190 #---------- utility functions ----------
191
192 sub lockfile ($$$) {
193     my ($fh, $fn, $flockmode) = @_;
194     my $what = $fn.(($flockmode & ~LOCK_NB) == LOCK_SH ? " (shared)" : "");
195     for (;;) {
196         close $fh;
197         open $fh, '+>', $fn or fail "open/create $fn for lock: $!";
198         logm 'debug', "lock $what: acquiring";
199         if (!flock $fh, $flockmode) {
200             if ($flockmode & LOCK_NB && $! == EWOULDBLOCK) {
201                 return 0; # ok then
202             }
203             fail "lock $what: $!";
204         }
205         stat $fh or fail "stat opened $fn: $!";
206         my $fh_ino = ((stat _)[1]);
207         if (!stat $fn) {
208             $! == ENOENT or fail "stat $fn: $!";
209             next;
210         }
211         my $fn_ino = ((stat _)[1]);
212         if ($fn_ino == $fh_ino) {
213             logm 'debug', "lock $what: acquired";
214             return 1;
215         }
216         logm 'debug', "lock $what: deleted, need to loop again";
217         # oh dear
218     }
219 }
220
221 sub xread {
222     my $length = shift;
223     my $buffer = "";
224     while ($length > length $buffer) {
225         my $ret = sysread STDIN, $buffer, $length, length $buffer;
226         fail "expected $length bytes, got ".length $buffer
227                             if defined $ret and $ret == 0;
228         fail "read: $!" if not defined $ret and $! != EINTR and $! != EAGAIN;
229     }
230     return $buffer;
231 }
232
233 #---------- main program ----------
234
235 chdir $cachedir or fail "chdir $cachedir: $!";
236
237 our ($service,$specpath,$spechost,$subdir);
238 our ($tmpd,$gitd,$lock);
239 our ($fetch,$url);
240
241 sub servinfo ($) {
242     my ($msg) = @_;
243     logm 'info', "service `$specpath': $msg";
244 }
245
246 sub readcommand () {
247     $SIG{ALRM} = sub { fail "timeout" };
248     alarm 30;
249
250     my $hex_len = xread 4;
251     fail "Bad hex in packet length" unless $hex_len =~ m|^[0-9a-fA-F]{4}$|;
252     my $line = xread -4 + hex $hex_len;
253     unless (($service,$specpath,$spechost) = $line =~
254             m|^(git-[a-z-]+) /*([!-~ ]+)\0host=([!-~]+)\0$|) {
255         $line =~ s|[^ -~]+| |g;
256         gitfail "unknown/unsupported instruction `$line'"
257     }
258
259     alarm 0;
260
261     $service eq 'git-upload-pack'
262         or gitfail "unknown/unsupported service `$service'";
263
264     $fetch = 2; # 0:don't; 1:try; 2:force
265     $url = $specpath;
266
267     while ($url =~ s#\s+(\[)([^][{}]+)\]$## ||
268            $url =~ s#\s+(\{)([^][{}]+)\}$##) {
269         $_ = $2;
270         my $must = $1 eq '{';
271         if (m/^fetch=try$/) {
272             $fetch = 1;
273         } elsif (m/^fetch=no$/) {
274             $fetch = 0;
275         } elsif (m/^fetch=must$/) {
276             $fetch = 2; # the default
277         } elsif (m/^timeout=(\d+)$/ && $1 >= 1) {
278             $fetchtimeout = $1 <= $maxfetchtimeout ? $1 : $maxfetchtimeout;
279         } elsif ($must) {
280             gitfail "unknown/unsupported option `$_'";
281         }
282     }
283
284     $url =~ m{^(?:https?|git)://[-.0-9a-z]+/}
285         or gitfail "unknown/unsupported url scheme or format `$url'";
286
287     $subdir = $url;
288     $subdir =~ s|\\|\\\\|g;
289     $subdir =~ s|,|\\,|g;
290     $subdir =~ s|/|,|g;
291
292     $tmpd= "$subdir\\.tmp";
293     $gitd= "$subdir\\.git";
294     $lock = "$subdir\\.lock";
295
296     servinfo "locking";
297 }
298
299 sub clonefetch () {
300     lockfile \*LOCK, $lock, LOCK_EX;
301
302     my $exists = lstat $gitd;
303     $exists or $!==ENOENT or fail "lstat $gitd: $!";
304
305     our $fetchfail = '';
306
307     if ($fetch) {
308
309         our @cmd;
310
311         if (!$exists) {
312             system qw(rm -rf --), $tmpd;
313             @cmd = (qw(git clone -q --mirror), $url, $tmpd);
314             servinfo "cloning";
315         } else {
316             @cmd = (qw(git remote update --prune));
317             servinfo "fetching";
318         }
319         my $cmd = "@cmd[0..1]";
320
321         my $child = open FETCHERR, "-|";
322         defined $child or fail "fork: $!";
323         if (!$child) {
324             if ($exists) {
325                 chdir $gitd or fail "chdir $gitd: $!";
326             }
327             setpgrp or fail "setpgrp: $!";
328             open STDERR, ">&STDOUT" or fail "redirect stderr: $!";
329             exec @cmd or fail "exec $cmd[0]: $!";
330         }
331
332         my $fetcherr = '';
333         my $timedout = 0;
334         {
335             local $SIG{ALRM} = sub {
336                 servinfo "fetch/clone timeout";
337                 $timedout=1; kill 9, -$child;
338             };
339             alarm($fetchtimeout);
340             $!=0; { local $/=undef; $fetcherr = <FETCHERR>; }
341             !FETCHERR->error or fail "read pipe from fetch/clone: $!";
342             alarm(10);
343         }
344
345         kill -9, $child or fail "kill fetch/clone: $!";
346         $!=0; $?=0; if (!close FETCHERR) {
347             fail "reap fetch/clone: $!" if $!;
348             my $fetchfail =
349                 !($? & 255) ? "$cmd died with error exit code ".($? >> 8) :
350                 $? != 9 ? "$cmd died due to fatal signa, status $?" :
351                 $timedout ? "$cmd timed out (${fetchtimeout}s)" :
352                 "$cmd died due to unexpected SIGKILL";
353             if (length $fetcherr) {
354                 $fetchfail .= "\n$fetcherr";
355                 $fetchfail =~ s/\n$//;
356                 $fetchfail =~ s{\n}{ // }g;
357             }
358             if ($fetch >= 2) {
359                 gitfail $fetchfail;
360             } else {
361                 servinfo "fetch/clone failed: $fetchfail";
362             }
363         }
364         alarm 0;
365
366         if (!$exists) {
367             rename $tmpd, $gitd or fail "rename fresh $tmpd to $gitd: $!";
368             $exists = 1;
369         }
370     } else {
371         $fetchfail = 'not attempted';
372     }
373
374     if (!$exists) {
375         gitfail "no cached data, and not cloned: $fetchfail";
376     }
377
378     servinfo "sharing";
379     lockfile \*LOCK, $lock, LOCK_SH; # NB releases and relocks
380
381     if (stat $gitd) {
382         return 1;
383     }
384     $!==ENOENT or fail "stat $gitd: $!";
385
386     # Well, err, someone must have taken the lock in between
387     # and garbage collected it.  How annoying.
388     return 0;
389 }
390
391 sub hkfail ($) { my ($msg) = @_; fail "housekeeping: $msg"; }
392
393 sub housekeeping () {
394     logm 'info', "housekeeping started";
395     foreach $lock (<[a-z]*\\.lock>) {
396         my $subdir = $lock;  $subdir =~ s/\\.lock$//;
397         if (!lstat $lock) {
398             $! == ENOENT or hkfail "$lock: lstat: $!";
399             next;
400         }
401         if (-M _ <= $treeexpiredays) {
402             logm 'debug', "housekeeping: subdirs $subdir: touched recently";
403             next;
404         }
405         if (!lockfile \*LOCK, $lock, LOCK_EX|LOCK_NB) {
406             logm 'info', "housekeeping: subdirs $subdir: lock busy, skipping";
407             next;
408         }
409         logm 'info', "housekeeping: subdirs $subdir: cleaning";
410         eval {
411             foreach my $suffix (qw(tmp git)) {
412                 my $dir = "${subdir}\\.$suffix";
413                 my $tdir = "${subdir}\\.tmp";
414                 if ($dir ne $tdir) {
415                     if (!rename $dir,$tdir) {
416                         next if $! == ENOENT;
417                         die "$dir: cannot rename to $tdir: $!\n";
418                     }
419                 }
420                 system qw(rm -rf --), $tdir;
421                 if (stat $tdir) {
422                     die "$dir: problem deleting file(s), rm exited $?\n";
423                 } elsif ($! != ENOENT) {
424                     die "$tdir: cannot stat after deletion: $!\n";
425                 }
426             }
427         };
428         if (length $@) {
429             chomp $@;
430             logm 'warning', "housekeeping: $subdir: cleanup prevented: $@";
431         } else {
432             unlink $lock or hkfail "remove $lock: $!";
433         }
434     }
435     open HS, ">", "Housekeeping.stamp" or hkfail "touch Housekeeping.stamp: $!";
436     close HS or hkfail "close Housekeeping.stamp: $!";
437     logm 'info', "housekeeping finished";
438 }
439
440 sub housekeepingcheck ($$) {
441     my ($dofork, $force) = @_;
442     if (!$force) {
443         if (!lockfile \*HLOCK, "Housekeeping.lock", LOCK_EX|LOCK_NB) {
444             logm 'debug', "housekeeping lock taken, not running";
445             close HLOCK;
446             return 0;
447         }
448     }
449     if ($force) {
450         logm 'info', "housekeeping forced";
451     } elsif (!lstat "Housekeeping.stamp") {
452         $! == ENOENT or fail "lstat Housekeeping.stamp: $!";
453         logm 'info', "housekeeping not done yet, will run";
454     } elsif (-M _ <= $housekeepingeverydays) {
455         logm 'debug', "housekeeping done recently";
456         close HLOCK;
457         return 0;
458     }
459     if ($dofork) {
460         my $child = fork;
461         defined $child or fail "fork: $!";
462         if (!$child) {
463             open STDERR, "|logger -p daemon.warning -t '$us(housekeeping)'"
464                 or die "fork: logger $!";
465             housekeeping();
466             exit 0;
467         }
468     } else {
469         housekeeping();
470     }
471     close HLOCK;
472     return 1;
473 }
474
475 sub runcommand () {
476     servinfo "serving";
477
478     chdir $gitd or fail "chdir $gitd: $!";
479
480     exec qw(git-upload-pack --strict --timeout=1000 .)
481         or fail "exec git-upload-pack: $!";
482 }
483
484 sub daemonservice () {
485     readcommand();
486     while (!clonefetch()) { }
487     housekeepingcheck(1,0);
488     runcommand();
489 }
490
491 if ($housekeepingonly) {
492     housekeepingcheck(0, $housekeepingonly>=2);
493 } else {
494     daemonservice();
495 }