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
22 # housekeeping-interval-days=<integer> } housekeeping tuning parameters
23 # tree-expire-days=<integer> }
24 # gc-interval-days=<integer> }
26 # example inetd.conf line:
27 # 9419 stream tcp nowait git-cache /usr/bin/git-cache-proxy git-cache-proxy
30 # mkdir /var/cache/git-cache-proxy
31 # chown git-cache /var/cache/git-cache-proxy
34 # Copyright 2010 Tony Finch
35 # Copyright 2013,2014 Ian Jackson
36 # Copyright 2017 Citrix
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.
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.
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.
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+.)
63 use Fcntl qw(:flock SEEK_SET);
64 use File::Path qw(remove_tree);
66 our $us = 'git-cache-proxy';
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;
78 #---------- error handling and logging ----------
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
84 our $log; # filehandle (ref), or "1" meaning syslog
88 return ('(local)') unless defined $sockaddr;
89 my ($port,$addr) = sockaddr_in $sockaddr;
90 $addr = inet_ntoa $addr;
91 return ("[$addr]:$port",$addr,$port);
94 our ($client) = ntoa getpeername STDIN;
95 our ($server) = ntoa getsockname STDIN;
99 openlog $us, qw(pid), 'daemon';
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 $!;
111 my $mainmsg = sprintf "%s-%s: %s", $server, $client, $msg;
113 my $wholemsg = sprintf("%s [%d] %s: %s\n",
114 strftime("%Y-%m-%d %H:%M:%S Z", gmtime),
116 $pri eq 'err' ? 'error' : $pri,
118 print $log $wholemsg;
120 syslog $pri, "%s", "$pri $mainmsg";
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;
131 if ($client ne '(local)') {
132 if ($?) { logm 'crit', "crashing ($?)"; }
133 seek TEMPERR, 0, SEEK_SET;
153 my $gitmsg = "ERR $us: $msg";
154 $gitmsg = substr($gitmsg,0,65535); # just in case
155 printf "%04x%s", length($gitmsg)+4, $gitmsg;
160 #---------- argument parsing ----------
164 last unless $ARGV[0] =~ m/^-/;
172 } elsif (s/^-L(.*)$//) {
174 open STDERR, ">>", $logfile or fail "open $logfile: $!";
176 } elsif (s/^-d(.*)$//) {
178 } elsif (s/^--( max-fetch-timeout
182 | housekeeping-interval-days
187 die $vn unless defined ${ $::{$vn} };
190 fail "bad usage: unknown option `$_'";
195 !@ARGV or fail "bad usage: no non-option arguments permitted";
197 #---------- utility functions ----------
200 my ($fh, $fn, $flockmode) = @_;
201 my $what = $fn.(($flockmode & ~LOCK_NB) == LOCK_SH ? " (shared)" : "");
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) {
210 fail "lock $what: $!";
212 stat $fh or fail "stat opened $fn: $!";
213 my $fh_ino = ((stat _)[1]);
215 $! == ENOENT or fail "stat $fn: $!";
218 my $fn_ino = ((stat _)[1]);
219 if ($fn_ino == $fh_ino) {
220 logm 'debug', "lock $what: acquired";
223 logm 'debug', "lock $what: deleted, need to loop again";
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;
240 #---------- main program ----------
242 chdir $cachedir or fail "chdir $cachedir: $!";
244 our ($service,$specpath,$spechost,$subdir);
245 our ($tmpd,$gitd,$lock);
250 logm 'info', "service `$specpath': $msg";
254 $SIG{ALRM} = sub { fail "timeout" };
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'"
268 $service eq 'git-upload-pack'
269 or gitfail "unknown/unsupported service `$service'";
271 $fetch = 2; # 0:don't; 1:try; 2:force
274 while ($url =~ s#\s+(\[)([^][{}]+)\]$## ||
275 $url =~ s#\s+(\{)([^][{}]+)\}$##) {
277 my $must = $1 eq '{';
278 if (m/^fetch=try$/) {
280 } elsif (m/^fetch=no$/) {
282 } elsif (m/^fetch=must$/) {
283 $fetch = 2; # the default
284 } elsif (m/^timeout=(\d+)$/ && $1 >= 1) {
285 $fetchtimeout = $1 <= $maxfetchtimeout ? $1 : $maxfetchtimeout;
287 gitfail "unknown/unsupported option `$_'";
291 $url =~ m{^(?:https?|git)://[-.0-9a-z]+/}
292 or gitfail "unknown/unsupported url scheme or format `$url'";
295 $subdir =~ s|\\|\\\\|g;
296 $subdir =~ s|,|\\,|g;
299 $tmpd= "$subdir\\.tmp";
300 $gitd= "$subdir\\.git";
301 $lock = "$subdir\\.lock";
306 sub update_gcstamp ($) {
308 my $gcdone = "$gitdir/cache-proxy-gc.stamp";
309 open GCSTAMP, '>', $gcdone or fail "create $gcdone: $!";
314 lockfile \*LOCK, $lock, LOCK_EX;
316 my $exists = lstat $gitd;
317 $exists or $!==ENOENT or fail "lstat $gitd: $!";
326 system qw(rm -rf --), $tmpd;
327 @cmd = (qw(git clone -q --mirror), $url, $tmpd);
330 @cmd = (qw(git remote update --prune));
333 my $cmd = "@cmd[0..1]";
335 my $child = open FETCHERR, "-|";
336 defined $child or fail "fork: $!";
339 chdir $gitd or fail "chdir $gitd: $!";
341 setpgrp or fail "setpgrp: $!";
342 open STDERR, ">&STDOUT" or fail "redirect stderr: $!";
343 exec @cmd or fail "exec $cmd[0]: $!";
349 local $SIG{ALRM} = sub {
350 servinfo "fetch/clone timeout";
351 $timedout=1; kill 9, -$child;
353 alarm($fetchtimeout);
354 $!=0; { local $/=undef; $fetcherr = <FETCHERR>; }
355 !FETCHERR->error or fail "read pipe from fetch/clone: $!";
359 kill -9, $child or fail "kill fetch/clone: $!";
360 $!=0; $?=0; if (!close FETCHERR) {
361 fail "reap fetch/clone: $!" if $!;
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;
375 servinfo "fetch/clone failed: $fetchfail";
381 update_gcstamp($tmpd);
382 rename $tmpd, $gitd or fail "rename fresh $tmpd to $gitd: $!";
386 $fetchfail = 'not attempted';
390 gitfail "no cached data, and not cloned: $fetchfail";
394 lockfile \*LOCK, $lock, LOCK_SH; # NB releases and relocks
399 $!==ENOENT or fail "stat $gitd: $!";
401 # Well, err, someone must have taken the lock in between
402 # and garbage collected it. How annoying.
406 sub hkfail ($) { my ($msg) = @_; fail "housekeeping: $msg"; }
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";
414 $! == ENOENT or hkfail "$lock: lstat: $!";
417 my ($mode_what,$mode_locknb,$mode_action);
418 if (-M _ <= $treeexpiredays) {
419 if (!lstat "$gcdone") {
420 $! == ENOENT or hkfail "$gcdone: lstat: $!";
422 "housekeeping: subdirs $subdir: touched recently, never gc'd!";
423 } elsif (-M _ <= $gcintervaldays) {
425 "housekeeping: subdirs $subdir: touched recently, gc'd recently";
429 "housekeeping: subdirs $subdir: touched recently, needs gc";
431 $mode_what = 'garbage collecting';
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",
441 "housekeeping: subdirs $subdir: gc failed (status $r)";
443 update_gcstamp("$subdir\\.git");
445 "housekeeping: subdirs $subdir: gc done";
449 $mode_what = 'cleaning';
450 $mode_locknb = LOCK_NB;
453 foreach my $suffix (qw(tmp git)) {
454 my $dir = "${subdir}\\.$suffix";
455 my $tdir = "${subdir}\\.tmp";
457 if (!rename $dir,$tdir) {
458 next if $! == ENOENT;
459 die "$dir: cannot rename to $tdir: $!\n";
462 system qw(rm -rf --), $tdir;
464 die "$dir: problem deleting file(s), rm exited $?\n";
465 } elsif ($! != ENOENT) {
466 die "$tdir: cannot stat after deletion: $!\n";
472 logm 'warning', "housekeeping: $subdir: cleanup prevented: $@";
474 unlink $lock or hkfail "remove $lock: $!";
478 if (!lockfile \*LOCK, $lock, LOCK_EX|$mode_locknb) {
479 die $! unless $mode_locknb;
480 logm 'info', "housekeeping: subdirs $subdir: lock busy, skipping";
483 logm 'info', "housekeeping: subdirs $subdir: $mode_what";
486 open HS, ">", "Housekeeping.stamp" or hkfail "touch Housekeeping.stamp: $!";
487 close HS or hkfail "close Housekeeping.stamp: $!";
488 logm 'info', "housekeeping finished";
491 sub housekeepingcheck ($$) {
492 my ($dofork, $force) = @_;
494 if (!lockfile \*HLOCK, "Housekeeping.lock", LOCK_EX|LOCK_NB) {
495 logm 'debug', "housekeeping lock taken, not running";
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";
512 defined $child or fail "fork: $!";
514 open STDERR, "|logger -p daemon.warning -t '$us(housekeeping)'"
515 or die "fork: logger $!";
529 chdir $gitd or fail "chdir $gitd: $!";
531 exec qw(git-upload-pack --strict), "--timeout=$servetimeout", qw(.)
532 or fail "exec git-upload-pack: $!";
535 sub daemonservice () {
537 while (!clonefetch()) { }
538 housekeepingcheck(1,0);
542 if ($housekeepingonly) {
543 housekeepingcheck(0, $housekeepingonly>=2);