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
33 # Copyright 2017 Citrix
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.
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.
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.
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+.)
60 use Fcntl qw(:flock SEEK_SET);
61 use File::Path qw(remove_tree);
63 our $us = 'git-cache-proxy';
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;
73 #---------- error handling and logging ----------
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
79 our $log; # filehandle (ref), or "1" meaning syslog
83 return ('(local)') unless defined $sockaddr;
84 my ($port,$addr) = sockaddr_in $sockaddr;
85 $addr = inet_ntoa $addr;
86 return ("[$addr]:$port",$addr,$port);
89 our ($client) = ntoa getpeername STDIN;
90 our ($server) = ntoa getsockname STDIN;
94 openlog $us, qw(pid), 'daemon';
100 return if $pri eq 'debug' && !$debug;
101 if ($client eq '(local)') {
102 print STDERR "$us: $pri: $msg\n" or die $!;
106 my $mainmsg = sprintf "%s-%s: %s", $server, $client, $msg;
108 my $wholemsg = sprintf("%s [%d] %s: %s\n",
109 strftime("%Y-%m-%d %H:%M:%S Z", gmtime),
111 $pri eq 'err' ? 'error' : $pri,
113 print $log $wholemsg;
115 syslog $pri, "%s", "$pri $mainmsg";
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;
126 if ($client ne '(local)') {
127 if ($?) { logm 'crit', "crashing ($?)"; }
128 seek TEMPERR, 0, SEEK_SET;
148 my $gitmsg = "ERR $us: $msg";
149 $gitmsg = substr($gitmsg,0,65535); # just in case
150 printf "%04x%s", length($gitmsg)+4, $gitmsg;
155 #---------- argument parsing ----------
159 last unless $ARGV[0] =~ m/^-/;
167 } elsif (s/^-L(.*)$//) {
169 open STDERR, ">>", $logfile or fail "open $logfile: $!";
171 } elsif (s/^-d(.*)$//) {
173 } elsif (s/^--( max-fetch-timeout
176 | housekeeping-interval-days
180 die $vn unless defined ${ $::{$vn} };
183 fail "bad usage: unknown option `$_'";
188 !@ARGV or fail "bad usage: no non-option arguments permitted";
190 #---------- utility functions ----------
193 my ($fh, $fn, $flockmode) = @_;
194 my $what = $fn.(($flockmode & ~LOCK_NB) == LOCK_SH ? " (shared)" : "");
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) {
203 fail "lock $what: $!";
205 stat $fh or fail "stat opened $fn: $!";
206 my $fh_ino = ((stat _)[1]);
208 $! == ENOENT or fail "stat $fn: $!";
211 my $fn_ino = ((stat _)[1]);
212 if ($fn_ino == $fh_ino) {
213 logm 'debug', "lock $what: acquired";
216 logm 'debug', "lock $what: deleted, need to loop again";
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;
233 #---------- main program ----------
235 chdir $cachedir or fail "chdir $cachedir: $!";
237 our ($service,$specpath,$spechost,$subdir);
238 our ($tmpd,$gitd,$lock);
243 logm 'info', "service `$specpath': $msg";
247 $SIG{ALRM} = sub { fail "timeout" };
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'"
261 $service eq 'git-upload-pack'
262 or gitfail "unknown/unsupported service `$service'";
264 $fetch = 2; # 0:don't; 1:try; 2:force
267 while ($url =~ s#\s+(\[)([^][{}]+)\]$## ||
268 $url =~ s#\s+(\{)([^][{}]+)\}$##) {
270 my $must = $1 eq '{';
271 if (m/^fetch=try$/) {
273 } elsif (m/^fetch=no$/) {
275 } elsif (m/^fetch=must$/) {
276 $fetch = 2; # the default
277 } elsif (m/^timeout=(\d+)$/ && $1 >= 1) {
278 $fetchtimeout = $1 <= $maxfetchtimeout ? $1 : $maxfetchtimeout;
280 gitfail "unknown/unsupported option `$_'";
284 $url =~ m{^(?:https?|git)://[-.0-9a-z]+/}
285 or gitfail "unknown/unsupported url scheme or format `$url'";
288 $subdir =~ s|\\|\\\\|g;
289 $subdir =~ s|,|\\,|g;
292 $tmpd= "$subdir\\.tmp";
293 $gitd= "$subdir\\.git";
294 $lock = "$subdir\\.lock";
300 lockfile \*LOCK, $lock, LOCK_EX;
302 my $exists = lstat $gitd;
303 $exists or $!==ENOENT or fail "lstat $gitd: $!";
312 system qw(rm -rf --), $tmpd;
313 @cmd = (qw(git clone -q --mirror), $url, $tmpd);
316 @cmd = (qw(git remote update --prune));
319 my $cmd = "@cmd[0..1]";
321 my $child = open FETCHERR, "-|";
322 defined $child or fail "fork: $!";
325 chdir $gitd or fail "chdir $gitd: $!";
327 setpgrp or fail "setpgrp: $!";
328 open STDERR, ">&STDOUT" or fail "redirect stderr: $!";
329 exec @cmd or fail "exec $cmd[0]: $!";
335 local $SIG{ALRM} = sub {
336 servinfo "fetch/clone timeout";
337 $timedout=1; kill 9, -$child;
339 alarm($fetchtimeout);
340 $!=0; { local $/=undef; $fetcherr = <FETCHERR>; }
341 !FETCHERR->error or fail "read pipe from fetch/clone: $!";
345 kill -9, $child or fail "kill fetch/clone: $!";
346 $!=0; $?=0; if (!close FETCHERR) {
347 fail "reap fetch/clone: $!" if $!;
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;
361 servinfo "fetch/clone failed: $fetchfail";
367 rename $tmpd, $gitd or fail "rename fresh $tmpd to $gitd: $!";
371 $fetchfail = 'not attempted';
375 gitfail "no cached data, and not cloned: $fetchfail";
379 lockfile \*LOCK, $lock, LOCK_SH; # NB releases and relocks
384 $!==ENOENT or fail "stat $gitd: $!";
386 # Well, err, someone must have taken the lock in between
387 # and garbage collected it. How annoying.
391 sub hkfail ($) { my ($msg) = @_; fail "housekeeping: $msg"; }
393 sub housekeeping () {
394 logm 'info', "housekeeping started";
395 foreach $lock (<[a-z]*\\.lock>) {
396 my $subdir = $lock; $subdir =~ s/\\.lock$//;
398 $! == ENOENT or hkfail "$lock: lstat: $!";
401 if (-M _ <= $treeexpiredays) {
402 logm 'debug', "housekeeping: subdirs $subdir: touched recently";
405 if (!lockfile \*LOCK, $lock, LOCK_EX|LOCK_NB) {
406 logm 'info', "housekeeping: subdirs $subdir: lock busy, skipping";
409 logm 'info', "housekeeping: subdirs $subdir: cleaning";
411 foreach my $suffix (qw(tmp git)) {
412 my $dir = "${subdir}\\.$suffix";
413 my $tdir = "${subdir}\\.tmp";
415 if (!rename $dir,$tdir) {
416 next if $! == ENOENT;
417 die "$dir: cannot rename to $tdir: $!\n";
420 system qw(rm -rf --), $tdir;
422 die "$dir: problem deleting file(s), rm exited $?\n";
423 } elsif ($! != ENOENT) {
424 die "$tdir: cannot stat after deletion: $!\n";
430 logm 'warning', "housekeeping: $subdir: cleanup prevented: $@";
432 unlink $lock or hkfail "remove $lock: $!";
435 open HS, ">", "Housekeeping.stamp" or hkfail "touch Housekeeping.stamp: $!";
436 close HS or hkfail "close Housekeeping.stamp: $!";
437 logm 'info', "housekeeping finished";
440 sub housekeepingcheck ($$) {
441 my ($dofork, $force) = @_;
443 if (!lockfile \*HLOCK, "Housekeeping.lock", LOCK_EX|LOCK_NB) {
444 logm 'debug', "housekeeping lock taken, not running";
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";
461 defined $child or fail "fork: $!";
463 open STDERR, "|logger -p daemon.warning -t '$us(housekeeping)'"
464 or die "fork: logger $!";
478 chdir $gitd or fail "chdir $gitd: $!";
480 exec qw(git-upload-pack --strict --timeout=1000 .)
481 or fail "exec git-upload-pack: $!";
484 sub daemonservice () {
486 while (!clonefetch()) { }
487 housekeepingcheck(1,0);
491 if ($housekeepingonly) {
492 housekeepingcheck(0, $housekeepingonly>=2);