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