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