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