]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GitHTTPBackend.pm
git-http-backend: do not drop connection on successful finish
[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 my $nextq;
37 sub do_next () {
38         my $q = $nextq;
39         $nextq = undef;
40         while (my $cb = shift @$q) {
41                 $cb->(); # this may redefine nextq
42         }
43 }
44
45 sub r {
46         [ $_[0] , [qw(Content-Type text/plain Content-Length 0) ], [] ]
47 }
48
49 sub serve {
50         my ($cgi, $git, $path) = @_;
51         return serve_dumb($cgi, $git, $path) if $nr_running >= $LIMIT;
52
53         my $service = $cgi->param('service') || '';
54         if ($service =~ /\Agit-\w+-pack\z/ || $path =~ /\Agit-\w+-pack\z/) {
55                 my $ok = serve_smart($cgi, $git, $path);
56                 return $ok if $ok;
57         }
58
59         serve_dumb($cgi, $git, $path);
60 }
61
62 sub err ($@) {
63         my ($env, @msg) = @_;
64         $env->{'psgi.errors'}->print(@msg, "\n");
65 }
66
67 sub drop_client ($) {
68         if (my $io = $_[0]->{'psgix.io'}) {
69                 $io->close; # this is Danga::Socket::close
70         }
71 }
72
73 sub serve_dumb {
74         my ($cgi, $git, $path) = @_;
75
76         my $type;
77         if ($path =~ /\A(?:$BIN)\z/o) {
78                 $type = 'application/octet-stream';
79         } elsif ($path =~ /\A(?:$TEXT)\z/o) {
80                 $type = 'text/plain';
81         } else {
82                 return r(404);
83         }
84
85         my $f = "$git->{git_dir}/$path";
86         return r(404) unless -f $f && -r _; # just in case it's a FIFO :P
87         my @st = stat(_);
88         my $size = $st[7];
89         my $env = $cgi->{env};
90
91         # TODO: If-Modified-Since and Last-Modified?
92         open my $in, '<', $f or return r(404);
93         my $len = $size;
94         my $n = 65536; # try to negotiate a big TCP window, first
95         my ($next, $fh);
96         my $cb = sub {
97                 $n = $len if $len < $n;
98                 my $r = sysread($in, my $buf, $n);
99                 if (!defined $r) {
100                         err($env, "$f read error: $!");
101                         drop_client($env);
102                 } elsif ($r <= 0) {
103                         err($env, "$f EOF with $len bytes left");
104                         drop_client($env);
105                 } else {
106                         $len -= $r;
107                         $fh->write($buf);
108                         if ($len == 0) {
109                                 $fh->close;
110                         } elsif ($next) {
111                                 # avoid recursion in Danga::Socket::write
112                                 unless ($nextq) {
113                                         $nextq = [];
114                                         Danga::Socket->AddTimer(0, *do_next);
115                                 }
116                                 # avoid buffering too much in case we have
117                                 # slow clients:
118                                 $n = 8192;
119                                 push @$nextq, $next;
120                                 return;
121                         }
122                 }
123                 # all done, cleanup references:
124                 $fh = $next = undef;
125         };
126
127         my $code = 200;
128         my @h = ('Content-Type', $type);
129         my $range = $env->{HTTP_RANGE};
130         if (defined $range && $range =~ /\bbytes=(\d*)-(\d*)\z/) {
131                 ($code, $len) = prepare_range($cgi, $in, \@h, $1, $2, $size);
132                 if ($code == 416) {
133                         push @h, 'Content-Range', "bytes */$size";
134                         return [ 416, \@h, [] ];
135                 }
136         }
137         push @h, 'Content-Length', $len;
138
139         sub {
140                 my ($res) = @_; # Plack callback
141                 $fh = $res->([ $code, \@h ]);
142                 if (defined $env->{'pi-httpd.async'}) {
143                         my $pi_http = $env->{'psgix.io'};
144                         $next = sub { $pi_http->write($cb) };
145                         $cb->(); # start it off!
146                 } else {
147                         $cb->() while $fh;
148                 }
149         }
150 }
151
152 sub prepare_range {
153         my ($cgi, $in, $h, $beg, $end, $size) = @_;
154         my $code = 200;
155         my $len = $size;
156         if ($beg eq '') {
157                 if ($end ne '') { # "bytes=-$end" => last N bytes
158                         $beg = $size - $end;
159                         $beg = 0 if $beg < 0;
160                         $end = $size - 1;
161                         $code = 206;
162                 } else {
163                         $code = 416;
164                 }
165         } else {
166                 if ($beg > $size) {
167                         $code = 416;
168                 } elsif ($end eq '' || $end >= $size) {
169                         $end = $size - 1;
170                         $code = 206;
171                 } elsif ($end < $size) {
172                         $code = 206;
173                 } else {
174                         $code = 416;
175                 }
176         }
177         if ($code == 206) {
178                 $len = $end - $beg + 1;
179                 if ($len <= 0) {
180                         $code = 416;
181                 } else {
182                         sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
183                         push @$h, qw(Accept-Ranges bytes Content-Range);
184                         push @$h, "bytes $beg-$end/$size";
185
186                         # FIXME: Plack::Middleware::Deflater bug?
187                         $cgi->{env}->{'psgix.no-compress'} = 1;
188                 }
189         }
190         ($code, $len);
191 }
192
193 # returns undef if 403 so it falls back to dumb HTTP
194 sub serve_smart {
195         my ($cgi, $git, $path) = @_;
196         my $env = $cgi->{env};
197
198         my $input = $env->{'psgi.input'};
199         my $buf;
200         my $in;
201         my $fd = eval { fileno($input) };
202         if (defined $fd && $fd >= 0) {
203                 $in = $input;
204         } else {
205                 $in = input_to_file($env) or return r(500);
206         }
207         my ($rpipe, $wpipe);
208         unless (pipe($rpipe, $wpipe)) {
209                 err($env, "error creating pipe: $! - going static");
210                 return;
211         }
212         my %env = %ENV;
213         # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
214         # may be set in the server-process and are passed as-is
215         foreach my $name (qw(QUERY_STRING
216                                 REMOTE_USER REMOTE_ADDR
217                                 HTTP_CONTENT_ENCODING
218                                 CONTENT_TYPE
219                                 SERVER_PROTOCOL
220                                 REQUEST_METHOD)) {
221                 my $val = $env->{$name};
222                 $env{$name} = $val if defined $val;
223         }
224         my $git_dir = $git->{git_dir};
225         $env{GIT_HTTP_EXPORT_ALL} = '1';
226         $env{PATH_TRANSLATED} = "$git_dir/$path";
227         my %rdr = ( 0 => fileno($in), 1 => fileno($wpipe) );
228         my $pid = spawn([qw(git http-backend)], \%env, \%rdr);
229         unless (defined $pid) {
230                 err($env, "error spawning: $! - going static");
231                 return;
232         }
233         $wpipe = $in = undef;
234         $buf = '';
235         my ($vin, $fh, $res);
236         $nr_running++;
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                         $nr_running--;
258                 }
259                 if (defined $pid) {
260                         my $e = $pid == waitpid($pid, 0) ?
261                                 $? : "PID:$pid still running?";
262                         err($env, "git http-backend ($git_dir): $e") if $e;
263                 }
264                 return unless $res;
265                 my $dumb = serve_dumb($cgi, $git, $path);
266                 ref($dumb) eq 'ARRAY' ? $res->($dumb) : $dumb->($res);
267         };
268         my $fail = sub {
269                 if ($!{EAGAIN} || $!{EINTR}) {
270                         select($vin, undef, undef, undef) if defined $vin;
271                         # $vin is undef on async, so this is a noop on EAGAIN
272                         return;
273                 }
274                 my $e = $!;
275                 $end->();
276                 err($env, "git http-backend ($git_dir): $e\n");
277         };
278         my $cb = sub { # read git-http-backend output and stream to client
279                 my $r = $rpipe ? $rpipe->sysread($buf, 8192, length($buf)) : 0;
280                 return $fail->() unless defined $r;
281                 return $end->() if $r == 0; # EOF
282                 if ($fh) { # stream body from git-http-backend to HTTP client
283                         $fh->write($buf);
284                         $buf = '';
285                         $read_disable->() if $read_disable;
286                 } elsif ($buf =~ s/\A(.*?)\r\n\r\n//s) { # parse headers
287                         my $h = $1;
288                         my $code = 200;
289                         my @h;
290                         foreach my $l (split(/\r\n/, $h)) {
291                                 my ($k, $v) = split(/:\s*/, $l, 2);
292                                 if ($k =~ /\AStatus\z/i) {
293                                         ($code) = ($v =~ /\b(\d+)\b/);
294                                 } else {
295                                         push @h, $k, $v;
296                                 }
297                         }
298                         if ($code == 403) {
299                                 # smart cloning disabled, serve dumbly
300                                 # in $end since we never undef $res in here
301                         } else { # write response header:
302                                 $fh = $res->([ $code, \@h ]);
303                                 $res = undef;
304                                 $fh->write($buf);
305                         }
306                         $buf = '';
307                 } # else { keep reading ... }
308         };
309         if (my $async = $env->{'pi-httpd.async'}) {
310                 # $async is PublicInbox::HTTPD::Async->new($rpipe, $cb)
311                 $rpipe = $async->($rpipe, $cb);
312                 sub { ($res) = @_ } # let Danga::Socket handle the rest.
313         } else { # synchronous loop for other PSGI servers
314                 $read_enable = $read_disable = undef;
315                 $vin = '';
316                 vec($vin, fileno($rpipe), 1) = 1;
317                 sub {
318                         ($res) = @_;
319                         while ($rpipe) { $cb->() }
320                 }
321         }
322 }
323
324 sub input_to_file {
325         my ($env) = @_;
326         my $in = IO::File->new_tmpfile;
327         my $input = $env->{'psgi.input'};
328         my $buf;
329         while (1) {
330                 my $r = $input->read($buf, 8192);
331                 unless (defined $r) {
332                         err($env, "error reading input: $!");
333                         return;
334                 }
335                 last if ($r == 0);
336                 $in->write($buf);
337         }
338         $in->flush;
339         $in->sysseek(0, SEEK_SET);
340         return $in;
341 }
342
343 1;