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