]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GitHTTPBackend.pm
githttpbackend: simplify compatibility code
[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::Handle;
11 use HTTP::Date qw(time2str);
12 use HTTP::Status qw(status_message);
13 use Plack::Util;
14 use PublicInbox::Qspawn;
15
16 # 32 is same as the git-daemon connection limit
17 my $default_limiter = PublicInbox::Qspawn::Limiter->new(32);
18
19 # n.b. serving "description" and "cloneurl" should be innocuous enough to
20 # not cause problems.  serving "config" might...
21 my @text = qw[HEAD info/refs
22         objects/info/(?:http-alternates|alternates|packs)
23         cloneurl description];
24
25 my @binary = qw!
26         objects/[a-f0-9]{2}/[a-f0-9]{38}
27         objects/pack/pack-[a-f0-9]{40}\.(?:pack|idx)
28         !;
29
30 our $ANY = join('|', @binary, @text, 'git-upload-pack');
31 my $BIN = join('|', @binary);
32 my $TEXT = join('|', @text);
33
34 my @no_cache = ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT',
35                 'Pragma', 'no-cache',
36                 'Cache-Control', 'no-cache, max-age=0, must-revalidate');
37
38 sub r ($;$) {
39         my ($code, $msg) = @_;
40         $msg ||= status_message($code);
41         my $len = length($msg);
42         [ $code, [qw(Content-Type text/plain Content-Length), $len, @no_cache],
43                 [$msg] ]
44 }
45
46 sub serve {
47         my ($env, $git, $path) = @_;
48
49         # XXX compatibility... ugh, can we stop supporting this?
50         $git = PublicInbox::Git->new($git) unless ref($git);
51
52         # Documentation/technical/http-protocol.txt in git.git
53         # requires one and exactly one query parameter:
54         if ($env->{QUERY_STRING} =~ /\Aservice=git-\w+-pack\z/ ||
55                                 $path =~ /\Agit-\w+-pack\z/) {
56                 my $ok = serve_smart($env, $git, $path);
57                 return $ok if $ok;
58         }
59
60         serve_dumb($env, $git, $path);
61 }
62
63 sub err ($@) {
64         my ($env, @msg) = @_;
65         $env->{'psgi.errors'}->print(@msg, "\n");
66 }
67
68 sub drop_client ($) {
69         if (my $io = $_[0]->{'psgix.io'}) {
70                 $io->close; # this is Danga::Socket::close
71         }
72 }
73
74 my $prev = 0;
75 my $exp;
76 sub cache_one_year {
77         my ($h) = @_;
78         my $t = time + 31536000;
79         push @$h, 'Expires', $t == $prev ? $exp : ($exp = time2str($prev = $t)),
80                 'Cache-Control', 'public, max-age=31536000';
81 }
82
83 sub serve_dumb {
84         my ($env, $git, $path) = @_;
85
86         my @h;
87         my $type;
88         if ($path =~ m!\Aobjects/[a-f0-9]{2}/[a-f0-9]{38}\z!) {
89                 $type = 'application/x-git-loose-object';
90                 cache_one_year(\@h);
91         } elsif ($path =~ m!\Aobjects/pack/pack-[a-f0-9]{40}\.pack\z!) {
92                 $type = 'application/x-git-packed-objects';
93                 cache_one_year(\@h);
94         } elsif ($path =~ m!\Aobjects/pack/pack-[a-f0-9]{40}\.idx\z!) {
95                 $type = 'application/x-git-packed-objects-toc';
96                 cache_one_year(\@h);
97         } elsif ($path =~ /\A(?:$TEXT)\z/o) {
98                 $type = 'text/plain';
99                 push @h, @no_cache;
100         } else {
101                 return r(404);
102         }
103
104         my $f = $git->{git_dir} . '/' . $path;
105         return r(404) unless -f $f && -r _; # just in case it's a FIFO :P
106         my $size = -s _;
107
108         # TODO: If-Modified-Since and Last-Modified?
109         open my $in, '<', $f or return r(404);
110         my $len = $size;
111         my $code = 200;
112         push @h, 'Content-Type', $type;
113         if (($env->{HTTP_RANGE} || '') =~ /\bbytes=(\d*)-(\d*)\z/) {
114                 ($code, $len) = prepare_range($env, $in, \@h, $1, $2, $size);
115                 if ($code == 416) {
116                         push @h, 'Content-Range', "bytes */$size";
117                         return [ 416, \@h, [] ];
118                 }
119         }
120         push @h, 'Content-Length', $len;
121         my $n = 65536;
122         [ $code, \@h, Plack::Util::inline_object(close => sub { close $in },
123                 getline => sub {
124                         return if $len == 0;
125                         $n = $len if $len < $n;
126                         my $r = sysread($in, my $buf, $n);
127                         if (!defined $r) {
128                                 err($env, "$f read error: $!");
129                         } elsif ($r <= 0) {
130                                 err($env, "$f EOF with $len bytes left");
131                         } else {
132                                 $len -= $r;
133                                 $n = 8192;
134                                 return $buf;
135                         }
136                         drop_client($env);
137                         return;
138                 })]
139 }
140
141 sub prepare_range {
142         my ($env, $in, $h, $beg, $end, $size) = @_;
143         my $code = 200;
144         my $len = $size;
145         if ($beg eq '') {
146                 if ($end ne '') { # "bytes=-$end" => last N bytes
147                         $beg = $size - $end;
148                         $beg = 0 if $beg < 0;
149                         $end = $size - 1;
150                         $code = 206;
151                 } else {
152                         $code = 416;
153                 }
154         } else {
155                 if ($beg > $size) {
156                         $code = 416;
157                 } elsif ($end eq '' || $end >= $size) {
158                         $end = $size - 1;
159                         $code = 206;
160                 } elsif ($end < $size) {
161                         $code = 206;
162                 } else {
163                         $code = 416;
164                 }
165         }
166         if ($code == 206) {
167                 $len = $end - $beg + 1;
168                 if ($len <= 0) {
169                         $code = 416;
170                 } else {
171                         sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
172                         push @$h, qw(Accept-Ranges bytes Content-Range);
173                         push @$h, "bytes $beg-$end/$size";
174
175                         # FIXME: Plack::Middleware::Deflater bug?
176                         $env->{'psgix.no-compress'} = 1;
177                 }
178         }
179         ($code, $len);
180 }
181
182 # returns undef if 403 so it falls back to dumb HTTP
183 sub serve_smart {
184         my ($env, $git, $path) = @_;
185         my $in = $env->{'psgi.input'};
186         my $fd = eval { fileno($in) };
187         unless (defined $fd && $fd >= 0) {
188                 $in = input_to_file($env) or return r(500);
189         }
190         my %env = %ENV;
191         # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
192         # may be set in the server-process and are passed as-is
193         foreach my $name (qw(QUERY_STRING
194                                 REMOTE_USER REMOTE_ADDR
195                                 HTTP_CONTENT_ENCODING
196                                 CONTENT_TYPE
197                                 SERVER_PROTOCOL
198                                 REQUEST_METHOD)) {
199                 my $val = $env->{$name};
200                 $env{$name} = $val if defined $val;
201         }
202         my $limiter = $git->{-httpbackend_limiter} || $default_limiter;
203         my $git_dir = $git->{git_dir};
204         $env{GIT_HTTP_EXPORT_ALL} = '1';
205         $env{PATH_TRANSLATED} = "$git_dir/$path";
206         my $rdr = { 0 => fileno($in) };
207         my $qsp = PublicInbox::Qspawn->new([qw(git http-backend)], \%env, $rdr);
208         my ($fh, $rpipe);
209         my $end = sub {
210                 if (my $err = $qsp->finish) {
211                         err($env, "git http-backend ($git_dir): $err");
212                 }
213                 $fh->close if $fh; # async-only
214         };
215
216         # Danga::Socket users, we queue up the read_enable callback to
217         # fire after pending writes are complete:
218         my $buf = '';
219         my $rd_hdr = sub {
220                 my $r = sysread($rpipe, $buf, 1024, length($buf));
221                 return if !defined($r) && ($!{EINTR} || $!{EAGAIN});
222                 return r(500, 'http-backend error') unless $r;
223                 $r = parse_cgi_headers(\$buf) or return; # incomplete headers
224                 $r->[0] == 403 ? serve_dumb($env, $git, $path) : $r;
225         };
226         my $res;
227         my $async = $env->{'pi-httpd.async'}; # XXX unstable API
228         my $io = $env->{'psgix.io'};
229         my $cb = sub {
230                 my $r = $rd_hdr->() or return;
231                 $rd_hdr = undef;
232                 if (scalar(@$r) == 3) { # error:
233                         if ($async) {
234                                 $async->close; # calls rpipe->close
235                         } else {
236                                 $rpipe->close;
237                                 $end->();
238                         }
239                         return $res->($r);
240                 }
241                 if ($async) {
242                         $fh = $res->($r);
243                         return $async->async_pass($io, $fh, \$buf);
244                 }
245
246                 # for synchronous PSGI servers
247                 require PublicInbox::GetlineBody;
248                 $r->[2] = PublicInbox::GetlineBody->new($rpipe, $end, $buf);
249                 $res->($r);
250         };
251         sub {
252                 ($res) = @_;
253
254                 # hopefully this doesn't break any middlewares,
255                 # holding the input here is a waste of FDs and memory
256                 $env->{'psgi.input'} = undef;
257
258                 $qsp->start($limiter, sub { # may run later, much later...
259                         ($rpipe) = @_;
260                         $in = undef;
261                         if ($async) {
262                                 $async = $async->($rpipe, $cb, $end);
263                         } else { # generic PSGI
264                                 $cb->() while $rd_hdr;
265                         }
266                 });
267         };
268 }
269
270 sub input_to_file {
271         my ($env) = @_;
272         open(my $in, '+>', undef);
273         unless (defined $in) {
274                 err($env, "could not open temporary file: $!");
275                 return;
276         }
277         my $input = $env->{'psgi.input'};
278         my $buf;
279         while (1) {
280                 my $r = $input->read($buf, 8192);
281                 unless (defined $r) {
282                         err($env, "error reading input: $!");
283                         return;
284                 }
285                 my $off = 0;
286                 while ($r > 0) {
287                         my $w = syswrite($in, $buf, $r, $off);
288                         if (defined $w) {
289                                 $r -= $w;
290                                 $off += $w;
291                         } else {
292                                 err($env, "error writing temporary file: $!");
293                                 return;
294                         }
295                 }
296         }
297         unless (defined(sysseek($in, 0, SEEK_SET))) {
298                 err($env, "error seeking temporary file: $!");
299                 return;
300         }
301         return $in;
302 }
303
304 sub parse_cgi_headers {
305         my ($bref) = @_;
306         $$bref =~ s/\A(.*?)\r\n\r\n//s or return;
307         my $h = $1;
308         my $code = 200;
309         my @h;
310         foreach my $l (split(/\r\n/, $h)) {
311                 my ($k, $v) = split(/:\s*/, $l, 2);
312                 if ($k =~ /\AStatus\z/i) {
313                         ($code) = ($v =~ /\b(\d+)\b/);
314                 } else {
315                         push @h, $k, $v;
316                 }
317         }
318         [ $code, \@h ]
319 }
320
321 1;