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