chiark / gitweb /
fishdescriptor: bugfixes
[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
23 # example inetd.conf line:
24 #  9419 stream tcp nowait git-cache /usr/bin/git-cache-proxy git-cache-proxy
25 # you'll need to 
26 #  adduser git-cache
27 #  mkdir /var/cache/git-cache-proxy
28 #  chown git-cache /var/cache/git-cache-proxy
29
30 # git-cache-proxy
31 # Copyright 2010 Tony Finch
32 # Copyright 2013,2014 Ian Jackson
33 # Copyright 2017 Citrix
34
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.
39 #
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.
44
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.
48
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+.)
53
54 use strict;
55 use warnings;
56
57 use POSIX;
58 use Socket;
59 use Sys::Syslog;
60 use Fcntl qw(:flock SEEK_SET);
61 use File::Path qw(remove_tree);
62
63 our $us = 'git-cache-proxy';
64
65 our $debug = 0;
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;
73
74 #---------- error handling and logging ----------
75
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
78 # inetd service.
79
80 our $log; # filehandle (ref), or "1" meaning syslog
81
82 sub ntoa {
83     my $sockaddr = shift;
84     return ('(local)') unless defined $sockaddr;
85     my ($port,$addr) = sockaddr_in $sockaddr;
86     $addr = inet_ntoa $addr;
87     return ("[$addr]:$port",$addr,$port);
88 }
89
90 our ($client) = ntoa getpeername STDIN;
91 our ($server) = ntoa getsockname STDIN;
92
93 sub ensurelog () {
94     return if $log;
95     openlog $us, qw(pid), 'daemon';
96     $log = 1;
97 }
98
99 sub logm ($$) {
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 $!;
104         return;
105     }
106     ensurelog();
107     my $mainmsg = sprintf "%s-%s: %s", $server, $client, $msg;
108     if (ref $log) {
109         my $wholemsg = sprintf("%s [%d] %s: %s\n",
110                                strftime("%Y-%m-%d %H:%M:%S Z", gmtime),
111                                $$,
112                                $pri eq 'err' ? 'error' : $pri,
113                                $mainmsg);
114         print $log $wholemsg;
115     } else {
116         syslog $pri, "%s", "$pri $mainmsg";
117     }
118 }
119
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;
124 }
125
126 END {
127     if ($client ne '(local)') {
128         if ($?) { logm 'crit', "crashing ($?)"; }
129         seek TEMPERR, 0, SEEK_SET;
130         while (<TEMPERR>) {
131             chomp;
132             logm 'crit', $_;
133         }
134     }
135     exit $?;
136 }
137
138 sub fail ($) {
139     my ($msg) = @_;
140     logm 'err', $msg;
141     exit 0;
142 }
143
144 sub gitfail ($) {
145     my ($msg) = @_;
146     close LOCK;
147     alarm 60;
148     logm 'notice', $msg;
149     my $gitmsg = "ERR $us: $msg";
150     $gitmsg = substr($gitmsg,0,65535); # just in case
151     printf "%04x%s", length($gitmsg)+4, $gitmsg;
152     flush STDOUT;
153     exit 0;
154 }
155
156 #---------- argument parsing ----------
157
158 for (;;) {
159     last unless @ARGV;
160     last unless $ARGV[0] =~ m/^-/;
161     $_ = shift @ARGV;
162     for (;;) {
163         last unless m/^-./;
164         if (s/^-H/-/) {
165             $housekeepingonly++;
166         } elsif (s/^-D/-/) {
167             $debug++;
168         } elsif (s/^-L(.*)$//) {
169             my $logfile = $_;
170             open STDERR, ">>", $logfile or fail "open $logfile: $!";
171             $log = \*STDERR;
172         } elsif (s/^-d(.*)$//) {
173             $cachedir = $1;
174         } elsif (s/^--( max-fetch-timeout
175                       | fetch-timeout
176                       | serve-timeout
177                       | tree-expire-days
178                       | housekeeping-interval-days
179                       )=(\d+)$//x) {
180             my $vn = $1;
181             $vn =~ y/-//d;
182             die $vn unless defined ${ $::{$vn} };
183             ${ $::{$vn} } = $2;
184         } else {
185             fail "bad usage: unknown option `$_'";
186         }
187     }
188 }
189
190 !@ARGV or fail "bad usage: no non-option arguments permitted";
191
192 #---------- utility functions ----------
193
194 sub lockfile ($$$) {
195     my ($fh, $fn, $flockmode) = @_;
196     my $what = $fn.(($flockmode & ~LOCK_NB) == LOCK_SH ? " (shared)" : "");
197     for (;;) {
198         close $fh;
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) {
203                 return 0; # ok then
204             }
205             fail "lock $what: $!";
206         }
207         stat $fh or fail "stat opened $fn: $!";
208         my $fh_ino = ((stat _)[1]);
209         if (!stat $fn) {
210             $! == ENOENT or fail "stat $fn: $!";
211             next;
212         }
213         my $fn_ino = ((stat _)[1]);
214         if ($fn_ino == $fh_ino) {
215             logm 'debug', "lock $what: acquired";
216             return 1;
217         }
218         logm 'debug', "lock $what: deleted, need to loop again";
219         # oh dear
220     }
221 }
222
223 sub xread {
224     my $length = shift;
225     my $buffer = "";
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;
231     }
232     return $buffer;
233 }
234
235 #---------- main program ----------
236
237 chdir $cachedir or fail "chdir $cachedir: $!";
238
239 our ($service,$specpath,$spechost,$subdir);
240 our ($tmpd,$gitd,$lock);
241 our ($fetch,$url);
242
243 sub servinfo ($) {
244     my ($msg) = @_;
245     logm 'info', "service `$specpath': $msg";
246 }
247
248 sub readcommand () {
249     $SIG{ALRM} = sub { fail "timeout" };
250     alarm 30;
251
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'"
259     }
260
261     alarm 0;
262
263     $service eq 'git-upload-pack'
264         or gitfail "unknown/unsupported service `$service'";
265
266     $fetch = 2; # 0:don't; 1:try; 2:force
267     $url = $specpath;
268
269     while ($url =~ s#\s+(\[)([^][{}]+)\]$## ||
270            $url =~ s#\s+(\{)([^][{}]+)\}$##) {
271         $_ = $2;
272         my $must = $1 eq '{';
273         if (m/^fetch=try$/) {
274             $fetch = 1;
275         } elsif (m/^fetch=no$/) {
276             $fetch = 0;
277         } elsif (m/^fetch=must$/) {
278             $fetch = 2; # the default
279         } elsif (m/^timeout=(\d+)$/ && $1 >= 1) {
280             $fetchtimeout = $1 <= $maxfetchtimeout ? $1 : $maxfetchtimeout;
281         } elsif ($must) {
282             gitfail "unknown/unsupported option `$_'";
283         }
284     }
285
286     $url =~ m{^(?:https?|git)://[-.0-9a-z]+/}
287         or gitfail "unknown/unsupported url scheme or format `$url'";
288
289     $subdir = $url;
290     $subdir =~ s|\\|\\\\|g;
291     $subdir =~ s|,|\\,|g;
292     $subdir =~ s|/|,|g;
293
294     $tmpd= "$subdir\\.tmp";
295     $gitd= "$subdir\\.git";
296     $lock = "$subdir\\.lock";
297
298     servinfo "locking";
299 }
300
301 sub clonefetch () {
302     lockfile \*LOCK, $lock, LOCK_EX;
303
304     my $exists = lstat $gitd;
305     $exists or $!==ENOENT or fail "lstat $gitd: $!";
306
307     our $fetchfail = '';
308
309     if ($fetch) {
310
311         our @cmd;
312
313         if (!$exists) {
314             system qw(rm -rf --), $tmpd;
315             @cmd = (qw(git clone -q --mirror), $url, $tmpd);
316             servinfo "cloning";
317         } else {
318             @cmd = (qw(git remote update --prune));
319             servinfo "fetching";
320         }
321         my $cmd = "@cmd[0..1]";
322
323         my $child = open FETCHERR, "-|";
324         defined $child or fail "fork: $!";
325         if (!$child) {
326             if ($exists) {
327                 chdir $gitd or fail "chdir $gitd: $!";
328             }
329             setpgrp or fail "setpgrp: $!";
330             open STDERR, ">&STDOUT" or fail "redirect stderr: $!";
331             exec @cmd or fail "exec $cmd[0]: $!";
332         }
333
334         my $fetcherr = '';
335         my $timedout = 0;
336         {
337             local $SIG{ALRM} = sub {
338                 servinfo "fetch/clone timeout";
339                 $timedout=1; kill 9, -$child;
340             };
341             alarm($fetchtimeout);
342             $!=0; { local $/=undef; $fetcherr = <FETCHERR>; }
343             !FETCHERR->error or fail "read pipe from fetch/clone: $!";
344             alarm(10);
345         }
346
347         kill -9, $child or fail "kill fetch/clone: $!";
348         $!=0; $?=0; if (!close FETCHERR) {
349             fail "reap fetch/clone: $!" if $!;
350             my $fetchfail =
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;
359             }
360             if ($fetch >= 2) {
361                 gitfail $fetchfail;
362             } else {
363                 servinfo "fetch/clone failed: $fetchfail";
364             }
365         }
366         alarm 0;
367
368         if (!$exists) {
369             rename $tmpd, $gitd or fail "rename fresh $tmpd to $gitd: $!";
370             $exists = 1;
371         }
372     } else {
373         $fetchfail = 'not attempted';
374     }
375
376     if (!$exists) {
377         gitfail "no cached data, and not cloned: $fetchfail";
378     }
379
380     servinfo "sharing";
381     lockfile \*LOCK, $lock, LOCK_SH; # NB releases and relocks
382
383     if (stat $gitd) {
384         return 1;
385     }
386     $!==ENOENT or fail "stat $gitd: $!";
387
388     # Well, err, someone must have taken the lock in between
389     # and garbage collected it.  How annoying.
390     return 0;
391 }
392
393 sub hkfail ($) { my ($msg) = @_; fail "housekeeping: $msg"; }
394
395 sub housekeeping () {
396     logm 'info', "housekeeping started";
397     foreach $lock (<[a-z]*\\.lock>) {
398         my $subdir = $lock;  $subdir =~ s/\\.lock$//;
399         if (!lstat $lock) {
400             $! == ENOENT or hkfail "$lock: lstat: $!";
401             next;
402         }
403         if (-M _ <= $treeexpiredays) {
404             logm 'debug', "housekeeping: subdirs $subdir: touched recently";
405             next;
406         }
407         if (!lockfile \*LOCK, $lock, LOCK_EX|LOCK_NB) {
408             logm 'info', "housekeeping: subdirs $subdir: lock busy, skipping";
409             next;
410         }
411         logm 'info', "housekeeping: subdirs $subdir: cleaning";
412         eval {
413             foreach my $suffix (qw(tmp git)) {
414                 my $dir = "${subdir}\\.$suffix";
415                 my $tdir = "${subdir}\\.tmp";
416                 if ($dir ne $tdir) {
417                     if (!rename $dir,$tdir) {
418                         next if $! == ENOENT;
419                         die "$dir: cannot rename to $tdir: $!\n";
420                     }
421                 }
422                 system qw(rm -rf --), $tdir;
423                 if (stat $tdir) {
424                     die "$dir: problem deleting file(s), rm exited $?\n";
425                 } elsif ($! != ENOENT) {
426                     die "$tdir: cannot stat after deletion: $!\n";
427                 }
428             }
429         };
430         if (length $@) {
431             chomp $@;
432             logm 'warning', "housekeeping: $subdir: cleanup prevented: $@";
433         } else {
434             unlink $lock or hkfail "remove $lock: $!";
435         }
436     }
437     open HS, ">", "Housekeeping.stamp" or hkfail "touch Housekeeping.stamp: $!";
438     close HS or hkfail "close Housekeeping.stamp: $!";
439     logm 'info', "housekeeping finished";
440 }
441
442 sub housekeepingcheck ($$) {
443     my ($dofork, $force) = @_;
444     if (!$force) {
445         if (!lockfile \*HLOCK, "Housekeeping.lock", LOCK_EX|LOCK_NB) {
446             logm 'debug', "housekeeping lock taken, not running";
447             close HLOCK;
448             return 0;
449         }
450     }
451     if ($force) {
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";
458         close HLOCK;
459         return 0;
460     }
461     if ($dofork) {
462         my $child = fork;
463         defined $child or fail "fork: $!";
464         if (!$child) {
465             open STDERR, "|logger -p daemon.warning -t '$us(housekeeping)'"
466                 or die "fork: logger $!";
467             housekeeping();
468             exit 0;
469         }
470     } else {
471         housekeeping();
472     }
473     close HLOCK;
474     return 1;
475 }
476
477 sub runcommand () {
478     servinfo "serving";
479
480     chdir $gitd or fail "chdir $gitd: $!";
481
482     exec qw(git-upload-pack --strict), "--timeout=$servetimeout", qw(.)
483         or fail "exec git-upload-pack: $!";
484 }
485
486 sub daemonservice () {
487     readcommand();
488     while (!clonefetch()) { }
489     housekeepingcheck(1,0);
490     runcommand();
491 }
492
493 if ($housekeepingonly) {
494     housekeepingcheck(0, $housekeepingonly>=2);
495 } else {
496     daemonservice();
497 }