]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GitHTTPBackend.pm
git-http-backend: check EINTR as well as EAGAIN
[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                 $fh->close;
99         }
100 }
101
102 sub prepare_range {
103         my ($cgi, $in, $h, $beg, $end, $size) = @_;
104         my $code = 200;
105         my $len = $size;
106         if ($beg eq '') {
107                 if ($end ne '') { # "bytes=-$end" => last N bytes
108                         $beg = $size - $end;
109                         $beg = 0 if $beg < 0;
110                         $end = $size - 1;
111                         $code = 206;
112                 } else {
113                         $code = 416;
114                 }
115         } else {
116                 if ($beg > $size) {
117                         $code = 416;
118                 } elsif ($end eq '' || $end >= $size) {
119                         $end = $size - 1;
120                         $code = 206;
121                 } elsif ($end < $size) {
122                         $code = 206;
123                 } else {
124                         $code = 416;
125                 }
126         }
127         if ($code == 206) {
128                 $len = $end - $beg + 1;
129                 if ($len <= 0) {
130                         $code = 416;
131                 } else {
132                         seek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
133                         push @$h, qw(Accept-Ranges bytes Content-Range);
134                         push @$h, "bytes $beg-$end/$size";
135
136                         # FIXME: Plack::Middleware::Deflater bug?
137                         $cgi->{env}->{'psgix.no-compress'} = 1;
138                 }
139         }
140         ($code, $len);
141 }
142
143 # returns undef if 403 so it falls back to dumb HTTP
144 sub serve_smart {
145         my ($cgi, $git, $path) = @_;
146         my $env = $cgi->{env};
147
148         my $input = $env->{'psgi.input'};
149         my $buf;
150         my $in;
151         my $err = $env->{'psgi.errors'};
152         my $fd = eval { fileno($input) };
153         if (defined $fd && $fd >= 0) {
154                 $in = $input;
155         } else {
156                 $in = input_to_file($env) or return r(500);
157         }
158         my ($rpipe, $wpipe);
159         unless (pipe($rpipe, $wpipe)) {
160                 $err->print("error creating pipe: $! - going static\n");
161                 return;
162         }
163         my %env = %ENV;
164         # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
165         # may be set in the server-process and are passed as-is
166         foreach my $name (qw(QUERY_STRING
167                                 REMOTE_USER REMOTE_ADDR
168                                 HTTP_CONTENT_ENCODING
169                                 CONTENT_TYPE
170                                 SERVER_PROTOCOL
171                                 REQUEST_METHOD)) {
172                 my $val = $env->{$name};
173                 $env{$name} = $val if defined $val;
174         }
175         my $git_dir = $git->{git_dir};
176         $env{GIT_HTTP_EXPORT_ALL} = '1';
177         $env{PATH_TRANSLATED} = "$git_dir/$path";
178         my %rdr = ( 0 => fileno($in), 1 => fileno($wpipe) );
179         my $pid = spawn([qw(git http-backend)], \%env, \%rdr);
180         unless (defined $pid) {
181                 $err->print("error spawning: $! - going static\n");
182                 return;
183         }
184         $wpipe = $in = undef;
185         $buf = '';
186         my ($vin, $fh, $res);
187         $nr_running++;
188         my $end = sub {
189                 if ($fh) {
190                         $fh->close;
191                         $fh = undef;
192                 }
193                 if ($rpipe) {
194                         $rpipe->close; # _may_ be Danga::Socket::close
195                         $rpipe = undef;
196                         $nr_running--;
197                 }
198                 if (defined $pid && $pid != waitpid($pid, 0)) {
199                         $err->print("git http-backend ($git_dir): $?\n");
200                 } else {
201                         $pid = undef;
202                 }
203                 return unless $res;
204                 my $dumb = serve_dumb($cgi, $git, $path);
205                 ref($dumb) eq 'ARRAY' ? $res->($dumb) : $dumb->($res);
206         };
207         my $fail = sub {
208                 if ($!{EAGAIN} || $!{EINTR}) {
209                         select($vin, undef, undef, undef) if defined $vin;
210                         # $vin is undef on async, so this is a noop on EAGAIN
211                         return;
212                 }
213                 my $e = $!;
214                 $end->();
215                 $err->print("git http-backend ($git_dir): $e\n");
216         };
217         my $cb = sub { # read git-http-backend output and stream to client
218                 my $r = $rpipe ? $rpipe->sysread($buf, 8192, length($buf)) : 0;
219                 return $fail->() unless defined $r;
220                 return $end->() if $r == 0; # EOF
221                 if ($fh) { # stream body from git-http-backend to HTTP client
222                         $fh->write($buf);
223                         $buf = '';
224                 } elsif ($buf =~ s/\A(.*?)\r\n\r\n//s) { # parse headers
225                         my $h = $1;
226                         my $code = 200;
227                         my @h;
228                         foreach my $l (split(/\r\n/, $h)) {
229                                 my ($k, $v) = split(/:\s*/, $l, 2);
230                                 if ($k =~ /\AStatus\z/i) {
231                                         ($code) = ($v =~ /\b(\d+)\b/);
232                                 } else {
233                                         push @h, $k, $v;
234                                 }
235                         }
236                         if ($code == 403) {
237                                 # smart cloning disabled, serve dumbly
238                                 # in $end since we never undef $res in here
239                         } else { # write response header:
240                                 $fh = $res->([ $code, \@h ]);
241                                 $res = undef;
242                                 $fh->write($buf);
243                         }
244                         $buf = '';
245                 } # else { keep reading ... }
246         };
247         if (my $async = $env->{'pi-httpd.async'}) {
248                 $rpipe = $async->($rpipe, $cb);
249                 sub { ($res) = @_ } # let Danga::Socket handle the rest.
250         } else { # synchronous loop for other PSGI servers
251                 $vin = '';
252                 vec($vin, fileno($rpipe), 1) = 1;
253                 sub {
254                         ($res) = @_;
255                         while ($rpipe) { $cb->() }
256                 }
257         }
258 }
259
260 sub input_to_file {
261         my ($env) = @_;
262         my $in = IO::File->new_tmpfile;
263         my $input = $env->{'psgi.input'};
264         my $buf;
265         while (1) {
266                 my $r = $input->read($buf, 8192);
267                 unless (defined $r) {
268                         my $err = $env->{'psgi.errors'};
269                         $err->print("error reading input: $!\n");
270                         return;
271                 }
272                 last if ($r == 0);
273                 $in->write($buf);
274         }
275         $in->flush;
276         $in->sysseek(0, SEEK_SET);
277         return $in;
278 }
279
280 1;