chiark / gitweb /
git-cache-proxy: Use open-coded fork/exec for git gc
[chiark-utils.git] / scripts / git-cache-proxy
1 #!/usr/bin/perl -w
2 #
3 # git caching proxy
4
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).
10
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>            }
25
26 # example inetd.conf line:
27 #  9419 stream tcp nowait git-cache /usr/bin/git-cache-proxy git-cache-proxy
28 # you'll need to 
29 #  adduser git-cache
30 #  mkdir /var/cache/git-cache-proxy
31 #  chown git-cache /var/cache/git-cache-proxy
32
33 # git-cache-proxy
34 # Copyright 2010 Tony Finch
35 # Copyright 2013,2014 Ian Jackson
36 # Copyright 2017 Citrix
37
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.
42 #
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.
47
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.
51
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+.)
56
57 use strict;
58 use warnings;
59
60 use POSIX;
61 use Socket;
62 use Sys::Syslog;
63 use Fcntl qw(:flock SEEK_SET);
64 use File::Path qw(remove_tree);
65
66 our $us = 'git-cache-proxy';
67
68 our $debug = 0;
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;
77
78 #---------- error handling and logging ----------
79
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
82 # inetd service.
83
84 our $log; # filehandle (ref), or "1" meaning syslog
85
86 sub ntoa {
87     my $sockaddr = shift;
88     return ('(local)') unless defined $sockaddr;
89     my ($port,$addr) = sockaddr_in $sockaddr;
90     $addr = inet_ntoa $addr;
91     return ("[$addr]:$port",$addr,$port);
92 }
93
94 our ($client) = ntoa getpeername STDIN;
95 our ($server) = ntoa getsockname STDIN;
96
97 sub ensurelog () {
98     return if $log;
99     openlog $us, qw(pid), 'daemon';
100     $log = 1;
101 }
102
103 sub logm ($$) {
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 $!;
108         return;
109     }
110     ensurelog();
111     my $mainmsg = sprintf "%s-%s: %s", $server, $client, $msg;
112     if (ref $log) {
113         my $wholemsg = sprintf("%s [%d] %s: %s\n",
114                                strftime("%Y-%m-%d %H:%M:%S Z", gmtime),
115                                $$,
116                                $pri eq 'err' ? 'error' : $pri,
117                                $mainmsg);
118         print $log $wholemsg;
119     } else {
120         syslog $pri, "%s", "$pri $mainmsg";
121     }
122 }
123
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;
128 }
129
130 END {
131     if ($client ne '(local)') {
132         if ($?) { logm 'crit', "crashing ($?)"; }
133         seek TEMPERR, 0, SEEK_SET;
134         while (<TEMPERR>) {
135             chomp;
136             logm 'crit', $_;
137         }
138     }
139     exit $?;
140 }
141
142 sub fail ($) {
143     my ($msg) = @_;
144     logm 'err', $msg;
145     exit 0;
146 }
147
148 $SIG{ALRM} = sub { fail "timeout" };
149
150 sub gitfail ($) {
151     my ($msg) = @_;
152     close LOCK;
153     alarm 60;
154     logm 'notice', $msg;
155     my $gitmsg = "ERR $us: $msg";
156     $gitmsg = substr($gitmsg,0,65535); # just in case
157     printf "%04x%s", length($gitmsg)+4, $gitmsg;
158     flush STDOUT;
159     exit 0;
160 }
161
162 #---------- argument parsing ----------
163
164 for (;;) {
165     last unless @ARGV;
166     last unless $ARGV[0] =~ m/^-/;
167     $_ = shift @ARGV;
168     for (;;) {
169         last unless m/^-./;
170         if (s/^-H/-/) {
171             $housekeepingonly++;
172         } elsif (s/^-D/-/) {
173             $debug++;
174         } elsif (s/^-L(.*)$//) {
175             my $logfile = $_;
176             open STDERR, ">>", $logfile or fail "open $logfile: $!";
177             $log = \*STDERR;
178         } elsif (s/^-d(.*)$//) {
179             $cachedir = $1;
180         } elsif (s/^--( max-fetch-timeout
181                       | fetch-timeout
182                       | serve-timeout
183                       | tree-expire-days
184                       | housekeeping-interval-days
185                       | gc-interval-days
186                       )=(\d+)$//x) {
187             my $vn = $1;
188             $vn =~ y/-//d;
189             die $vn unless defined ${ $::{$vn} };
190             ${ $::{$vn} } = $2;
191         } else {
192             fail "bad usage: unknown option `$_'";
193         }
194     }
195 }
196
197 !@ARGV or fail "bad usage: no non-option arguments permitted";
198
199 #---------- utility functions ----------
200
201 sub lockfile ($$$) {
202     my ($fh, $fn, $flockmode) = @_;
203     my $what = $fn.(($flockmode & ~LOCK_NB) == LOCK_SH ? " (shared)" : "");
204     for (;;) {
205         close $fh;
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) {
210                 return 0; # ok then
211             }
212             fail "lock $what: $!";
213         }
214         stat $fh or fail "stat opened $fn: $!";
215         my $fh_ino = ((stat _)[1]);
216         if (!stat $fn) {
217             $! == ENOENT or fail "stat $fn: $!";
218             next;
219         }
220         my $fn_ino = ((stat _)[1]);
221         if ($fn_ino == $fh_ino) {
222             logm 'debug', "lock $what: acquired";
223             return 1;
224         }
225         logm 'debug', "lock $what: deleted, need to loop again";
226         # oh dear
227     }
228 }
229
230 sub xread {
231     my $length = shift;
232     my $buffer = "";
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;
238     }
239     return $buffer;
240 }
241
242 #---------- main program ----------
243
244 chdir $cachedir or fail "chdir $cachedir: $!";
245
246 our ($service,$specpath,$spechost,$subdir);
247 our ($tmpd,$gitd,$lock);
248 our ($fetch,$url);
249
250 sub servinfo ($) {
251     my ($msg) = @_;
252     logm 'info', "service `$specpath': $msg";
253 }
254
255 sub readcommand () {
256     alarm 30;
257
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'"
265     }
266
267     alarm 0;
268
269     $service eq 'git-upload-pack'
270         or gitfail "unknown/unsupported service `$service'";
271
272     $fetch = 2; # 0:don't; 1:try; 2:force
273     $url = $specpath;
274
275     while ($url =~ s#\s+(\[)([^][{}]+)\]$## ||
276            $url =~ s#\s+(\{)([^][{}]+)\}$##) {
277         $_ = $2;
278         my $must = $1 eq '{';
279         if (m/^fetch=try$/) {
280             $fetch = 1;
281         } elsif (m/^fetch=no$/) {
282             $fetch = 0;
283         } elsif (m/^fetch=must$/) {
284             $fetch = 2; # the default
285         } elsif (m/^timeout=(\d+)$/ && $1 >= 1) {
286             $fetchtimeout = $1 <= $maxfetchtimeout ? $1 : $maxfetchtimeout;
287         } elsif ($must) {
288             gitfail "unknown/unsupported option `$_'";
289         }
290     }
291
292     $url =~ m{^(?:https?|git)://[-.0-9a-z]+/}
293         or gitfail "unknown/unsupported url scheme or format `$url'";
294
295     $subdir = $url;
296     $subdir =~ s|\\|\\\\|g;
297     $subdir =~ s|,|\\,|g;
298     $subdir =~ s|/|,|g;
299
300     $tmpd= "$subdir\\.tmp";
301     $gitd= "$subdir\\.git";
302     $lock = "$subdir\\.lock";
303
304     servinfo "locking";
305 }
306
307 sub update_gcstamp ($) {
308     my ($gitdir) = (@_);
309     my $gcdone = "$gitdir/cache-proxy-gc.stamp";
310     open GCSTAMP, '>', $gcdone or fail "create $gcdone: $!";
311     close GCSTAMP;
312 }
313
314 sub clonefetch () {
315     lockfile \*LOCK, $lock, LOCK_EX;
316
317     my $exists = lstat $gitd;
318     $exists or $!==ENOENT or fail "lstat $gitd: $!";
319
320     our $fetchfail = '';
321
322     if ($fetch) {
323
324         my $rbits = '';
325         vec($rbits,0,1) = 1;
326         my $ebits = $rbits;
327         my $r=select $rbits,undef,$ebits,0;
328         $r>=0 or fail "select recheck STDOUT failed: $!";
329         if ($r) {
330             servinfo 'client disconnected (stdin unexpectedly'.
331                 (vec($rbits,0,1) ? ' readable' : '').
332                 (vec($ebits,0,1) ? ' exception' : '').
333                 ')';
334             exit 0;
335         }
336
337         our @cmd;
338
339         if (!$exists) {
340             system qw(rm -rf --), $tmpd;
341             @cmd = (qw(git clone -q --mirror), $url, $tmpd);
342             servinfo "cloning";
343         } else {
344             @cmd = (qw(git remote update --prune));
345             servinfo "fetching";
346         }
347         my $cmd = "@cmd[0..1]";
348
349         my $child = open FETCHERR, "-|";
350         defined $child or fail "fork: $!";
351         if (!$child) {
352             if ($exists) {
353                 chdir $gitd or fail "chdir $gitd: $!";
354             }
355             setpgrp or fail "setpgrp: $!";
356             open STDERR, ">&STDOUT" or fail "redirect stderr: $!";
357             exec @cmd or fail "exec $cmd[0]: $!";
358         }
359
360         my $fetcherr = '';
361         my $timedout = 0;
362         {
363             local $SIG{ALRM} = sub {
364                 servinfo "fetch/clone timeout";
365                 $timedout=1; kill 9, -$child;
366             };
367             alarm($fetchtimeout);
368             $!=0; { local $/=undef; $fetcherr = <FETCHERR>; }
369             !FETCHERR->error or fail "read pipe from fetch/clone: $!";
370             alarm(10);
371         }
372
373         kill -9, $child or fail "kill fetch/clone: $!";
374         $!=0; $?=0; if (!close FETCHERR) {
375             fail "reap fetch/clone: $!" if $!;
376             my $fetchfail =
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;
385             }
386             if ($fetch >= 2) {
387                 gitfail $fetchfail;
388             } else {
389                 servinfo "fetch/clone failed: $fetchfail";
390             }
391         }
392         alarm 0;
393
394         if (!$exists) {
395             update_gcstamp($tmpd);
396             rename $tmpd, $gitd or fail "rename fresh $tmpd to $gitd: $!";
397             $exists = 1;
398         }
399     } else {
400         $fetchfail = 'not attempted';
401     }
402
403     if (!$exists) {
404         gitfail "no cached data, and not cloned: $fetchfail";
405     }
406
407     servinfo "sharing";
408     lockfile \*LOCK, $lock, LOCK_SH; # NB releases and relocks
409
410     if (stat $gitd) {
411         return 1;
412     }
413     $!==ENOENT or fail "stat $gitd: $!";
414
415     # Well, err, someone must have taken the lock in between
416     # and garbage collected it.  How annoying.
417     return 0;
418 }
419
420 sub hkfail ($) { my ($msg) = @_; fail "housekeeping: $msg"; }
421
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";
427         if (!lstat $lock) {
428             $! == ENOENT or hkfail "$lock: lstat: $!";
429             next;
430         }
431         my ($mode_what,$mode_locknb,$mode_action);
432         if (-M _ <= $treeexpiredays) {
433             if (!lstat "$gcdone") {
434                 $! == ENOENT or hkfail "$gcdone: lstat: $!";
435                 logm 'debug',
436  "housekeeping: subdirs $subdir: touched recently, never gc'd!";
437             } elsif (-M _ <= $gcintervaldays) {
438                 logm 'debug',
439  "housekeeping: subdirs $subdir: touched recently, gc'd recently";
440                 next;
441             } else {
442                 logm 'debug',
443  "housekeeping: subdirs $subdir: touched recently, needs gc";
444             }
445             $mode_what = 'garbage collecting';
446             $mode_locknb = 0;
447             $mode_action = sub {
448                 my $gclog = "$subdir/gc.log";
449                 unlink $gclog or $!==ENOENT or hkfail "remove $gclog: $!";
450                 my $child = fork // hkfail "fork (for $subdir): $!";
451                 if (!$child) {
452                     if (!chdir "$subdir\\.git") {
453                         exit 0 if $!==ENOENT;
454                         die "for gc: chdir $subdir: $!\n";
455                     }
456                     exec qw(git gc --quiet);
457                     die "exec git gc (for $subdir): $!\n";
458                 }
459                 waitpid($child, 0) == $child or hkfail "waitpid failed! $!";
460                 if ($?) {
461                     logm 'err',
462  "housekeeping: subdirs $subdir: gc failed (wait status $?)";
463                 } else {
464                     update_gcstamp("$subdir\\.git");
465                     logm 'debug',
466                         "housekeeping: subdirs $subdir: gc done";
467                 }
468             };
469         } else {
470             $mode_what = 'cleaning';
471             $mode_locknb = LOCK_NB;
472             $mode_action = sub {
473                 eval {
474                     foreach my $suffix (qw(tmp git)) {
475                         my $dir = "${subdir}\\.$suffix";
476                         my $tdir = "${subdir}\\.tmp";
477                         if ($dir ne $tdir) {
478                             if (!rename $dir,$tdir) {
479                                 next if $! == ENOENT;
480                                 die "$dir: cannot rename to $tdir: $!\n";
481                             }
482                         }
483                         system qw(rm -rf --), $tdir;
484                         if (stat $tdir) {
485  die "$dir: problem deleting file(s), rm exited $?\n";
486                         } elsif ($! != ENOENT) {
487                             die "$tdir: cannot stat after deletion: $!\n";
488                         }
489                     }
490                 };
491                 if (length $@) {
492                     chomp $@;
493  logm 'warning', "housekeeping: $subdir: cleanup prevented: $@";
494                 } else {
495                     unlink $lock or hkfail "remove $lock: $!";
496                 }
497             };
498         }
499         if (!lockfile \*LOCK, $lock, LOCK_EX|$mode_locknb) {
500             die $! unless $mode_locknb;
501             logm 'info', "housekeeping: subdirs $subdir: lock busy, skipping";
502             next;
503         }
504         logm 'info', "housekeeping: subdirs $subdir: $mode_what";
505         $mode_action->();
506     }
507     open HS, ">", "Housekeeping.stamp" or hkfail "touch Housekeeping.stamp: $!";
508     close HS or hkfail "close Housekeeping.stamp: $!";
509     logm 'info', "housekeeping finished";
510 }
511
512 sub housekeepingcheck ($$) {
513     my ($dofork, $force) = @_;
514     if (!$force) {
515         if (!lockfile \*HLOCK, "Housekeeping.lock", LOCK_EX|LOCK_NB) {
516             logm 'debug', "housekeeping lock taken, not running";
517             close HLOCK;
518             return 0;
519         }
520     }
521     if ($force) {
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";
528         close HLOCK;
529         return 0;
530     }
531     if ($dofork) {
532         my $child = fork;
533         defined $child or fail "fork: $!";
534         if (!$child) {
535             open STDERR, "|logger -p daemon.warning -t '$us(housekeeping)'"
536                 or die "fork: logger $!";
537             housekeeping();
538             exit 0;
539         }
540     } else {
541         housekeeping();
542     }
543     close HLOCK;
544     return 1;
545 }
546
547 sub runcommand () {
548     servinfo "serving";
549
550     chdir $gitd or fail "chdir $gitd: $!";
551
552     exec qw(git-upload-pack --strict), "--timeout=$servetimeout", qw(.)
553         or fail "exec git-upload-pack: $!";
554 }
555
556 sub daemonservice () {
557     readcommand();
558     while (!clonefetch()) { }
559     housekeepingcheck(1,0);
560     runcommand();
561 }
562
563 if ($housekeepingonly) {
564     housekeepingcheck(0, $housekeepingonly>=2);
565 } else {
566     daemonservice();
567 }