]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GitHTTPBackend.pm
git-http-backend: set cache headers
[public-inbox.git] / lib / PublicInbox / GitHTTPBackend.pm
1 # Copyright (C) 2016 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # when no endpoints match, fallback to this and serve a static file
5 # or smart HTTP
6 package PublicInbox::GitHTTPBackend;
7 use strict;
8 use warnings;
9 use Fcntl qw(:seek);
10 use IO::File;
11 use PublicInbox::Spawn qw(spawn);
12 use HTTP::Date qw(time2str);
13
14 # TODO: make configurable, but keep in mind it's better to have
15 # multiple -httpd worker processes which are already scaled to
16 # the proper number of CPUs and memory.  git-pack-objects(1) may
17 # also use threads and bust memory limits, too, so I recommend
18 # limiting threads to 1 (via `pack.threads` knob in git) for serving.
19 my $LIMIT = 1;
20 my $nr_running = 0;
21
22 # n.b. serving "description" and "cloneurl" should be innocuous enough to
23 # not cause problems.  serving "config" might...
24 my @text = qw[HEAD info/refs
25         objects/info/(?:http-alternates|alternates|packs)
26         cloneurl description];
27
28 my @binary = qw!
29         objects/[a-f0-9]{2}/[a-f0-9]{38}
30         objects/pack/pack-[a-f0-9]{40}\.(?:pack|idx)
31         !;
32
33 our $ANY = join('|', @binary, @text);
34 my $BIN = join('|', @binary);
35 my $TEXT = join('|', @text);
36
37 my @no_cache = ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT',
38                 'Pragma', 'no-cache',
39                 'Cache-Control', 'no-cache, max-age=0, must-revalidate');
40
41 my $nextq;
42 sub do_next () {
43         my $q = $nextq;
44         $nextq = undef;
45         while (my $cb = shift @$q) {
46                 $cb->(); # this may redefine nextq
47         }
48 }
49
50 sub r ($) {
51         my ($s) = @_;
52         [ $s, [qw(Content-Type text/plain Content-Length 0), @no_cache ], [] ]
53 }
54
55 sub serve {
56         my ($cgi, $git, $path) = @_;
57         return serve_dumb($cgi, $git, $path) if $nr_running >= $LIMIT;
58
59         my $service = $cgi->param('service') || '';
60         if ($service =~ /\Agit-\w+-pack\z/ || $path =~ /\Agit-\w+-pack\z/) {
61                 my $ok = serve_smart($cgi, $git, $path);
62                 return $ok if $ok;
63         }
64
65         serve_dumb($cgi, $git, $path);
66 }
67
68 sub err ($@) {
69         my ($env, @msg) = @_;
70         $env->{'psgi.errors'}->print(@msg, "\n");
71 }
72
73 sub drop_client ($) {
74         if (my $io = $_[0]->{'psgix.io'}) {
75                 $io->close; # this is Danga::Socket::close
76         }
77 }
78
79 sub serve_dumb {
80         my ($cgi, $git, $path) = @_;
81
82         my @h;
83         my $type;
84         if ($path =~ /\A(?:$BIN)\z/o) {
85                 $type = 'application/octet-stream';
86                 push @h, 'Expires', time2str(time + 31536000);
87                 push @h, 'Cache-Control', 'public, max-age=31536000';
88         } elsif ($path =~ /\A(?:$TEXT)\z/o) {
89                 $type = 'text/plain';
90                 push @h, @no_cache;
91         } else {
92                 return r(404);
93         }
94
95         my $f = "$git->{git_dir}/$path";
96         return r(404) unless -f $f && -r _; # just in case it's a FIFO :P
97         my @st = stat(_);
98         my $size = $st[7];
99         my $env = $cgi->{env};
100
101         # TODO: If-Modified-Since and Last-Modified?
102         open my $in, '<', $f or return r(404);
103         my $len = $size;
104         my $n = 65536; # try to negotiate a big TCP window, first
105         my ($next, $fh);
106         my $cb = sub {
107                 $n = $len if $len < $n;
108                 my $r = sysread($in, my $buf, $n);
109                 if (!defined $r) {
110                         err($env, "$f read error: $!");
111                         drop_client($env);
112                 } elsif ($r <= 0) {
113                         err($env, "$f EOF with $len bytes left");
114                         drop_client($env);
115                 } else {
116                         $len -= $r;
117                         $fh->write($buf);
118                         if ($len == 0) {
119                                 $fh->close;
120                         } elsif ($next) {
121                                 # avoid recursion in Danga::Socket::write
122                                 unless ($nextq) {
123                                         $nextq = [];
124                                         Danga::Socket->AddTimer(0, *do_next);
125                                 }
126                                 # avoid buffering too much in case we have
127                                 # slow clients:
128                                 $n = 8192;
129                                 push @$nextq, $next;
130                                 return;
131                         }
132                 }
133                 # all done, cleanup references:
134                 $fh = $next = undef;
135         };
136
137         my $code = 200;
138         push @h, 'Content-Type', $type;
139         my $range = $env->{HTTP_RANGE};
140         if (defined $range && $range =~ /\bbytes=(\d*)-(\d*)\z/) {
141                 ($code, $len) = prepare_range($cgi, $in, \@h, $1, $2, $size);
142                 if ($code == 416) {
143                         push @h, 'Content-Range', "bytes */$size";
144                         return [ 416, \@h, [] ];
145                 }
146         }
147         push @h, 'Content-Length', $len;
148
149         sub {
150                 my ($res) = @_; # Plack callback
151                 $fh = $res->([ $code, \@h ]);
152                 if (defined $env->{'pi-httpd.async'}) {
153                         my $pi_http = $env->{'psgix.io'};
154                         $next = sub { $pi_http->write($cb) };
155                         $cb->(); # start it off!
156                 } else {
157                         $cb->() while $fh;
158                 }
159         }
160 }
161
162 sub prepare_range {
163         my ($cgi, $in, $h, $beg, $end, $size) = @_;
164         my $code = 200;
165         my $len = $size;
166         if ($beg eq '') {
167                 if ($end ne '') { # "bytes=-$end" => last N bytes
168                         $beg = $size - $end;
169                         $beg = 0 if $beg < 0;
170                         $end = $size - 1;
171                         $code = 206;
172                 } else {
173                         $code = 416;
174                 }
175         } else {
176                 if ($beg > $size) {
177                         $code = 416;
178                 } elsif ($end eq '' || $end >= $size) {
179                         $end = $size - 1;
180                         $code = 206;
181                 } elsif ($end < $size) {
182                         $code = 206;
183                 } else {
184                         $code = 416;
185                 }
186         }
187         if ($code == 206) {
188                 $len = $end - $beg + 1;
189                 if ($len <= 0) {
190                         $code = 416;
191                 } else {
192                         sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
193                         push @$h, qw(Accept-Ranges bytes Content-Range);
194                         push @$h, "bytes $beg-$end/$size";
195
196                         # FIXME: Plack::Middleware::Deflater bug?
197                         $cgi->{env}->{'psgix.no-compress'} = 1;
198                 }
199         }
200         ($code, $len);
201 }
202
203 # returns undef if 403 so it falls back to dumb HTTP
204 sub serve_smart {
205         my ($cgi, $git, $path) = @_;
206         my $env = $cgi->{env};
207
208         my $input = $env->{'psgi.input'};
209         my $buf;
210         my $in;
211         my $fd = eval { fileno($input) };
212         if (defined $fd && $fd >= 0) {
213                 $in = $input;
214         } else {
215                 $in = input_to_file($env) or return r(500);
216         }
217         my ($rpipe, $wpipe);
218         unless (pipe($rpipe, $wpipe)) {
219                 err($env, "error creating pipe: $! - going static");
220                 return;
221         }
222         my %env = %ENV;
223         # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
224         # may be set in the server-process and are passed as-is
225         foreach my $name (qw(QUERY_STRING
226                                 REMOTE_USER REMOTE_ADDR
227                                 HTTP_CONTENT_ENCODING
228                                 CONTENT_TYPE
229                                 SERVER_PROTOCOL
230                                 REQUEST_METHOD)) {
231                 my $val = $env->{$name};
232                 $env{$name} = $val if defined $val;
233         }
234         my $git_dir = $git->{git_dir};
235         $env{GIT_HTTP_EXPORT_ALL} = '1';
236         $env{PATH_TRANSLATED} = "$git_dir/$path";
237         my %rdr = ( 0 => fileno($in), 1 => fileno($wpipe) );
238         my $pid = spawn([qw(git http-backend)], \%env, \%rdr);
239         unless (defined $pid) {
240                 err($env, "error spawning: $! - going static");
241                 return;
242         }
243         $wpipe = $in = undef;
244         $buf = '';
245         my ($vin, $fh, $res);
246         $nr_running++;
247
248         # Danga::Socket users, we queue up the read_enable callback to
249         # fire after pending writes are complete:
250         my $pi_http = $env->{'psgix.io'};
251         my $read_enable = sub { $rpipe->watch_read(1) };
252         my $read_disable = sub {
253                 $rpipe->watch_read(0);
254                 $pi_http->write($read_enable);
255         };
256
257         my $end = sub {
258                 if ($fh) {
259                         $fh->close;
260                         $fh = undef;
261                 }
262                 if ($rpipe) {
263                         # _may_ be Danga::Socket::close via
264                         # PublicInbox::HTTPD::Async::close:
265                         $rpipe->close;
266                         $rpipe = undef;
267                         $nr_running--;
268                 }
269                 if (defined $pid) {
270                         my $e = $pid == waitpid($pid, 0) ?
271                                 $? : "PID:$pid still running?";
272                         err($env, "git http-backend ($git_dir): $e") if $e;
273                 }
274                 return unless $res;
275                 my $dumb = serve_dumb($cgi, $git, $path);
276                 ref($dumb) eq 'ARRAY' ? $res->($dumb) : $dumb->($res);
277         };
278         my $fail = sub {
279                 if ($!{EAGAIN} || $!{EINTR}) {
280                         select($vin, undef, undef, undef) if defined $vin;
281                         # $vin is undef on async, so this is a noop on EAGAIN
282                         return;
283                 }
284                 my $e = $!;
285                 $end->();
286                 err($env, "git http-backend ($git_dir): $e\n");
287         };
288         my $cb = sub { # read git-http-backend output and stream to client
289                 my $r = $rpipe ? $rpipe->sysread($buf, 8192, length($buf)) : 0;
290                 return $fail->() unless defined $r;
291                 return $end->() if $r == 0; # EOF
292                 if ($fh) { # stream body from git-http-backend to HTTP client
293                         $fh->write($buf);
294                         $buf = '';
295                         $read_disable->() if $read_disable;
296                 } elsif ($buf =~ s/\A(.*?)\r\n\r\n//s) { # parse headers
297                         my $h = $1;
298                         my $code = 200;
299                         my @h;
300                         foreach my $l (split(/\r\n/, $h)) {
301                                 my ($k, $v) = split(/:\s*/, $l, 2);
302                                 if ($k =~ /\AStatus\z/i) {
303                                         ($code) = ($v =~ /\b(\d+)\b/);
304                                 } else {
305                                         push @h, $k, $v;
306                                 }
307                         }
308                         if ($code == 403) {
309                                 # smart cloning disabled, serve dumbly
310                                 # in $end since we never undef $res in here
311                         } else { # write response header:
312                                 $fh = $res->([ $code, \@h ]);
313                                 $res = undef;
314                                 $fh->write($buf);
315                         }
316                         $buf = '';
317                 } # else { keep reading ... }
318         };
319         if (my $async = $env->{'pi-httpd.async'}) {
320                 # $async is PublicInbox::HTTPD::Async->new($rpipe, $cb)
321                 $rpipe = $async->($rpipe, $cb);
322                 sub { ($res) = @_ } # let Danga::Socket handle the rest.
323         } else { # synchronous loop for other PSGI servers
324                 $read_enable = $read_disable = undef;
325                 $vin = '';
326                 vec($vin, fileno($rpipe), 1) = 1;
327                 sub {
328                         ($res) = @_;
329                         while ($rpipe) { $cb->() }
330                 }
331         }
332 }
333
334 sub input_to_file {
335         my ($env) = @_;
336         my $in = IO::File->new_tmpfile;
337         my $input = $env->{'psgi.input'};
338         my $buf;
339         while (1) {
340                 my $r = $input->read($buf, 8192);
341                 unless (defined $r) {
342                         err($env, "error reading input: $!");
343                         return;
344                 }
345                 last if ($r == 0);
346                 $in->write($buf);
347         }
348         $in->flush;
349         $in->sysseek(0, SEEK_SET);
350         return $in;
351 }
352
353 1;