]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GitHTTPBackend.pm
config: support "inboxdir" in addition to "mainrepo"
[public-inbox.git] / lib / PublicInbox / GitHTTPBackend.pm
1 # Copyright (C) 2016-2019 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.  This is our wrapper for git-http-backend(1)
6 package PublicInbox::GitHTTPBackend;
7 use strict;
8 use warnings;
9 use Fcntl qw(:seek);
10 use IO::Handle;
11 use HTTP::Date qw(time2str);
12 use HTTP::Status qw(status_message);
13 use Plack::Util;
14 use PublicInbox::Qspawn;
15 use PublicInbox::Tmpfile;
16
17 # 32 is same as the git-daemon connection limit
18 my $default_limiter = PublicInbox::Qspawn::Limiter->new(32);
19
20 # n.b. serving "description" and "cloneurl" should be innocuous enough to
21 # not cause problems.  serving "config" might...
22 my @text = qw[HEAD info/refs info/attributes
23         objects/info/(?:http-alternates|alternates|packs)
24         cloneurl description];
25
26 my @binary = qw!
27         objects/[a-f0-9]{2}/[a-f0-9]{38}
28         objects/pack/pack-[a-f0-9]{40}\.(?:pack|idx)
29         !;
30
31 our $ANY = join('|', @binary, @text, 'git-upload-pack');
32 my $BIN = join('|', @binary);
33 my $TEXT = join('|', @text);
34
35 my @no_cache = ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT',
36                 'Pragma', 'no-cache',
37                 'Cache-Control', 'no-cache, max-age=0, must-revalidate');
38
39 sub r ($;$) {
40         my ($code, $msg) = @_;
41         $msg ||= status_message($code);
42         my $len = length($msg);
43         [ $code, [qw(Content-Type text/plain Content-Length), $len, @no_cache],
44                 [$msg] ]
45 }
46
47 sub serve {
48         my ($env, $git, $path) = @_;
49
50         # XXX compatibility... ugh, can we stop supporting this?
51         $git = PublicInbox::Git->new($git) unless ref($git);
52
53         # Documentation/technical/http-protocol.txt in git.git
54         # requires one and exactly one query parameter:
55         if ($env->{QUERY_STRING} =~ /\Aservice=git-[A-Za-z0-9_]+-pack\z/ ||
56                                 $path =~ /\Agit-[A-Za-z0-9_]+-pack\z/) {
57                 my $ok = serve_smart($env, $git, $path);
58                 return $ok if $ok;
59         }
60
61         serve_dumb($env, $git, $path);
62 }
63
64 sub err ($@) {
65         my ($env, @msg) = @_;
66         $env->{'psgi.errors'}->print(@msg, "\n");
67 }
68
69 sub drop_client ($) {
70         if (my $io = $_[0]->{'psgix.io'}) {
71                 $io->close; # this is PublicInbox::DS::close
72         }
73 }
74
75 my $prev = 0;
76 my $exp;
77 sub cache_one_year {
78         my ($h) = @_;
79         my $t = time + 31536000;
80         push @$h, 'Expires', $t == $prev ? $exp : ($exp = time2str($prev = $t)),
81                 'Cache-Control', 'public, max-age=31536000';
82 }
83
84 sub static_result ($$$$) {
85         my ($env, $h, $f, $type) = @_;
86         return r(404) unless -f $f && -r _; # just in case it's a FIFO :P
87
88         # TODO: If-Modified-Since and Last-Modified?
89         open my $in, '<', $f or return r(404);
90         my $size = -s $in;
91         my $len = $size;
92         my $code = 200;
93         push @$h, 'Content-Type', $type;
94         if (($env->{HTTP_RANGE} || '') =~ /\bbytes=([0-9]*)-([0-9]*)\z/) {
95                 ($code, $len) = prepare_range($env, $in, $h, $1, $2, $size);
96                 if ($code == 416) {
97                         push @$h, 'Content-Range', "bytes */$size";
98                         return [ 416, $h, [] ];
99                 }
100         }
101         push @$h, 'Content-Length', $len;
102         my $n = 65536;
103         [ $code, $h, Plack::Util::inline_object(close => sub { close $in },
104                 getline => sub {
105                         return if $len == 0;
106                         $n = $len if $len < $n;
107                         my $r = sysread($in, my $buf, $n);
108                         if (!defined $r) {
109                                 err($env, "$f read error: $!");
110                         } elsif ($r <= 0) {
111                                 err($env, "$f EOF with $len bytes left");
112                         } else {
113                                 $len -= $r;
114                                 $n = 8192;
115                                 return $buf;
116                         }
117                         drop_client($env);
118                         return;
119                 })]
120 }
121
122 sub serve_dumb {
123         my ($env, $git, $path) = @_;
124
125         my $h = [];
126         my $type;
127         if ($path =~ m!\Aobjects/[a-f0-9]{2}/[a-f0-9]{38}\z!) {
128                 $type = 'application/x-git-loose-object';
129                 cache_one_year($h);
130         } elsif ($path =~ m!\Aobjects/pack/pack-[a-f0-9]{40}\.pack\z!) {
131                 $type = 'application/x-git-packed-objects';
132                 cache_one_year($h);
133         } elsif ($path =~ m!\Aobjects/pack/pack-[a-f0-9]{40}\.idx\z!) {
134                 $type = 'application/x-git-packed-objects-toc';
135                 cache_one_year($h);
136         } elsif ($path =~ /\A(?:$TEXT)\z/o) {
137                 $type = 'text/plain';
138                 push @$h, @no_cache;
139         } else {
140                 return r(404);
141         }
142
143         static_result($env, $h, "$git->{git_dir}/$path", $type);
144 }
145
146 sub prepare_range {
147         my ($env, $in, $h, $beg, $end, $size) = @_;
148         my $code = 200;
149         my $len = $size;
150         if ($beg eq '') {
151                 if ($end ne '') { # "bytes=-$end" => last N bytes
152                         $beg = $size - $end;
153                         $beg = 0 if $beg < 0;
154                         $end = $size - 1;
155                         $code = 206;
156                 } else {
157                         $code = 416;
158                 }
159         } else {
160                 if ($beg > $size) {
161                         $code = 416;
162                 } elsif ($end eq '' || $end >= $size) {
163                         $end = $size - 1;
164                         $code = 206;
165                 } elsif ($end < $size) {
166                         $code = 206;
167                 } else {
168                         $code = 416;
169                 }
170         }
171         if ($code == 206) {
172                 $len = $end - $beg + 1;
173                 if ($len <= 0) {
174                         $code = 416;
175                 } else {
176                         sysseek($in, $beg, SEEK_SET) or return [ 500, [], [] ];
177                         push @$h, qw(Accept-Ranges bytes Content-Range);
178                         push @$h, "bytes $beg-$end/$size";
179
180                         # FIXME: Plack::Middleware::Deflater bug?
181                         $env->{'psgix.no-compress'} = 1;
182                 }
183         }
184         ($code, $len);
185 }
186
187 # returns undef if 403 so it falls back to dumb HTTP
188 sub serve_smart {
189         my ($env, $git, $path) = @_;
190         my %env = %ENV;
191         # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
192         # may be set in the server-process and are passed as-is
193         foreach my $name (qw(QUERY_STRING
194                                 REMOTE_USER REMOTE_ADDR
195                                 HTTP_CONTENT_ENCODING
196                                 CONTENT_TYPE
197                                 SERVER_PROTOCOL
198                                 REQUEST_METHOD)) {
199                 my $val = $env->{$name};
200                 $env{$name} = $val if defined $val;
201         }
202         my $limiter = $git->{-httpbackend_limiter} || $default_limiter;
203         $env{GIT_HTTP_EXPORT_ALL} = '1';
204         $env{PATH_TRANSLATED} = "$git->{git_dir}/$path";
205         my $rdr = input_prepare($env) or return r(500);
206         my $qsp = PublicInbox::Qspawn->new([qw(git http-backend)], \%env, $rdr);
207         $qsp->psgi_return($env, $limiter, sub { # parse_hdr
208                 my ($r, $bref) = @_;
209                 my $res = parse_cgi_headers($r, $bref) or return; # incomplete
210                 $res->[0] == 403 ? serve_dumb($env, $git, $path) : $res;
211         });
212 }
213
214 sub input_prepare {
215         my ($env) = @_;
216
217         my $input = $env->{'psgi.input'};
218         my $fd = eval { fileno($input) };
219         if (defined $fd && $fd >= 0) {
220                 return { 0 => $fd };
221         }
222         my $id = "git-http.input.$env->{REMOTE_ADDR}:$env->{REMOTE_PORT}";
223         my $in = tmpfile($id);
224         unless (defined $in) {
225                 err($env, "could not open temporary file: $!");
226                 return;
227         }
228         my $buf;
229         while (1) {
230                 my $r = $input->read($buf, 8192);
231                 unless (defined $r) {
232                         err($env, "error reading input: $!");
233                         return;
234                 }
235                 last if $r == 0;
236                 unless (print $in $buf) {
237                         err($env, "error writing temporary file: $!");
238                         return;
239                 }
240         }
241         # ensure it's visible to git-http-backend(1):
242         unless ($in->flush) {
243                 err($env, "error writing temporary file: $!");
244                 return;
245         }
246         unless (defined(sysseek($in, 0, SEEK_SET))) {
247                 err($env, "error seeking temporary file: $!");
248                 return;
249         }
250         { 0 => fileno($in), -hold => $in };
251 }
252
253 sub parse_cgi_headers {
254         my ($r, $bref) = @_;
255         return r(500) unless defined $r && $r >= 0;
256         $$bref =~ s/\A(.*?)\r?\n\r?\n//s or return $r == 0 ? r(500) : undef;
257         my $h = $1;
258         my $code = 200;
259         my @h;
260         foreach my $l (split(/\r?\n/, $h)) {
261                 my ($k, $v) = split(/:\s*/, $l, 2);
262                 if ($k =~ /\AStatus\z/i) {
263                         ($code) = ($v =~ /\b([0-9]+)\b/);
264                 } else {
265                         push @h, $k, $v;
266                 }
267         }
268         [ $code, \@h ]
269 }
270
271 1;