]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GitHTTPBackend.pm
spawn: allow passing GLOB handles for redirects
[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 PublicInbox::Qspawn;
14 use PublicInbox::Tmpfile;
15 use PublicInbox::WwwStatic;
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 my $prev = 0;
70 my $exp;
71 sub cache_one_year {
72         my ($h) = @_;
73         my $t = time + 31536000;
74         push @$h, 'Expires', $t == $prev ? $exp : ($exp = time2str($prev = $t)),
75                 'Cache-Control', 'public, max-age=31536000';
76 }
77
78 sub serve_dumb {
79         my ($env, $git, $path) = @_;
80
81         my $h = [];
82         my $type;
83         if ($path =~ m!\Aobjects/[a-f0-9]{2}/[a-f0-9]{38}\z!) {
84                 $type = 'application/x-git-loose-object';
85                 cache_one_year($h);
86         } elsif ($path =~ m!\Aobjects/pack/pack-[a-f0-9]{40}\.pack\z!) {
87                 $type = 'application/x-git-packed-objects';
88                 cache_one_year($h);
89         } elsif ($path =~ m!\Aobjects/pack/pack-[a-f0-9]{40}\.idx\z!) {
90                 $type = 'application/x-git-packed-objects-toc';
91                 cache_one_year($h);
92         } elsif ($path =~ /\A(?:$TEXT)\z/o) {
93                 $type = 'text/plain';
94                 push @$h, @no_cache;
95         } else {
96                 return r(404);
97         }
98         $path = "$git->{git_dir}/$path";
99         PublicInbox::WwwStatic::response($env, $h, $path, $type) // r(404);
100 }
101
102 sub git_parse_hdr { # {parse_hdr} for Qspawn
103         my ($r, $bref, $dumb_args) = @_;
104         my $res = parse_cgi_headers($r, $bref) or return; # incomplete
105         $res->[0] == 403 ? serve_dumb(@$dumb_args) : $res;
106 }
107
108 # returns undef if 403 so it falls back to dumb HTTP
109 sub serve_smart {
110         my ($env, $git, $path) = @_;
111         my %env = %ENV;
112         # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
113         # may be set in the server-process and are passed as-is
114         foreach my $name (qw(QUERY_STRING
115                                 REMOTE_USER REMOTE_ADDR
116                                 HTTP_CONTENT_ENCODING
117                                 CONTENT_TYPE
118                                 SERVER_PROTOCOL
119                                 REQUEST_METHOD)) {
120                 my $val = $env->{$name};
121                 $env{$name} = $val if defined $val;
122         }
123         my $limiter = $git->{-httpbackend_limiter} || $default_limiter;
124         $env{GIT_HTTP_EXPORT_ALL} = '1';
125         $env{PATH_TRANSLATED} = "$git->{git_dir}/$path";
126         my $rdr = input_prepare($env) or return r(500);
127         my $qsp = PublicInbox::Qspawn->new([qw(git http-backend)], \%env, $rdr);
128         $qsp->psgi_return($env, $limiter, \&git_parse_hdr, [$env, $git, $path]);
129 }
130
131 sub input_prepare {
132         my ($env) = @_;
133
134         my $input = $env->{'psgi.input'};
135         my $fd = eval { fileno($input) };
136         if (defined $fd && $fd >= 0) {
137                 return { 0 => $fd };
138         }
139         my $id = "git-http.input.$env->{REMOTE_ADDR}:$env->{REMOTE_PORT}";
140         my $in = tmpfile($id);
141         unless (defined $in) {
142                 err($env, "could not open temporary file: $!");
143                 return;
144         }
145         my $buf;
146         while (1) {
147                 my $r = $input->read($buf, 8192);
148                 unless (defined $r) {
149                         err($env, "error reading input: $!");
150                         return;
151                 }
152                 last if $r == 0;
153                 unless (print $in $buf) {
154                         err($env, "error writing temporary file: $!");
155                         return;
156                 }
157         }
158         # ensure it's visible to git-http-backend(1):
159         unless ($in->flush) {
160                 err($env, "error writing temporary file: $!");
161                 return;
162         }
163         unless (defined(sysseek($in, 0, SEEK_SET))) {
164                 err($env, "error seeking temporary file: $!");
165                 return;
166         }
167         { 0 => $in };
168 }
169
170 sub parse_cgi_headers {
171         my ($r, $bref) = @_;
172         return r(500) unless defined $r && $r >= 0;
173         $$bref =~ s/\A(.*?)\r?\n\r?\n//s or return $r == 0 ? r(500) : undef;
174         my $h = $1;
175         my $code = 200;
176         my @h;
177         foreach my $l (split(/\r?\n/, $h)) {
178                 my ($k, $v) = split(/:\s*/, $l, 2);
179                 if ($k =~ /\AStatus\z/i) {
180                         ($code) = ($v =~ /\b([0-9]+)\b/);
181                 } else {
182                         push @h, $k, $v;
183                 }
184         }
185         [ $code, \@h ]
186 }
187
188 1;