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 $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;
75 #---------- error handling and logging ----------
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
81 our $log; # filehandle (ref), or "1" meaning syslog
85 return ('(local)') unless defined $sockaddr;
86 my ($port,$addr) = sockaddr_in $sockaddr;
87 $addr = inet_ntoa $addr;
88 return ("[$addr]:$port",$addr,$port);
91 our ($client) = ntoa getpeername STDIN;
92 our ($server) = ntoa getsockname STDIN;
96 openlog $us, qw(pid), 'daemon';
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 $!;
108 my $mainmsg = sprintf "%s-%s: %s", $server, $client, $msg;
110 my $wholemsg = sprintf("%s [%d] %s: %s\n",
111 strftime("%Y-%m-%d %H:%M:%S Z", gmtime),
113 $pri eq 'err' ? 'error' : $pri,
115 print $log $wholemsg;
117 syslog $pri, "%s", "$pri $mainmsg";
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;
128 if ($client ne '(local)') {
129 if ($?) { logm 'crit', "crashing ($?)"; }
130 seek TEMPERR, 0, SEEK_SET;
150 my $gitmsg = "ERR $us: $msg";
151 $gitmsg = substr($gitmsg,0,65535); # just in case
152 printf "%04x%s", length($gitmsg)+4, $gitmsg;
157 #---------- argument parsing ----------
161 last unless $ARGV[0] =~ m/^-/;
169 } elsif (s/^-L(.*)$//) {
171 open STDERR, ">>", $logfile or fail "open $logfile: $!";
173 } elsif (s/^-d(.*)$//) {
175 } elsif (s/^--( max-fetch-timeout
179 | housekeeping-interval-days
184 die $vn unless defined ${ $::{$vn} };
187 fail "bad usage: unknown option `$_'";
192 !@ARGV or fail "bad usage: no non-option arguments permitted";
194 #---------- utility functions ----------
197 my ($fh, $fn, $flockmode) = @_;
198 my $what = $fn.(($flockmode & ~LOCK_NB) == LOCK_SH ? " (shared)" : "");
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) {
207 fail "lock $what: $!";
209 stat $fh or fail "stat opened $fn: $!";
210 my $fh_ino = ((stat _)[1]);
212 $! == ENOENT or fail "stat $fn: $!";
215 my $fn_ino = ((stat _)[1]);
216 if ($fn_ino == $fh_ino) {
217 logm 'debug', "lock $what: acquired";
220 logm 'debug', "lock $what: deleted, need to loop again";
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;
237 #---------- main program ----------
239 chdir $cachedir or fail "chdir $cachedir: $!";
241 our ($service,$specpath,$spechost,$subdir);
242 our ($tmpd,$gitd,$lock);
247 logm 'info', "service `$specpath': $msg";
251 $SIG{ALRM} = sub { fail "timeout" };
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'"
265 $service eq 'git-upload-pack'
266 or gitfail "unknown/unsupported service `$service'";
268 $fetch = 2; # 0:don't; 1:try; 2:force
271 while ($url =~ s#\s+(\[)([^][{}]+)\]$## ||
272 $url =~ s#\s+(\{)([^][{}]+)\}$##) {
274 my $must = $1 eq '{';
275 if (m/^fetch=try$/) {
277 } elsif (m/^fetch=no$/) {
279 } elsif (m/^fetch=must$/) {
280 $fetch = 2; # the default
281 } elsif (m/^timeout=(\d+)$/ && $1 >= 1) {
282 $fetchtimeout = $1 <= $maxfetchtimeout ? $1 : $maxfetchtimeout;
284 gitfail "unknown/unsupported option `$_'";
288 $url =~ m{^(?:https?|git)://[-.0-9a-z]+/}
289 or gitfail "unknown/unsupported url scheme or format `$url'";
292 $subdir =~ s|\\|\\\\|g;
293 $subdir =~ s|,|\\,|g;
296 $tmpd= "$subdir\\.tmp";
297 $gitd= "$subdir\\.git";
298 $lock = "$subdir\\.lock";
303 sub update_gcstamp ($) {
305 my $gcdone = "$gitdir/cache-proxy-gc.stamp";
306 open GCSTAMP, '>', $gcdone or fail "create $gcdone: $!";
311 lockfile \*LOCK, $lock, LOCK_EX;
313 my $exists = lstat $gitd;
314 $exists or $!==ENOENT or fail "lstat $gitd: $!";
323 system qw(rm -rf --), $tmpd;
324 @cmd = (qw(git clone -q --mirror), $url, $tmpd);
327 @cmd = (qw(git remote update --prune));
330 my $cmd = "@cmd[0..1]";
332 my $child = open FETCHERR, "-|";
333 defined $child or fail "fork: $!";
336 chdir $gitd or fail "chdir $gitd: $!";
338 setpgrp or fail "setpgrp: $!";
339 open STDERR, ">&STDOUT" or fail "redirect stderr: $!";
340 exec @cmd or fail "exec $cmd[0]: $!";
346 local $SIG{ALRM} = sub {
347 servinfo "fetch/clone timeout";
348 $timedout=1; kill 9, -$child;
350 alarm($fetchtimeout);
351 $!=0; { local $/=undef; $fetcherr = <FETCHERR>; }
352 !FETCHERR->error or fail "read pipe from fetch/clone: $!";
356 kill -9, $child or fail "kill fetch/clone: $!";
357 $!=0; $?=0; if (!close FETCHERR) {
358 fail "reap fetch/clone: $!" if $!;
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;
372 servinfo "fetch/clone failed: $fetchfail";
378 update_gcstamp($tmpd);
379 rename $tmpd, $gitd or fail "rename fresh $tmpd to $gitd: $!";
383 $fetchfail = 'not attempted';
387 gitfail "no cached data, and not cloned: $fetchfail";
391 lockfile \*LOCK, $lock, LOCK_SH; # NB releases and relocks
396 $!==ENOENT or fail "stat $gitd: $!";
398 # Well, err, someone must have taken the lock in between
399 # and garbage collected it. How annoying.
403 sub hkfail ($) { my ($msg) = @_; fail "housekeeping: $msg"; }
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";
411 $! == ENOENT or hkfail "$lock: lstat: $!";
414 my ($mode_what,$mode_locknb,$mode_action);
415 if (-M _ <= $treeexpiredays) {
416 if (!lstat "$gcdone") {
417 $! == ENOENT or hkfail "$gcdone: lstat: $!";
419 "housekeeping: subdirs $subdir: touched recently, never gc'd!";
420 } elsif (-M _ <= $gcintervaldays) {
422 "housekeeping: subdirs $subdir: touched recently, gc'd recently";
426 "housekeeping: subdirs $subdir: touched recently, needs gc";
428 $mode_what = 'garbage collecting';
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",
438 "housekeeping: subdirs $subdir: gc failed (status $r)";
440 update_gcstamp("$subdir\\.git");
442 "housekeeping: subdirs $subdir: gc done";
446 $mode_what = 'cleaning';
447 $mode_locknb = LOCK_NB;
450 foreach my $suffix (qw(tmp git)) {
451 my $dir = "${subdir}\\.$suffix";
452 my $tdir = "${subdir}\\.tmp";
454 if (!rename $dir,$tdir) {
455 next if $! == ENOENT;
456 die "$dir: cannot rename to $tdir: $!\n";
459 system qw(rm -rf --), $tdir;
461 die "$dir: problem deleting file(s), rm exited $?\n";
462 } elsif ($! != ENOENT) {
463 die "$tdir: cannot stat after deletion: $!\n";
469 logm 'warning', "housekeeping: $subdir: cleanup prevented: $@";
471 unlink $lock or hkfail "remove $lock: $!";
475 if (!lockfile \*LOCK, $lock, LOCK_EX|$mode_locknb) {
476 die $! unless $mode_locknb;
477 logm 'info', "housekeeping: subdirs $subdir: lock busy, skipping";
480 logm 'info', "housekeeping: subdirs $subdir: $mode_what";
483 open HS, ">", "Housekeeping.stamp" or hkfail "touch Housekeeping.stamp: $!";
484 close HS or hkfail "close Housekeeping.stamp: $!";
485 logm 'info', "housekeeping finished";
488 sub housekeepingcheck ($$) {
489 my ($dofork, $force) = @_;
491 if (!lockfile \*HLOCK, "Housekeeping.lock", LOCK_EX|LOCK_NB) {
492 logm 'debug', "housekeeping lock taken, not running";
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";
509 defined $child or fail "fork: $!";
511 open STDERR, "|logger -p daemon.warning -t '$us(housekeeping)'"
512 or die "fork: logger $!";
526 chdir $gitd or fail "chdir $gitd: $!";
528 exec qw(git-upload-pack --strict), "--timeout=$servetimeout", qw(.)
529 or fail "exec git-upload-pack: $!";
532 sub daemonservice () {
534 while (!clonefetch()) { }
535 housekeepingcheck(1,0);
539 if ($housekeepingonly) {
540 housekeepingcheck(0, $housekeepingonly>=2);