]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GitHTTPBackend.pm
git-http-backend: remove process limit
[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 $n = 65536; # try to negotiate a big TCP window, first
96         my ($next, $fh);
97         my $cb = sub {
98                 $n = $len if $len < $n;
99                 my $r = sysread($in, my $buf, $n);
100                 if (!defined $r) {
101                         err($env, "$f read error: $!");
102                         drop_client($env);
103                 } elsif ($r <= 0) {
104                         err($env, "$f EOF with $len bytes left");
105                         drop_client($env);
106                 } else {
107                         $len -= $r;
108                         $fh->write($buf);
109                         if ($len == 0) {
110                                 $fh->close;
111                         } elsif ($next) {
112                                 # avoid recursion in Danga::Socket::write
113                                 unless ($nextq) {
114                                         $nextq = [];
115                                         Danga::Socket->AddTimer(0, *do_next);
116                                 }
117                                 # avoid buffering too much in case we have
118                                 # slow clients:
119                                 $n = 8192;
120                                 push @$nextq, $next;
121                                 return;
122                         }
123                 }
124                 # all done, cleanup references:
125                 $fh = $next = undef;
126         };
127
128         my $code = 200;
129         push @h, 'Content-Type', $type;
130         my $range = $env->{HTTP_RANGE};
131         if (defined $range && $range =~ /\bbytes=(\d*)-(\d*)\z/) {
132                 ($code, $len) = prepare_range($cgi, $in, \@h, $1, $2, $size);
133                 if ($code == 416) {
134                         push @h, 'Content-Range', "bytes */$size";
135                         return [ 416, \@h, [] ];
136                 }
137         }
138         push @h, 'Content-Length', $len;
139
140         sub {
141                 my ($res) = @_; # Plack callback
142                 $fh = $res->([ $code, \@h ]);
143                 if (defined $env->{'pi-httpd.async'}) {
144                         my $pi_http = $env->{'psgix.io'};
145                         $next = sub { $pi_http->write($cb) };
146                         $cb->(); # start it off!
147                 } else {
148                         $cb->() while $fh;
149                 }
150         }
151 }
152
153 sub prepare_range {
154         my ($cgi, $in, $h, $beg, $end, $size) = @_;
155         my $code = 200;
156         my $len = $size;
157         if ($beg eq '') {
158                 if ($end ne '') { # "bytes=-$end" => last N bytes
159                         $beg = $size - $end;
160                         $beg = 0 if $beg < 0;
161                         $end = $size - 1;
162                         $code = 206;
163                 } else {
164                         $code = 416;
165                 }
166         } else {
167                 if ($beg > $size) {
168                         $code = 416;
169                 } elsif ($end eq '' || $end >= $size) {
170                         $end = $size - 1;
171                         $code = 206;
172                 } elsif ($end < $size) {
173                         $code = 206;
174                 } else {
175                         $code = 416;
176                 }
177         }
178         if ($code == 206) {
179                 $len = $end - $beg + 1;
180                 if ($len <= 0) {
181                         $code = 416;
182                 } else {
183                         sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
184                         push @$h, qw(Accept-Ranges bytes Content-Range);
185                         push @$h, "bytes $beg-$end/$size";
186
187                         # FIXME: Plack::Middleware::Deflater bug?
188                         $cgi->{env}->{'psgix.no-compress'} = 1;
189                 }
190         }
191         ($code, $len);
192 }
193
194 # returns undef if 403 so it falls back to dumb HTTP
195 sub serve_smart {
196         my ($cgi, $git, $path) = @_;
197         my $env = $cgi->{env};
198
199         my $input = $env->{'psgi.input'};
200         my $buf;
201         my $in;
202         my $fd = eval { fileno($input) };
203         if (defined $fd && $fd >= 0) {
204                 $in = $input;
205         } else {
206                 $in = input_to_file($env) or return r(500);
207         }
208         my ($rpipe, $wpipe);
209         unless (pipe($rpipe, $wpipe)) {
210                 err($env, "error creating pipe: $! - going static");
211                 return;
212         }
213         my %env = %ENV;
214         # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
215         # may be set in the server-process and are passed as-is
216         foreach my $name (qw(QUERY_STRING
217                                 REMOTE_USER REMOTE_ADDR
218                                 HTTP_CONTENT_ENCODING
219                                 CONTENT_TYPE
220                                 SERVER_PROTOCOL
221                                 REQUEST_METHOD)) {
222                 my $val = $env->{$name};
223                 $env{$name} = $val if defined $val;
224         }
225         my $git_dir = $git->{git_dir};
226         $env{GIT_HTTP_EXPORT_ALL} = '1';
227         $env{PATH_TRANSLATED} = "$git_dir/$path";
228         my %rdr = ( 0 => fileno($in), 1 => fileno($wpipe) );
229         my $pid = spawn([qw(git http-backend)], \%env, \%rdr);
230         unless (defined $pid) {
231                 err($env, "error spawning: $! - going static");
232                 return;
233         }
234         $wpipe = $in = undef;
235         $buf = '';
236         my ($vin, $fh, $res);
237
238         # Danga::Socket users, we queue up the read_enable callback to
239         # fire after pending writes are complete:
240         my $pi_http = $env->{'psgix.io'};
241         my $read_enable = sub { $rpipe->watch_read(1) };
242         my $read_disable = sub {
243                 $rpipe->watch_read(0);
244                 $pi_http->write($read_enable);
245         };
246
247         my $end = sub {
248                 if ($fh) {
249                         $fh->close;
250                         $fh = undef;
251                 }
252                 if ($rpipe) {
253                         # _may_ be Danga::Socket::close via
254                         # PublicInbox::HTTPD::Async::close:
255                         $rpipe->close;
256                         $rpipe = undef;
257                 }
258                 if (defined $pid) {
259                         my $e = $pid == waitpid($pid, 0) ?
260                                 $? : "PID:$pid still running?";
261                         err($env, "git http-backend ($git_dir): $e") if $e;
262                 }
263                 return unless $res;
264                 my $dumb = serve_dumb($cgi, $git, $path);
265                 ref($dumb) eq 'ARRAY' ? $res->($dumb) : $dumb->($res);
266         };
267         my $fail = sub {
268                 if ($!{EAGAIN} || $!{EINTR}) {
269                         select($vin, undef, undef, undef) if defined $vin;
270                         # $vin is undef on async, so this is a noop on EAGAIN
271                         return;
272                 }
273                 my $e = $!;
274                 $end->();
275                 err($env, "git http-backend ($git_dir): $e\n");
276         };
277         my $cb = sub { # read git-http-backend output and stream to client
278                 my $r = $rpipe ? $rpipe->sysread($buf, 8192, length($buf)) : 0;
279                 return $fail->() unless defined $r;
280                 return $end->() if $r == 0; # EOF
281                 if ($fh) { # stream body from git-http-backend to HTTP client
282                         $fh->write($buf);
283                         $buf = '';
284                         $read_disable->() if $read_disable;
285                 } elsif ($buf =~ s/\A(.*?)\r\n\r\n//s) { # parse headers
286                         my $h = $1;
287                         my $code = 200;
288                         my @h;
289                         foreach my $l (split(/\r\n/, $h)) {
290                                 my ($k, $v) = split(/:\s*/, $l, 2);
291                                 if ($k =~ /\AStatus\z/i) {
292                                         ($code) = ($v =~ /\b(\d+)\b/);
293                                 } else {
294                                         push @h, $k, $v;
295                                 }
296                         }
297                         if ($code == 403) {
298                                 # smart cloning disabled, serve dumbly
299                                 # in $end since we never undef $res in here
300                         } else { # write response header:
301                                 $fh = $res->([ $code, \@h ]);
302                                 $res = undef;
303                                 $fh->write($buf);
304                         }
305                         $buf = '';
306                 } # else { keep reading ... }
307         };
308         if (my $async = $env->{'pi-httpd.async'}) {
309                 # $async is PublicInbox::HTTPD::Async->new($rpipe, $cb)
310                 $rpipe = $async->($rpipe, $cb);
311                 sub { ($res) = @_ } # let Danga::Socket handle the rest.
312         } else { # synchronous loop for other PSGI servers
313                 $read_enable = $read_disable = undef;
314                 $vin = '';
315                 vec($vin, fileno($rpipe), 1) = 1;
316                 sub {
317                         ($res) = @_;
318                         while ($rpipe) { $cb->() }
319                 }
320         }
321 }
322
323 sub input_to_file {
324         my ($env) = @_;
325         my $in = IO::File->new_tmpfile;
326         my $input = $env->{'psgi.input'};
327         my $buf;
328         while (1) {
329                 my $r = $input->read($buf, 8192);
330                 unless (defined $r) {
331                         err($env, "error reading input: $!");
332                         return;
333                 }
334                 last if ($r == 0);
335                 $in->write($buf);
336         }
337         $in->flush;
338         $in->sysseek(0, SEEK_SET);
339         return $in;
340 }
341
342 1;