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 = 3600;
69 our $maxfetchtimeout = 7200;
70 our $servetimeout = 3600;
71 our $cachedir = '/var/cache/git-cache-proxy';
72 our $housekeepingonly = 0;
74 #---------- error handling and logging ----------
76 # This is a bit fiddly, because we want to catch errors sent to stderr
77 # and dump them to syslog if we can, but only if we are running as an
80 our $log; # filehandle (ref), or "1" meaning syslog
84 return ('(local)') unless defined $sockaddr;
85 my ($port,$addr) = sockaddr_in $sockaddr;
86 $addr = inet_ntoa $addr;
87 return ("[$addr]:$port",$addr,$port);
90 our ($client) = ntoa getpeername STDIN;
91 our ($server) = ntoa getsockname STDIN;
95 openlog $us, qw(pid), 'daemon';
100 my ($pri, $msg) = @_;
101 return if $pri eq 'debug' && !$debug;
102 if ($client eq '(local)') {
103 print STDERR "$us: $pri: $msg\n" or die $!;
107 my $mainmsg = sprintf "%s-%s: %s", $server, $client, $msg;
109 my $wholemsg = sprintf("%s [%d] %s: %s\n",
110 strftime("%Y-%m-%d %H:%M:%S Z", gmtime),
112 $pri eq 'err' ? 'error' : $pri,
114 print $log $wholemsg;
116 syslog $pri, "%s", "$pri $mainmsg";
120 if ($client ne '(local)') {
121 open STDERR, ">/dev/null" or exit 255;
122 open TEMPERR, "+>", undef or exit 255;
123 open STDERR, ">&TEMPERR" or exit 255;
127 if ($client ne '(local)') {
128 if ($?) { logm 'crit', "crashing ($?)"; }
129 seek TEMPERR, 0, SEEK_SET;
149 my $gitmsg = "ERR $us: $msg";
150 $gitmsg = substr($gitmsg,0,65535); # just in case
151 printf "%04x%s", length($gitmsg)+4, $gitmsg;
156 #---------- argument parsing ----------
160 last unless $ARGV[0] =~ m/^-/;
168 } elsif (s/^-L(.*)$//) {
170 open STDERR, ">>", $logfile or fail "open $logfile: $!";
172 } elsif (s/^-d(.*)$//) {
174 } elsif (s/^--( max-fetch-timeout
178 | housekeeping-interval-days
182 die $vn unless defined ${ $::{$vn} };
185 fail "bad usage: unknown option `$_'";
190 !@ARGV or fail "bad usage: no non-option arguments permitted";
192 #---------- utility functions ----------
195 my ($fh, $fn, $flockmode) = @_;
196 my $what = $fn.(($flockmode & ~LOCK_NB) == LOCK_SH ? " (shared)" : "");
199 open $fh, '+>', $fn or fail "open/create $fn for lock: $!";
200 logm 'debug', "lock $what: acquiring";
201 if (!flock $fh, $flockmode) {
202 if ($flockmode & LOCK_NB && $! == EWOULDBLOCK) {
205 fail "lock $what: $!";
207 stat $fh or fail "stat opened $fn: $!";
208 my $fh_ino = ((stat _)[1]);
210 $! == ENOENT or fail "stat $fn: $!";
213 my $fn_ino = ((stat _)[1]);
214 if ($fn_ino == $fh_ino) {
215 logm 'debug', "lock $what: acquired";
218 logm 'debug', "lock $what: deleted, need to loop again";
226 while ($length > length $buffer) {
227 my $ret = sysread STDIN, $buffer, $length, length $buffer;
228 fail "expected $length bytes, got ".length $buffer
229 if defined $ret and $ret == 0;
230 fail "read: $!" if not defined $ret and $! != EINTR and $! != EAGAIN;
235 #---------- main program ----------
237 chdir $cachedir or fail "chdir $cachedir: $!";
239 our ($service,$specpath,$spechost,$subdir);
240 our ($tmpd,$gitd,$lock);
245 logm 'info', "service `$specpath': $msg";
249 $SIG{ALRM} = sub { fail "timeout" };
252 my $hex_len = xread 4;
253 fail "Bad hex in packet length" unless $hex_len =~ m|^[0-9a-fA-F]{4}$|;
254 my $line = xread -4 + hex $hex_len;
255 unless (($service,$specpath,$spechost) = $line =~
256 m|^(git-[a-z-]+) /*([!-~ ]+)\0host=([!-~]+)\0$|) {
257 $line =~ s|[^ -~]+| |g;
258 gitfail "unknown/unsupported instruction `$line'"
263 $service eq 'git-upload-pack'
264 or gitfail "unknown/unsupported service `$service'";
266 $fetch = 2; # 0:don't; 1:try; 2:force
269 while ($url =~ s#\s+(\[)([^][{}]+)\]$## ||
270 $url =~ s#\s+(\{)([^][{}]+)\}$##) {
272 my $must = $1 eq '{';
273 if (m/^fetch=try$/) {
275 } elsif (m/^fetch=no$/) {
277 } elsif (m/^fetch=must$/) {
278 $fetch = 2; # the default
279 } elsif (m/^timeout=(\d+)$/ && $1 >= 1) {
280 $fetchtimeout = $1 <= $maxfetchtimeout ? $1 : $maxfetchtimeout;
282 gitfail "unknown/unsupported option `$_'";
286 $url =~ m{^(?:https?|git)://[-.0-9a-z]+/}
287 or gitfail "unknown/unsupported url scheme or format `$url'";
290 $subdir =~ s|\\|\\\\|g;
291 $subdir =~ s|,|\\,|g;
294 $tmpd= "$subdir\\.tmp";
295 $gitd= "$subdir\\.git";
296 $lock = "$subdir\\.lock";
302 lockfile \*LOCK, $lock, LOCK_EX;
304 my $exists = lstat $gitd;
305 $exists or $!==ENOENT or fail "lstat $gitd: $!";
314 system qw(rm -rf --), $tmpd;
315 @cmd = (qw(git clone -q --mirror), $url, $tmpd);
318 @cmd = (qw(git remote update --prune));
321 my $cmd = "@cmd[0..1]";
323 my $child = open FETCHERR, "-|";
324 defined $child or fail "fork: $!";
327 chdir $gitd or fail "chdir $gitd: $!";
329 setpgrp or fail "setpgrp: $!";
330 open STDERR, ">&STDOUT" or fail "redirect stderr: $!";
331 exec @cmd or fail "exec $cmd[0]: $!";
337 local $SIG{ALRM} = sub {
338 servinfo "fetch/clone timeout";
339 $timedout=1; kill 9, -$child;
341 alarm($fetchtimeout);
342 $!=0; { local $/=undef; $fetcherr = <FETCHERR>; }
343 !FETCHERR->error or fail "read pipe from fetch/clone: $!";
347 kill -9, $child or fail "kill fetch/clone: $!";
348 $!=0; $?=0; if (!close FETCHERR) {
349 fail "reap fetch/clone: $!" if $!;
351 !($? & 255) ? "$cmd died with error exit code ".($? >> 8) :
352 $? != 9 ? "$cmd died due to fatal signa, status $?" :
353 $timedout ? "$cmd timed out (${fetchtimeout}s)" :
354 "$cmd died due to unexpected SIGKILL";
355 if (length $fetcherr) {
356 $fetchfail .= "\n$fetcherr";
357 $fetchfail =~ s/\n$//;
358 $fetchfail =~ s{\n}{ // }g;
363 servinfo "fetch/clone failed: $fetchfail";
369 rename $tmpd, $gitd or fail "rename fresh $tmpd to $gitd: $!";
373 $fetchfail = 'not attempted';
377 gitfail "no cached data, and not cloned: $fetchfail";
381 lockfile \*LOCK, $lock, LOCK_SH; # NB releases and relocks
386 $!==ENOENT or fail "stat $gitd: $!";
388 # Well, err, someone must have taken the lock in between
389 # and garbage collected it. How annoying.
393 sub hkfail ($) { my ($msg) = @_; fail "housekeeping: $msg"; }
395 sub housekeeping () {
396 logm 'info', "housekeeping started";
397 foreach $lock (<[a-z]*\\.lock>) {
398 my $subdir = $lock; $subdir =~ s/\\.lock$//;
400 $! == ENOENT or hkfail "$lock: lstat: $!";
403 if (-M _ <= $treeexpiredays) {
404 logm 'debug', "housekeeping: subdirs $subdir: touched recently";
407 if (!lockfile \*LOCK, $lock, LOCK_EX|LOCK_NB) {
408 logm 'info', "housekeeping: subdirs $subdir: lock busy, skipping";
411 logm 'info', "housekeeping: subdirs $subdir: cleaning";
413 foreach my $suffix (qw(tmp git)) {
414 my $dir = "${subdir}\\.$suffix";
415 my $tdir = "${subdir}\\.tmp";
417 if (!rename $dir,$tdir) {
418 next if $! == ENOENT;
419 die "$dir: cannot rename to $tdir: $!\n";
422 system qw(rm -rf --), $tdir;
424 die "$dir: problem deleting file(s), rm exited $?\n";
425 } elsif ($! != ENOENT) {
426 die "$tdir: cannot stat after deletion: $!\n";
432 logm 'warning', "housekeeping: $subdir: cleanup prevented: $@";
434 unlink $lock or hkfail "remove $lock: $!";
437 open HS, ">", "Housekeeping.stamp" or hkfail "touch Housekeeping.stamp: $!";
438 close HS or hkfail "close Housekeeping.stamp: $!";
439 logm 'info', "housekeeping finished";
442 sub housekeepingcheck ($$) {
443 my ($dofork, $force) = @_;
445 if (!lockfile \*HLOCK, "Housekeeping.lock", LOCK_EX|LOCK_NB) {
446 logm 'debug', "housekeeping lock taken, not running";
452 logm 'info', "housekeeping forced";
453 } elsif (!lstat "Housekeeping.stamp") {
454 $! == ENOENT or fail "lstat Housekeeping.stamp: $!";
455 logm 'info', "housekeeping not done yet, will run";
456 } elsif (-M _ <= $housekeepingeverydays) {
457 logm 'debug', "housekeeping done recently";
463 defined $child or fail "fork: $!";
465 open STDERR, "|logger -p daemon.warning -t '$us(housekeeping)'"
466 or die "fork: logger $!";
480 chdir $gitd or fail "chdir $gitd: $!";
482 exec qw(git-upload-pack --strict), "--timeout=$servetimeout", qw(.)
483 or fail "exec git-upload-pack: $!";
486 sub daemonservice () {
488 while (!clonefetch()) { }
489 housekeepingcheck(1,0);
493 if ($housekeepingonly) {
494 housekeepingcheck(0, $housekeepingonly>=2);