chiark / gitweb /
7dd6f3ec531d53553633905a2c491bd8ffb43645
[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 $gcintervaldays = 10;
68 our $treeexpiredays = 21;
69 our $fetchtimeout = 3600;
70 our $maxfetchtimeout = 7200;
71 our $servetimeout = 3600;
72 our $cachedir = '/var/cache/git-cache-proxy';
73 our $housekeepingonly = 0;
74
75 #---------- error handling and logging ----------
76
77 # This is a bit fiddly, because we want to catch errors sent to stderr
78 # and dump them to syslog if we can, but only if we are running as an
79 # inetd service.
80
81 our $log; # filehandle (ref), or "1" meaning syslog
82
83 sub ntoa {
84     my $sockaddr = shift;
85     return ('(local)') unless defined $sockaddr;
86     my ($port,$addr) = sockaddr_in $sockaddr;
87     $addr = inet_ntoa $addr;
88     return ("[$addr]:$port",$addr,$port);
89 }
90
91 our ($client) = ntoa getpeername STDIN;
92 our ($server) = ntoa getsockname STDIN;
93
94 sub ensurelog () {
95     return if $log;
96     openlog $us, qw(pid), 'daemon';
97     $log = 1;
98 }
99
100 sub logm ($$) {
101     my ($pri, $msg) = @_;
102     return if $pri eq 'debug' && !$debug;
103     if ($client eq '(local)') {
104         print STDERR "$us: $pri: $msg\n" or die $!;
105         return;
106     }
107     ensurelog();
108     my $mainmsg = sprintf "%s-%s: %s", $server, $client, $msg;
109     if (ref $log) {
110         my $wholemsg = sprintf("%s [%d] %s: %s\n",
111                                strftime("%Y-%m-%d %H:%M:%S Z", gmtime),
112                                $$,
113                                $pri eq 'err' ? 'error' : $pri,
114                                $mainmsg);
115         print $log $wholemsg;
116     } else {
117         syslog $pri, "%s", "$pri $mainmsg";
118     }
119 }
120
121 if ($client ne '(local)') {
122     open STDERR, ">/dev/null" or exit 255;
123     open TEMPERR, "+>", undef or exit 255;
124     open STDERR, ">&TEMPERR" or exit 255;
125 }
126
127 END {
128     if ($client ne '(local)') {
129         if ($?) { logm 'crit', "crashing ($?)"; }
130         seek TEMPERR, 0, SEEK_SET;
131         while (<TEMPERR>) {
132             chomp;
133             logm 'crit', $_;
134         }
135     }
136     exit $?;
137 }
138
139 sub fail ($) {
140     my ($msg) = @_;
141     logm 'err', $msg;
142     exit 0;
143 }
144
145 sub gitfail ($) {
146     my ($msg) = @_;
147     close LOCK;
148     alarm 60;
149     logm 'notice', $msg;
150     my $gitmsg = "ERR $us: $msg";
151     $gitmsg = substr($gitmsg,0,65535); # just in case
152     printf "%04x%s", length($gitmsg)+4, $gitmsg;
153     flush STDOUT;
154     exit 0;
155 }
156
157 #---------- argument parsing ----------
158
159 for (;;) {
160     last unless @ARGV;
161     last unless $ARGV[0] =~ m/^-/;
162     $_ = shift @ARGV;
163     for (;;) {
164         last unless m/^-./;
165         if (s/^-H/-/) {
166             $housekeepingonly++;
167         } elsif (s/^-D/-/) {
168             $debug++;
169         } elsif (s/^-L(.*)$//) {
170             my $logfile = $_;
171             open STDERR, ">>", $logfile or fail "open $logfile: $!";
172             $log = \*STDERR;
173         } elsif (s/^-d(.*)$//) {
174             $cachedir = $1;
175         } elsif (s/^--( max-fetch-timeout
176                       | fetch-timeout
177                       | serve-timeout
178                       | tree-expire-days
179                       | housekeeping-interval-days
180                       | gc-interval-days
181                       )=(\d+)$//x) {
182             my $vn = $1;
183             $vn =~ y/-//d;
184             die $vn unless defined ${ $::{$vn} };
185             ${ $::{$vn} } = $2;
186         } else {
187             fail "bad usage: unknown option `$_'";
188         }
189     }
190 }
191
192 !@ARGV or fail "bad usage: no non-option arguments permitted";
193
194 #---------- utility functions ----------
195
196 sub lockfile ($$$) {
197     my ($fh, $fn, $flockmode) = @_;
198     my $what = $fn.(($flockmode & ~LOCK_NB) == LOCK_SH ? " (shared)" : "");
199     for (;;) {
200         close $fh;
201         open $fh, '+>', $fn or fail "open/create $fn for lock: $!";
202         logm 'debug', "lock $what: acquiring";
203         if (!flock $fh, $flockmode) {
204             if ($flockmode & LOCK_NB && $! == EWOULDBLOCK) {
205                 return 0; # ok then
206             }
207             fail "lock $what: $!";
208         }
209         stat $fh or fail "stat opened $fn: $!";
210         my $fh_ino = ((stat _)[1]);
211         if (!stat $fn) {
212             $! == ENOENT or fail "stat $fn: $!";
213             next;
214         }
215         my $fn_ino = ((stat _)[1]);
216         if ($fn_ino == $fh_ino) {
217             logm 'debug', "lock $what: acquired";
218             return 1;
219         }
220         logm 'debug', "lock $what: deleted, need to loop again";
221         # oh dear
222     }
223 }
224
225 sub xread {
226     my $length = shift;
227     my $buffer = "";
228     while ($length > length $buffer) {
229         my $ret = sysread STDIN, $buffer, $length, length $buffer;
230         fail "expected $length bytes, got ".length $buffer
231                             if defined $ret and $ret == 0;
232         fail "read: $!" if not defined $ret and $! != EINTR and $! != EAGAIN;
233     }
234     return $buffer;
235 }
236
237 #---------- main program ----------
238
239 chdir $cachedir or fail "chdir $cachedir: $!";
240
241 our ($service,$specpath,$spechost,$subdir);
242 our ($tmpd,$gitd,$lock);
243 our ($fetch,$url);
244
245 sub servinfo ($) {
246     my ($msg) = @_;
247     logm 'info', "service `$specpath': $msg";
248 }
249
250 sub readcommand () {
251     $SIG{ALRM} = sub { fail "timeout" };
252     alarm 30;
253
254     my $hex_len = xread 4;
255     fail "Bad hex in packet length" unless $hex_len =~ m|^[0-9a-fA-F]{4}$|;
256     my $line = xread -4 + hex $hex_len;
257     unless (($service,$specpath,$spechost) = $line =~
258             m|^(git-[a-z-]+) /*([!-~ ]+)\0host=([!-~]+)\0$|) {
259         $line =~ s|[^ -~]+| |g;
260         gitfail "unknown/unsupported instruction `$line'"
261     }
262
263     alarm 0;
264
265     $service eq 'git-upload-pack'
266         or gitfail "unknown/unsupported service `$service'";
267
268     $fetch = 2; # 0:don't; 1:try; 2:force
269     $url = $specpath;
270
271     while ($url =~ s#\s+(\[)([^][{}]+)\]$## ||
272            $url =~ s#\s+(\{)([^][{}]+)\}$##) {
273         $_ = $2;
274         my $must = $1 eq '{';
275         if (m/^fetch=try$/) {
276             $fetch = 1;
277         } elsif (m/^fetch=no$/) {
278             $fetch = 0;
279         } elsif (m/^fetch=must$/) {
280             $fetch = 2; # the default
281         } elsif (m/^timeout=(\d+)$/ && $1 >= 1) {
282             $fetchtimeout = $1 <= $maxfetchtimeout ? $1 : $maxfetchtimeout;
283         } elsif ($must) {
284             gitfail "unknown/unsupported option `$_'";
285         }
286     }
287
288     $url =~ m{^(?:https?|git)://[-.0-9a-z]+/}
289         or gitfail "unknown/unsupported url scheme or format `$url'";
290
291     $subdir = $url;
292     $subdir =~ s|\\|\\\\|g;
293     $subdir =~ s|,|\\,|g;
294     $subdir =~ s|/|,|g;
295
296     $tmpd= "$subdir\\.tmp";
297     $gitd= "$subdir\\.git";
298     $lock = "$subdir\\.lock";
299
300     servinfo "locking";
301 }
302
303 sub update_gcstamp ($) {
304     my ($gitdir) = (@_);
305     my $gcdone = "$gitdir/cache-proxy-gc.stamp";
306     open GCSTAMP, '>', $gcdone or fail "create $gcdone: $!";
307     close GCSTAMP;
308 }
309
310 sub clonefetch () {
311     lockfile \*LOCK, $lock, LOCK_EX;
312
313     my $exists = lstat $gitd;
314     $exists or $!==ENOENT or fail "lstat $gitd: $!";
315
316     our $fetchfail = '';
317
318     if ($fetch) {
319
320         our @cmd;
321
322         if (!$exists) {
323             system qw(rm -rf --), $tmpd;
324             @cmd = (qw(git clone -q --mirror), $url, $tmpd);
325             servinfo "cloning";
326         } else {
327             @cmd = (qw(git remote update --prune));
328             servinfo "fetching";
329         }
330         my $cmd = "@cmd[0..1]";
331
332         my $child = open FETCHERR, "-|";
333         defined $child or fail "fork: $!";
334         if (!$child) {
335             if ($exists) {
336                 chdir $gitd or fail "chdir $gitd: $!";
337             }
338             setpgrp or fail "setpgrp: $!";
339             open STDERR, ">&STDOUT" or fail "redirect stderr: $!";
340             exec @cmd or fail "exec $cmd[0]: $!";
341         }
342
343         my $fetcherr = '';
344         my $timedout = 0;
345         {
346             local $SIG{ALRM} = sub {
347                 servinfo "fetch/clone timeout";
348                 $timedout=1; kill 9, -$child;
349             };
350             alarm($fetchtimeout);
351             $!=0; { local $/=undef; $fetcherr = <FETCHERR>; }
352             !FETCHERR->error or fail "read pipe from fetch/clone: $!";
353             alarm(10);
354         }
355
356         kill -9, $child or fail "kill fetch/clone: $!";
357         $!=0; $?=0; if (!close FETCHERR) {
358             fail "reap fetch/clone: $!" if $!;
359             my $fetchfail =
360                 !($? & 255) ? "$cmd died with error exit code ".($? >> 8) :
361                 $? != 9 ? "$cmd died due to fatal signa, status $?" :
362                 $timedout ? "$cmd timed out (${fetchtimeout}s)" :
363                 "$cmd died due to unexpected SIGKILL";
364             if (length $fetcherr) {
365                 $fetchfail .= "\n$fetcherr";
366                 $fetchfail =~ s/\n$//;
367                 $fetchfail =~ s{\n}{ // }g;
368             }
369             if ($fetch >= 2) {
370                 gitfail $fetchfail;
371             } else {
372                 servinfo "fetch/clone failed: $fetchfail";
373             }
374         }
375         alarm 0;
376
377         if (!$exists) {
378             update_gcstamp($tmpd);
379             rename $tmpd, $gitd or fail "rename fresh $tmpd to $gitd: $!";
380             $exists = 1;
381         }
382     } else {
383         $fetchfail = 'not attempted';
384     }
385
386     if (!$exists) {
387         gitfail "no cached data, and not cloned: $fetchfail";
388     }
389
390     servinfo "sharing";
391     lockfile \*LOCK, $lock, LOCK_SH; # NB releases and relocks
392
393     if (stat $gitd) {
394         return 1;
395     }
396     $!==ENOENT or fail "stat $gitd: $!";
397
398     # Well, err, someone must have taken the lock in between
399     # and garbage collected it.  How annoying.
400     return 0;
401 }
402
403 sub hkfail ($) { my ($msg) = @_; fail "housekeeping: $msg"; }
404
405 sub housekeeping () {
406     logm 'info', "housekeeping started";
407     foreach $lock (<[a-z]*\\.lock>) {
408         my $subdir = $lock;  $subdir =~ s/\\.lock$//;
409         my $gcdone = "$subdir\\.git/cache-proxy-gc.stamp";
410         if (!lstat $lock) {
411             $! == ENOENT or hkfail "$lock: lstat: $!";
412             next;
413         }
414         my ($mode_what,$mode_locknb,$mode_action);
415         if (-M _ <= $treeexpiredays) {
416             if (!lstat "$gcdone") {
417                 $! == ENOENT or hkfail "$gcdone: lstat: $!";
418                 logm 'debug',
419  "housekeeping: subdirs $subdir: touched recently, never gc'd!";
420             } elsif (-M _ <= $gcintervaldays) {
421                 logm 'debug',
422  "housekeeping: subdirs $subdir: touched recently, gc'd recently";
423                 next;
424             } else {
425                 logm 'debug',
426  "housekeeping: subdirs $subdir: touched recently, needs gc";
427             }
428             $mode_what = 'garbage collecting';
429             $mode_locknb = 0;
430             $mode_action = sub {
431                 my $gclog = "$subdir/gc.log";
432                 unlink $gclog or $!==ENOENT or hkfail "remove $gclog: $!";
433                 my $r = system qw(sh -ec),
434                     'cd "$1"; shift; exec "$@"', 'x', "$subdir\\.git",
435                     qw(git gc --quiet);
436                 if ($r) {
437                     logm 'err',
438                         "housekeeping: subdirs $subdir: gc failed (status $r)";
439                 } else {
440                     update_gcstamp("$subdir\\.git");
441                     logm 'debug',
442                         "housekeeping: subdirs $subdir: gc done";
443                 }
444             };
445         } else {
446             $mode_what = 'cleaning';
447             $mode_locknb = LOCK_NB;
448             $mode_action = sub {
449                 eval {
450                     foreach my $suffix (qw(tmp git)) {
451                         my $dir = "${subdir}\\.$suffix";
452                         my $tdir = "${subdir}\\.tmp";
453                         if ($dir ne $tdir) {
454                             if (!rename $dir,$tdir) {
455                                 next if $! == ENOENT;
456                                 die "$dir: cannot rename to $tdir: $!\n";
457                             }
458                         }
459                         system qw(rm -rf --), $tdir;
460                         if (stat $tdir) {
461  die "$dir: problem deleting file(s), rm exited $?\n";
462                         } elsif ($! != ENOENT) {
463                             die "$tdir: cannot stat after deletion: $!\n";
464                         }
465                     }
466                 };
467                 if (length $@) {
468                     chomp $@;
469  logm 'warning', "housekeeping: $subdir: cleanup prevented: $@";
470                 } else {
471                     unlink $lock or hkfail "remove $lock: $!";
472                 }
473             };
474         }
475         if (!lockfile \*LOCK, $lock, LOCK_EX|$mode_locknb) {
476             die $! unless $mode_locknb;
477             logm 'info', "housekeeping: subdirs $subdir: lock busy, skipping";
478             next;
479         }
480         logm 'info', "housekeeping: subdirs $subdir: $mode_what";
481         $mode_action->();
482     }
483     open HS, ">", "Housekeeping.stamp" or hkfail "touch Housekeeping.stamp: $!";
484     close HS or hkfail "close Housekeeping.stamp: $!";
485     logm 'info', "housekeeping finished";
486 }
487
488 sub housekeepingcheck ($$) {
489     my ($dofork, $force) = @_;
490     if (!$force) {
491         if (!lockfile \*HLOCK, "Housekeeping.lock", LOCK_EX|LOCK_NB) {
492             logm 'debug', "housekeeping lock taken, not running";
493             close HLOCK;
494             return 0;
495         }
496     }
497     if ($force) {
498         logm 'info', "housekeeping forced";
499     } elsif (!lstat "Housekeeping.stamp") {
500         $! == ENOENT or fail "lstat Housekeeping.stamp: $!";
501         logm 'info', "housekeeping not done yet, will run";
502     } elsif (-M _ <= $housekeepingeverydays) {
503         logm 'debug', "housekeeping done recently";
504         close HLOCK;
505         return 0;
506     }
507     if ($dofork) {
508         my $child = fork;
509         defined $child or fail "fork: $!";
510         if (!$child) {
511             open STDERR, "|logger -p daemon.warning -t '$us(housekeeping)'"
512                 or die "fork: logger $!";
513             housekeeping();
514             exit 0;
515         }
516     } else {
517         housekeeping();
518     }
519     close HLOCK;
520     return 1;
521 }
522
523 sub runcommand () {
524     servinfo "serving";
525
526     chdir $gitd or fail "chdir $gitd: $!";
527
528     exec qw(git-upload-pack --strict), "--timeout=$servetimeout", qw(.)
529         or fail "exec git-upload-pack: $!";
530 }
531
532 sub daemonservice () {
533     readcommand();
534     while (!clonefetch()) { }
535     housekeepingcheck(1,0);
536     runcommand();
537 }
538
539 if ($housekeepingonly) {
540     housekeepingcheck(0, $housekeepingonly>=2);
541 } else {
542     daemonservice();
543 }