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;
148 $SIG{ALRM} = sub { fail "timeout" };
155 my $gitmsg = "ERR $us: $msg";
156 $gitmsg = substr($gitmsg,0,65535); # just in case
157 printf "%04x%s", length($gitmsg)+4, $gitmsg;
162 #---------- argument parsing ----------
166 last unless $ARGV[0] =~ m/^-/;
174 } elsif (s/^-L(.*)$//) {
176 open STDERR, ">>", $logfile or fail "open $logfile: $!";
178 } elsif (s/^-d(.*)$//) {
180 } elsif (s/^--( max-fetch-timeout
184 | housekeeping-interval-days
189 die $vn unless defined ${ $::{$vn} };
192 fail "bad usage: unknown option `$_'";
197 !@ARGV or fail "bad usage: no non-option arguments permitted";
199 #---------- utility functions ----------
202 my ($fh, $fn, $flockmode) = @_;
203 my $what = $fn.(($flockmode & ~LOCK_NB) == LOCK_SH ? " (shared)" : "");
206 open $fh, '+>', $fn or fail "open/create $fn for lock: $!";
207 logm 'debug', "lock $what: acquiring";
208 if (!flock $fh, $flockmode) {
209 if ($flockmode & LOCK_NB && $! == EWOULDBLOCK) {
212 fail "lock $what: $!";
214 stat $fh or fail "stat opened $fn: $!";
215 my $fh_ino = ((stat _)[1]);
217 $! == ENOENT or fail "stat $fn: $!";
220 my $fn_ino = ((stat _)[1]);
221 if ($fn_ino == $fh_ino) {
222 logm 'debug', "lock $what: acquired";
225 logm 'debug', "lock $what: deleted, need to loop again";
233 while ($length > length $buffer) {
234 my $ret = sysread STDIN, $buffer, $length, length $buffer;
235 fail "expected $length bytes, got ".length $buffer
236 if defined $ret and $ret == 0;
237 fail "read: $!" if not defined $ret and $! != EINTR and $! != EAGAIN;
242 #---------- main program ----------
244 chdir $cachedir or fail "chdir $cachedir: $!";
246 our ($service,$specpath,$spechost,$subdir);
247 our ($tmpd,$gitd,$lock);
252 logm 'info', "service `$specpath': $msg";
258 my $hex_len = xread 4;
259 fail "Bad hex in packet length" unless $hex_len =~ m|^[0-9a-fA-F]{4}$|;
260 my $line = xread -4 + hex $hex_len;
261 unless (($service,$specpath,$spechost) = $line =~
262 m|^(git-[a-z-]+) /*([!-~ ]+)\0host=([!-~]+)\0$|) {
263 $line =~ s|[^ -~]+| |g;
264 gitfail "unknown/unsupported instruction `$line'"
269 $service eq 'git-upload-pack'
270 or gitfail "unknown/unsupported service `$service'";
272 $fetch = 2; # 0:don't; 1:try; 2:force
275 while ($url =~ s#\s+(\[)([^][{}]+)\]$## ||
276 $url =~ s#\s+(\{)([^][{}]+)\}$##) {
278 my $must = $1 eq '{';
279 if (m/^fetch=try$/) {
281 } elsif (m/^fetch=no$/) {
283 } elsif (m/^fetch=must$/) {
284 $fetch = 2; # the default
285 } elsif (m/^timeout=(\d+)$/ && $1 >= 1) {
286 $fetchtimeout = $1 <= $maxfetchtimeout ? $1 : $maxfetchtimeout;
288 gitfail "unknown/unsupported option `$_'";
292 $url =~ m{^(?:https?|git)://[-.0-9a-z]+/}
293 or gitfail "unknown/unsupported url scheme or format `$url'";
296 $subdir =~ s|\\|\\\\|g;
297 $subdir =~ s|,|\\,|g;
300 $tmpd= "$subdir\\.tmp";
301 $gitd= "$subdir\\.git";
302 $lock = "$subdir\\.lock";
307 sub update_gcstamp ($) {
309 my $gcdone = "$gitdir/cache-proxy-gc.stamp";
310 open GCSTAMP, '>', $gcdone or fail "create $gcdone: $!";
315 lockfile \*LOCK, $lock, LOCK_EX;
317 my $exists = lstat $gitd;
318 $exists or $!==ENOENT or fail "lstat $gitd: $!";
327 my $r=select $rbits,undef,$ebits,0;
328 $r>=0 or fail "select recheck STDOUT failed: $!";
330 servinfo 'client disconnected (stdin unexpectedly'.
331 (vec($rbits,0,1) ? ' readable' : '').
332 (vec($ebits,0,1) ? ' exception' : '').
340 system qw(rm -rf --), $tmpd;
341 @cmd = (qw(git clone -q --mirror), $url, $tmpd);
344 @cmd = (qw(git remote update --prune));
347 my $cmd = "@cmd[0..1]";
349 my $child = open FETCHERR, "-|";
350 defined $child or fail "fork: $!";
353 chdir $gitd or fail "chdir $gitd: $!";
355 setpgrp or fail "setpgrp: $!";
356 open STDERR, ">&STDOUT" or fail "redirect stderr: $!";
357 exec @cmd or fail "exec $cmd[0]: $!";
363 local $SIG{ALRM} = sub {
364 servinfo "fetch/clone timeout";
365 $timedout=1; kill 9, -$child;
367 alarm($fetchtimeout);
368 $!=0; { local $/=undef; $fetcherr = <FETCHERR>; }
369 !FETCHERR->error or fail "read pipe from fetch/clone: $!";
373 kill -9, $child or fail "kill fetch/clone: $!";
374 $!=0; $?=0; if (!close FETCHERR) {
375 fail "reap fetch/clone: $!" if $!;
377 !($? & 255) ? "$cmd died with error exit code ".($? >> 8) :
378 $? != 9 ? "$cmd died due to fatal signa, status $?" :
379 $timedout ? "$cmd timed out (${fetchtimeout}s)" :
380 "$cmd died due to unexpected SIGKILL";
381 if (length $fetcherr) {
382 $fetchfail .= "\n$fetcherr";
383 $fetchfail =~ s/\n$//;
384 $fetchfail =~ s{\n}{ // }g;
389 servinfo "fetch/clone failed: $fetchfail";
395 update_gcstamp($tmpd);
396 rename $tmpd, $gitd or fail "rename fresh $tmpd to $gitd: $!";
400 $fetchfail = 'not attempted';
404 gitfail "no cached data, and not cloned: $fetchfail";
408 lockfile \*LOCK, $lock, LOCK_SH; # NB releases and relocks
413 $!==ENOENT or fail "stat $gitd: $!";
415 # Well, err, someone must have taken the lock in between
416 # and garbage collected it. How annoying.
420 sub hkfail ($) { my ($msg) = @_; fail "housekeeping: $msg"; }
422 sub housekeeping () {
423 logm 'info', "housekeeping started";
424 foreach $lock (<[a-z]*\\.lock>) {
425 my $subdir = $lock; $subdir =~ s/\\.lock$//;
426 my $gcdone = "$subdir\\.git/cache-proxy-gc.stamp";
428 $! == ENOENT or hkfail "$lock: lstat: $!";
431 my ($mode_what,$mode_locknb,$mode_action);
432 if (-M _ <= $treeexpiredays) {
433 if (!lstat "$gcdone") {
434 $! == ENOENT or hkfail "$gcdone: lstat: $!";
436 "housekeeping: subdirs $subdir: touched recently, never gc'd!";
437 } elsif (-M _ <= $gcintervaldays) {
439 "housekeeping: subdirs $subdir: touched recently, gc'd recently";
443 "housekeeping: subdirs $subdir: touched recently, needs gc";
445 $mode_what = 'garbage collecting';
448 my $gclog = "$subdir/gc.log";
449 unlink $gclog or $!==ENOENT or hkfail "remove $gclog: $!";
450 my $child = fork // hkfail "fork (for $subdir): $!";
452 if (!chdir "$subdir\\.git") {
453 exit 0 if $!==ENOENT;
454 die "for gc: chdir $subdir: $!\n";
456 exec qw(git gc --quiet);
457 die "exec git gc (for $subdir): $!\n";
459 waitpid($child, 0) == $child or hkfail "waitpid failed! $!";
462 "housekeeping: subdirs $subdir: gc failed (wait status $?)";
464 update_gcstamp("$subdir\\.git");
466 "housekeeping: subdirs $subdir: gc done";
470 $mode_what = 'cleaning';
471 $mode_locknb = LOCK_NB;
474 foreach my $suffix (qw(tmp git)) {
475 my $dir = "${subdir}\\.$suffix";
476 my $tdir = "${subdir}\\.tmp";
478 if (!rename $dir,$tdir) {
479 next if $! == ENOENT;
480 die "$dir: cannot rename to $tdir: $!\n";
483 system qw(rm -rf --), $tdir;
485 die "$dir: problem deleting file(s), rm exited $?\n";
486 } elsif ($! != ENOENT) {
487 die "$tdir: cannot stat after deletion: $!\n";
493 logm 'warning', "housekeeping: $subdir: cleanup prevented: $@";
495 unlink $lock or hkfail "remove $lock: $!";
499 if (!lockfile \*LOCK, $lock, LOCK_EX|$mode_locknb) {
500 die $! unless $mode_locknb;
501 logm 'info', "housekeeping: subdirs $subdir: lock busy, skipping";
504 logm 'info', "housekeeping: subdirs $subdir: $mode_what";
507 open HS, ">", "Housekeeping.stamp" or hkfail "touch Housekeeping.stamp: $!";
508 close HS or hkfail "close Housekeeping.stamp: $!";
509 logm 'info', "housekeeping finished";
512 sub housekeepingcheck ($$) {
513 my ($dofork, $force) = @_;
515 if (!lockfile \*HLOCK, "Housekeeping.lock", LOCK_EX|LOCK_NB) {
516 logm 'debug', "housekeeping lock taken, not running";
522 logm 'info', "housekeeping forced";
523 } elsif (!lstat "Housekeeping.stamp") {
524 $! == ENOENT or fail "lstat Housekeeping.stamp: $!";
525 logm 'info', "housekeeping not done yet, will run";
526 } elsif (-M _ <= $housekeepingeverydays) {
527 logm 'debug', "housekeeping done recently";
533 defined $child or fail "fork: $!";
535 open STDERR, "|logger -p daemon.warning -t '$us(housekeeping)'"
536 or die "fork: logger $!";
550 chdir $gitd or fail "chdir $gitd: $!";
552 exec qw(git-upload-pack --strict), "--timeout=$servetimeout", qw(.)
553 or fail "exec git-upload-pack: $!";
556 sub daemonservice () {
558 while (!clonefetch()) { }
559 housekeepingcheck(1,0);
563 if ($housekeepingonly) {
564 housekeepingcheck(0, $housekeepingonly>=2);