]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GitHTTPBackend.pm
git-http-backend: start async API for streaming
[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 POSIX qw(dup2);
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         if (fileno($input) >= 0) {
136                 $in = $input;
137         } else { # FIXME untested
138                 $in = IO::File->new_tmpfile;
139                 while (1) {
140                         my $r = $input->read($buf, 8192);
141                         unless (defined $r) {
142                                 $err->print('error reading input: ', $!, "\n");
143                                 return r(500);
144                         }
145                         last if ($r == 0);
146                         $in->write($buf);
147                 }
148                 $in->flush;
149                 $in->sysseek(0, SEEK_SET);
150         }
151         my ($rpipe, $wpipe);
152         unless (pipe($rpipe, $wpipe)) {
153                 $err->print('error creating pipe', $!, "\n");
154                 return r(500);
155         }
156         my $pid = fork; # TODO: vfork under Linux...
157         unless (defined $pid) {
158                 $err->print('error forking: ', $!, "\n");
159                 return r(500);
160         }
161         my $git_dir = $git->{git_dir};
162         if ($pid == 0) {
163                 # GIT_HTTP_EXPORT_ALL, GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
164                 # may be set in the server-process and are passed as-is
165                 foreach my $name (qw(QUERY_STRING
166                                         REMOTE_USER REMOTE_ADDR
167                                         HTTP_CONTENT_ENCODING
168                                         CONTENT_TYPE
169                                         SERVER_PROTOCOL
170                                         REQUEST_METHOD)) {
171                         my $val = $env->{$name};
172                         $ENV{$name} = $val if defined $val;
173                 }
174                 # $ENV{GIT_PROJECT_ROOT} = $git->{git_dir};
175                 $ENV{GIT_HTTP_EXPORT_ALL} = '1';
176                 $ENV{PATH_TRANSLATED} = "$git_dir/$path";
177                 dup2(fileno($in), 0) or die "redirect stdin failed: $!\n";
178                 dup2(fileno($wpipe), 1) or die "redirect stdout failed: $!\n";
179                 my @cmd = qw(git http-backend);
180                 exec(@cmd) or die 'exec `' . join(' ', @cmd). "' failed: $!\n";
181         }
182         $wpipe = $in = undef;
183         $buf = '';
184         my ($vin, $fh, $res);
185         my $end = sub {
186                 if ($fh) {
187                         $fh->close;
188                         $fh = undef;
189                 } else {
190                         $res->(r(500)) if $res;
191                 }
192                 if ($rpipe) {
193                         $rpipe->close; # _may_ be Danga::Socket::close
194                         $rpipe = undef;
195                 }
196                 if (defined $pid) {
197                         my $wpid = $pid;
198                         $pid = undef;
199                         return if $wpid == waitpid($wpid, 0);
200                         $err->print("git http-backend ($git_dir): $?\n");
201                 }
202         };
203         my $fail = sub {
204                 my ($e) = @_;
205                 if ($e eq 'EAGAIN') {
206                         select($vin, undef, undef, undef) if defined $vin;
207                         # $vin is undef on async, so this is a noop on EAGAIN
208                         return;
209                 }
210                 $end->();
211                 $err->print("git http-backend ($git_dir): $e\n");
212         };
213         my $cb = sub { # read git-http-backend output and stream to client
214                 my $r = $rpipe ? $rpipe->sysread($buf, 8192, length($buf)) : 0;
215                 return $fail->($!{EAGAIN} ? 'EAGAIN' : $!) unless defined $r;
216                 return $end->() if $r == 0; # EOF
217                 if ($fh) { # stream body from git-http-backend to HTTP client
218                         $fh->write($buf);
219                         $buf = '';
220                 } elsif ($buf =~ s/\A(.*?)\r?\n\r?\n//s) { # parse headers
221                         my $h = $1;
222                         my $code = 200;
223                         my @h;
224                         foreach my $l (split(/\r?\n/, $h)) {
225                                 my ($k, $v) = split(/:\s*/, $l, 2);
226                                 if ($k =~ /\AStatus\z/i) {
227                                         $code = int($v);
228                                 } else {
229                                         push @h, $k, $v;
230                                 }
231                         }
232                         # write response header:
233                         $fh = $res->([ $code, \@h ]);
234                         $res = undef;
235                         $fh->write($buf);
236                         $buf = '';
237                 } # else { keep reading ... }
238         };
239         if (my $async = $env->{'pi-httpd.async'}) {
240                 $rpipe = $async->($rpipe, $cb);
241                 sub { ($res) = @_ } # let Danga::Socket handle the rest.
242         } else { # synchronous loop
243                 $vin = '';
244                 vec($vin, fileno($rpipe), 1) = 1;
245                 sub {
246                         ($res) = @_;
247                         while ($rpipe) { $cb->() }
248                 }
249         }
250 }
251
252 1;