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).
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
23 # example inetd.conf line:
24 # 9419 stream tcp nowait git-cache /usr/bin/git-cache-proxy git-cache-proxy
27 # mkdir /var/cache/git-cache-proxy
28 # chown git-cache /var/cache/git-cache-proxy
31 # Copyright 2010 Tony Finch
32 # Copyright 2013,2014 Ian Jackson
34 # git-cache-proxy is free software; you can redistribute it and/or
35 # modify them under the terms of the GNU General Public License as
36 # published by the Free Software Foundation; either version 3, or (at
37 # your option) any later version.
39 # git-cache-proxy is distributed in the hope that it will be useful,
40 # but WITHOUT ANY WARRANTY; without even the implied warranty of
41 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
42 # General Public License for more details.
44 # You should have received a copy of the GNU General Public License along
45 # with this program; if not, consult the Free Software Foundation's
46 # website at www.fsf.org, or the GNU Project website at www.gnu.org.
48 # (Some code taken from userv-utils's git-daemon.in and git-service.in
49 # which were written by Tony Finch <dot@dotat.at> and subsequently
50 # heavily modified by Ian Jackson <ijackson@chiark.greenend.org.uk>
51 # and were released under CC0 1.0. The whole program is now GPLv3+.)
59 use Fcntl qw(:flock SEEK_SET);
60 use File::Path qw(remove_tree);
62 our $us = 'git-cache-proxy';
65 our $housekeepingeverydays = 1;
66 our $treeexpiredays = 21;
67 our $fetchtimeout = 1800;
68 our $maxfetchtimeout = 3600;
69 our $cachedir = '/var/cache/git-cache-proxy';
70 our $housekeepingonly = 0;
72 #---------- error handling and logging ----------
74 # This is a bit fiddly, because we want to catch errors sent to stderr
75 # and dump them to syslog if we can, but only if we are running as an
78 our $log; # filehandle (ref), or "1" meaning syslog
82 return ('(local)') unless defined $sockaddr;
83 my ($port,$addr) = sockaddr_in $sockaddr;
84 $addr = inet_ntoa $addr;
85 return ("[$addr]:$port",$addr,$port);
88 our ($client) = ntoa getpeername STDIN;
89 our ($server) = ntoa getsockname STDIN;
93 openlog $us, qw(pid), 'daemon';
99 return if $pri eq 'debug' && !$debug;
100 if ($client eq '(local)') {
101 print STDERR "$us: $pri: $msg\n" or die $!;
105 my $mainmsg = sprintf "%s-%s: %s", $server, $client, $msg;
107 my $wholemsg = sprintf("%s [%d] %s: %s\n",
108 strftime("%Y-%m-%d %H:%M:%S Z", gmtime),
110 $pri eq 'err' ? 'error' : $pri,
112 print $log $wholemsg;
114 syslog $pri, "%s", "$pri $mainmsg";
118 if ($client ne '(local)') {
119 open STDERR, ">/dev/null" or exit 255;
120 open TEMPERR, "+>", undef or exit 255;
121 open STDERR, ">&TEMPERR" or exit 255;
125 if ($client ne '(local)') {
126 if ($?) { logm 'crit', "crashing ($?)"; }
127 seek TEMPERR, 0, SEEK_SET;
147 my $gitmsg = "ERR $us: $msg";
148 $gitmsg = substr($gitmsg,0,65535); # just in case
149 printf "%04x%s", length($gitmsg)+4, $gitmsg;
154 #---------- argument parsing ----------
158 last unless $ARGV[0] =~ m/^-/;
166 } elsif (s/^-L(.*)$//) {
168 open STDERR, ">>", $logfile or fail "open $logfile: $!";
170 } elsif (s/^-d(.*)$//) {
172 } elsif (s/^--( max-fetch-timeout
175 | housekeeping-interval-days
179 die $vn unless defined ${ $::{$vn} };
182 fail "bad usage: unknown option `$_'";
187 !@ARGV or fail "bad usage: no non-option arguments permitted";
189 #---------- utility functions ----------
192 my ($fh, $fn, $flockmode) = @_;
193 my $what = $fn.(($flockmode & ~LOCK_NB) == LOCK_SH ? " (shared)" : "");
196 open $fh, '+>', $fn or fail "open/create $fn for lock: $!";
197 logm 'debug', "lock $what: acquiring";
198 if (!flock $fh, $flockmode) {
199 if ($flockmode & LOCK_NB && $! == EWOULDBLOCK) {
202 fail "lock $what: $!";
204 stat $fh or fail "stat opened $fn: $!";
205 my $fh_ino = ((stat _)[1]);
207 $! == ENOENT or fail "stat $fn: $!";
210 my $fn_ino = ((stat _)[1]);
211 if ($fn_ino == $fh_ino) {
212 logm 'debug', "lock $what: acquired";
215 logm 'debug', "lock $what: deleted, need to loop again";
223 while ($length > length $buffer) {
224 my $ret = sysread STDIN, $buffer, $length, length $buffer;
225 fail "expected $length bytes, got ".length $buffer
226 if defined $ret and $ret == 0;
227 fail "read: $!" if not defined $ret and $! != EINTR and $! != EAGAIN;
232 #---------- main program ----------
234 chdir $cachedir or fail "chdir $cachedir: $!";
236 our ($service,$specpath,$spechost,$subdir);
237 our ($tmpd,$gitd,$lock);
242 logm 'info', "service `$specpath': $msg";
246 $SIG{ALRM} = sub { fail "timeout" };
249 my $hex_len = xread 4;
250 fail "Bad hex in packet length" unless $hex_len =~ m|^[0-9a-fA-F]{4}$|;
251 my $line = xread -4 + hex $hex_len;
252 unless (($service,$specpath,$spechost) = $line =~
253 m|^(git-[a-z-]+) /*([!-~ ]+)\0host=([!-~]+)\0$|) {
254 $line =~ s|[^ -~]+| |g;
255 gitfail "unknown/unsupported instruction `$line'"
260 $service eq 'git-upload-pack'
261 or gitfail "unknown/unsupported service `$service'";
263 $fetch = 2; # 0:don't; 1:try; 2:force
266 while ($url =~ s#\s+(\[)([^][{}]+)\]$## ||
267 $url =~ s#\s+(\{)([^][{}]+)\}$##) {
269 my $must = $1 eq '{';
270 if (m/^fetch=try$/) {
272 } elsif (m/^fetch=no$/) {
274 } elsif (m/^fetch=must$/) {
275 $fetch = 2; # the default
276 } elsif (m/^timeout=(\d+)$/ && $1 >= 1) {
277 $fetchtimeout = $1 <= $maxfetchtimeout ? $1 : $maxfetchtimeout;
279 gitfail "unknown/unsupported option `$_'";
283 $url =~ m{^(?:https?|git)://[-.0-9a-z]+/}
284 or gitfail "unknown/unsupported url scheme or format `$url'";
287 $subdir =~ s|\\|\\\\|g;
288 $subdir =~ s|,|\\,|g;
291 $tmpd= "$subdir\\.tmp";
292 $gitd= "$subdir\\.git";
293 $lock = "$subdir\\.lock";
299 lockfile \*LOCK, $lock, LOCK_EX;
301 my $exists = lstat $gitd;
302 $exists or $!==ENOENT or fail "lstat $gitd: $!";
311 system qw(rm -rf --), $tmpd;
312 @cmd = (qw(git clone -q --mirror), $url, $tmpd);
315 @cmd = (qw(git remote update --prune));
318 my $cmd = "@cmd[0..1]";
320 my $child = open FETCHERR, "-|";
321 defined $child or fail "fork: $!";
324 chdir $gitd or fail "chdir $gitd: $!";
326 setpgrp or fail "setpgrp: $!";
327 open STDERR, ">&STDOUT" or fail "redirect stderr: $!";
328 exec @cmd or fail "exec $cmd[0]: $!";
334 local $SIG{ALRM} = sub {
335 servinfo "fetch/clone timeout";
336 $timedout=1; kill 9, -$child;
338 alarm($fetchtimeout);
339 $!=0; { local $/=undef; $fetcherr = <FETCHERR>; }
340 !FETCHERR->error or fail "read pipe from fetch/clone: $!";
344 kill -9, $child or fail "kill fetch/clone: $!";
345 $!=0; $?=0; if (!close FETCHERR) {
346 fail "reap fetch/clone: $!" if $!;
348 !($? & 255) ? "$cmd died with error exit code ".($? >> 8) :
349 $? != 9 ? "$cmd died due to fatal signa, status $?" :
350 $timedout ? "$cmd timed out (${fetchtimeout}s)" :
351 "$cmd died due to unexpected SIGKILL";
352 if (length $fetcherr) {
353 $fetchfail .= "\n$fetcherr";
354 $fetchfail =~ s/\n$//;
355 $fetchfail =~ s{\n}{ // }g;
360 servinfo "fetch/clone failed: $fetchfail";
365 rename $tmpd, $gitd or fail "rename fresh $tmpd to $gitd: $!";
369 $fetchfail = 'not attempted';
373 gitfail "no cached data, and not cloned: $fetchfail";
377 lockfile \*LOCK, $lock, LOCK_SH; # NB releases and relocks
382 $!==ENOENT or fail "stat $gitd: $!";
384 # Well, err, someone must have taken the lock in between
385 # and garbage collected it. How annoying.
389 sub hkfail ($) { my ($msg) = @_; fail "housekeeping: $msg"; }
391 sub housekeeping () {
392 logm 'info', "housekeeping started";
393 foreach $lock (<[a-z]*\\.lock>) {
394 my $subdir = $lock; $subdir =~ s/\\.lock$//;
396 $! == ENOENT or hkfail "$lock: lstat: $!";
399 if (-M _ <= $treeexpiredays) {
400 logm 'debug', "housekeeping: subdirs $subdir: touched recently";
403 if (!lockfile \*LOCK, $lock, LOCK_EX|LOCK_NB) {
404 logm 'info', "housekeeping: subdirs $subdir: lock busy, skipping";
407 logm 'info', "housekeeping: subdirs $subdir: cleaning";
409 foreach my $suffix (qw(tmp git)) {
410 my $dir = "${subdir}\\.$suffix";
411 my $tdir = "${subdir}\\.tmp";
413 if (!rename $dir,$tdir) {
414 next if $! == ENOENT;
415 die "$dir: cannot rename to $tdir: $!\n";
418 system qw(rm -rf --), $tdir;
420 die "$dir: problem deleting file(s), rm exited $?\n";
421 } elsif ($! != ENOENT) {
422 die "$tdir: cannot stat after deletion: $!\n";
428 logm 'warning', "housekeeping: $subdir: cleanup prevented: $@";
430 unlink $lock or hkfail "remove $lock: $!";
433 open HS, ">", "Housekeeping.stamp" or hkfail "touch Housekeeping.stamp: $!";
434 close HS or hkfail "close Housekeeping.stamp: $!";
435 logm 'info', "housekeeping finished";
438 sub housekeepingcheck ($$) {
439 my ($dofork, $force) = @_;
441 if (!lockfile \*HLOCK, "Housekeeping.lock", LOCK_EX|LOCK_NB) {
442 logm 'debug', "housekeeping lock taken, not running";
448 logm 'info', "housekeeping forced";
449 } elsif (!lstat "Housekeeping.stamp") {
450 $! == ENOENT or fail "lstat Housekeeping.stamp: $!";
451 logm 'info', "housekeeping not done yet, will run";
452 } elsif (-M _ <= $housekeepingeverydays) {
453 logm 'debug', "housekeeping done recently";
459 defined $child or fail "fork: $!";
461 open STDERR, "|logger -p daemon.warning -t '$us(housekeeping)'"
462 or die "fork: logger $!";
476 chdir $gitd or fail "chdir $gitd: $!";
478 exec qw(git-upload-pack --strict --timeout=1000 .)
479 or fail "exec git-upload-pack: $!";
482 sub daemonservice () {
484 while (!clonefetch()) { }
485 housekeepingcheck(1,0);
489 if ($housekeepingonly) {
490 housekeepingcheck(0, $housekeepingonly>=2);