]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GitHTTPBackend.pm
No ext_urls
[public-inbox.git] / lib / PublicInbox / GitHTTPBackend.pm
1 # Copyright (C) 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 v5.10.1;
9 use Fcntl qw(:seek);
10 use IO::Handle; # ->flush
11 use HTTP::Date qw(time2str);
12 use PublicInbox::Qspawn;
13 use PublicInbox::Tmpfile;
14 use PublicInbox::WwwStatic qw(r @NO_CACHE);
15 use Carp ();
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 = ('objects/[a-f0-9]{2}/[a-f0-9]{38,62}',
27         'objects/pack/pack-[a-f0-9]{40,64}\.(?:pack|idx)');
28
29 our $ANY = join('|', @binary, @text, 'git-upload-pack');
30 my $TEXT = join('|', @text);
31
32 sub serve {
33         my ($env, $git, $path) = @_;
34
35         # Documentation/technical/http-protocol.txt in git.git
36         # requires one and exactly one query parameter:
37         if ($env->{QUERY_STRING} =~ /\Aservice=git-[A-Za-z0-9_]+-pack\z/ ||
38                                 $path =~ /\Agit-[A-Za-z0-9_]+-pack\z/) {
39                 my $ok = serve_smart($env, $git, $path);
40                 return $ok if $ok;
41         }
42
43         serve_dumb($env, $git, $path);
44 }
45
46 sub ucarp { Carp::carp(@_); undef }
47
48 my $prev = 0;
49 my $exp;
50 sub cache_one_year {
51         my ($h) = @_;
52         my $t = time + 31536000;
53         push @$h, 'Expires', $t == $prev ? $exp : ($exp = time2str($prev = $t)),
54                 'Cache-Control', 'public, max-age=31536000';
55 }
56
57 sub serve_dumb {
58         my ($env, $git, $path) = @_;
59
60         my $h = [];
61         my $type;
62         if ($path =~ m!\Aobjects/[a-f0-9]{2}/[a-f0-9]{38,62}\z!) {
63                 $type = 'application/x-git-loose-object';
64                 cache_one_year($h);
65         } elsif ($path =~ m!\Aobjects/pack/pack-[a-f0-9]{40,64}\.pack\z!) {
66                 $type = 'application/x-git-packed-objects';
67                 cache_one_year($h);
68         } elsif ($path =~ m!\Aobjects/pack/pack-[a-f0-9]{40,64}\.idx\z!) {
69                 $type = 'application/x-git-packed-objects-toc';
70                 cache_one_year($h);
71         } elsif ($path =~ /\A(?:$TEXT)\z/o) {
72                 $type = 'text/plain';
73                 push @$h, @NO_CACHE;
74         } else {
75                 return r(404);
76         }
77         $path = "$git->{git_dir}/$path";
78         PublicInbox::WwwStatic::response($env, $h, $path, $type);
79 }
80
81 sub git_parse_hdr { # {parse_hdr} for Qspawn
82         my ($r, $bref, $dumb_args) = @_;
83         my $res = parse_cgi_headers($r, $bref) or return; # incomplete
84         $res->[0] == 403 ? serve_dumb(@$dumb_args) : $res;
85 }
86
87 # returns undef if 403 so it falls back to dumb HTTP
88 sub serve_smart {
89         my ($env, $git, $path) = @_;
90         my %env = %ENV;
91         # GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL
92         # may be set in the server-process and are passed as-is
93         foreach my $name (qw(QUERY_STRING
94                                 REMOTE_USER REMOTE_ADDR
95                                 HTTP_CONTENT_ENCODING
96                                 HTTP_GIT_PROTOCOL
97                                 CONTENT_TYPE
98                                 SERVER_PROTOCOL
99                                 REQUEST_METHOD)) {
100                 my $val = $env->{$name};
101                 $env{$name} = $val if defined $val;
102         }
103         my $limiter = $git->{-httpbackend_limiter} || $default_limiter;
104         $env{GIT_HTTP_EXPORT_ALL} = '1';
105         $env{PATH_TRANSLATED} = "$git->{git_dir}/$path";
106         my $rdr = input_prepare($env) or return r(500);
107         my $qsp = PublicInbox::Qspawn->new([qw(git http-backend)], \%env, $rdr);
108         $qsp->psgi_return($env, $limiter, \&git_parse_hdr, [$env, $git, $path]);
109 }
110
111 sub input_prepare {
112         my ($env) = @_;
113
114         my $input = $env->{'psgi.input'};
115         my $fd = eval { fileno($input) };
116         return { 0 => $fd } if (defined $fd && $fd >= 0);
117         my $id = "git-http.input.$env->{REMOTE_ADDR}:$env->{REMOTE_PORT}";
118         my $in = tmpfile($id) // return ucarp("tmpfile: $!");
119         my $buf;
120         while (1) {
121                 my $r = $input->read($buf, 8192) // return ucarp("read $!");
122                 last if $r == 0;
123                 print $in $buf // return ucarp("print: $!");
124         }
125         # ensure it's visible to git-http-backend(1):
126         $in->flush // return ucarp("flush: $!");
127         sysseek($in, 0, SEEK_SET) // return ucarp($env, "seek: $!");
128         { 0 => $in };
129 }
130
131 sub parse_cgi_headers { # {parse_hdr} for Qspawn
132         my ($r, $bref, $ctx) = @_;
133         return r(500) unless defined $r && $r >= 0;
134         $$bref =~ s/\A(.*?)\r?\n\r?\n//s or return $r == 0 ? r(500) : undef;
135         my $h = $1;
136         my $code = 200;
137         my @h;
138         foreach my $l (split(/\r?\n/, $h)) {
139                 my ($k, $v) = split(/:\s*/, $l, 2);
140                 if ($k =~ /\AStatus\z/i) {
141                         ($code) = ($v =~ /\b([0-9]+)\b/);
142                 } else {
143                         push @h, $k, $v;
144                 }
145         }
146
147         # fallback to WwwCoderepo if cgit 404s.  Duplicating $ctx prevents
148         # ->finalize from the current Qspawn from using qspawn.wcb.
149         # This makes qspawn skip ->async_pass and causes
150         # PublicInbox::HTTPD::Async::event_step to close shortly after
151         if ($code == 404 && $ctx->{www} && !$ctx->{_coderepo_tried}++) {
152                 my $wcb = delete $ctx->{env}->{'qspawn.wcb'};
153                 $ctx->{env}->{'plack.skip-deflater'} = 1; # prevent 2x gzip
154                 $ctx->{env}->{'qspawn.fallback'} = $code;
155                 my $res = $ctx->{www}->coderepo->srv($ctx);
156                 # for ->psgi_return_init_cb
157                 $ctx->{env}->{'qspawn.wcb'} = $wcb;
158                 $res; # CODE or ARRAY ref
159         } else {
160                 [ $code, \@h ]
161         }
162 }
163
164 1;