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