]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GitHTTPBackend.pm
git-http-backend: start refactoring to use callback
[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         if ($pid == 0) {
162                 # GIT_HTTP_EXPORT_ALL, GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
163                 # may be set in the server-process and are passed as-is
164                 foreach my $name (qw(QUERY_STRING
165                                         REMOTE_USER REMOTE_ADDR
166                                         HTTP_CONTENT_ENCODING
167                                         CONTENT_TYPE
168                                         SERVER_PROTOCOL
169                                         REQUEST_METHOD)) {
170                         my $val = $env->{$name};
171                         $ENV{$name} = $val if defined $val;
172                 }
173                 # $ENV{GIT_PROJECT_ROOT} = $git->{git_dir};
174                 $ENV{GIT_HTTP_EXPORT_ALL} = '1';
175                 $ENV{PATH_TRANSLATED} = "$git->{git_dir}/$path";
176                 dup2(fileno($in), 0) or die "redirect stdin failed: $!\n";
177                 dup2(fileno($wpipe), 1) or die "redirect stdout failed: $!\n";
178                 my @cmd = qw(git http-backend);
179                 exec(@cmd) or die 'exec `' . join(' ', @cmd). "' failed: $!\n";
180         }
181         $wpipe = $in = undef;
182         $rpipe->blocking(0);
183         $buf = '';
184         my $vin;
185         vec($vin, fileno($rpipe), 1) = 1;
186         my ($fh, $res);
187         my $fail = sub {
188                 my ($e) = @_;
189                 if ($e eq 'EAGAIN') {
190                         select($vin, undef, undef, undef);
191                 } else {
192                         $rpipe = undef;
193                         $fh->close if $fh;
194                         $err->print('git http-backend error: ', $e, "\n");
195                 }
196         };
197         my $cb = sub {
198                 my $r = sysread($rpipe, $buf, 8192, length($buf));
199                 return $fail->($!{EAGAIN} ? 'EAGAIN' : $!) unless defined $r;
200                 if ($r == 0) { # EOF
201                         $rpipe = undef;
202                         $fh->close if $fh;
203                         return;
204                 }
205                 if ($fh) { # stream body from git-http-backend to HTTP client
206                         $fh->write($buf);
207                         $buf = '';
208                 } elsif ($buf =~ s/\A(.*?)\r?\n\r?\n//s) { # parse headers
209                         my $h = $1;
210                         my $code = 200;
211                         my @h;
212                         foreach my $l (split(/\r?\n/, $h)) {
213                                 my ($k, $v) = split(/:\s*/, $l, 2);
214                                 if ($k =~ /\AStatus\z/i) {
215                                         $code = int($v);
216                                 } else {
217                                         push @h, $k, $v;
218                                 }
219                         }
220                         # write response header:
221                         $fh = $res->([ $code, \@h ]);
222                         $fh->write($buf);
223                         $buf = '';
224                 } # else { keep reading ... }
225         };
226         sub {
227                 ($res) = @_;
228                 while ($rpipe) { $cb->() }
229         };
230 }
231
232 1;