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