]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WwwListing.pm
wwwlisting: do not rely on $? after ProcessPipe::CLOSE
[public-inbox.git] / lib / PublicInbox / WwwListing.pm
1 # Copyright (C) 2019 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Provide an HTTP-accessible listing of inboxes.
5 # Used by PublicInbox::WWW
6 package PublicInbox::WwwListing;
7 use strict;
8 use warnings;
9 use PublicInbox::Hval qw(ascii_html);
10 use PublicInbox::Linkify;
11 use PublicInbox::View;
12 use PublicInbox::Inbox;
13 use bytes ();
14 use HTTP::Date qw(time2str);
15 require Digest::SHA;
16 require File::Spec;
17 *try_cat = \&PublicInbox::Inbox::try_cat;
18
19 sub list_all ($$$) {
20         my ($self, $env, $hide_key) = @_;
21         my @list;
22         $self->{pi_config}->each_inbox(sub {
23                 my ($ibx) = @_;
24                 push @list, $ibx unless $ibx->{-hide}->{$hide_key};
25         });
26         \@list;
27 }
28
29 sub list_match_domain ($$$) {
30         my ($self, $env, $hide_key) = @_;
31         my @list;
32         my $host = $env->{HTTP_HOST} // $env->{SERVER_NAME};
33         $host =~ s/:[0-9]+\z//;
34         my $re = qr!\A(?:https?:)?//\Q$host\E(?::[0-9]+)?/!i;
35         $self->{pi_config}->each_inbox(sub {
36                 my ($ibx) = @_;
37                 if (!$ibx->{-hide}->{$hide_key} && $ibx->{url} =~ $re) {
38                         push @list, $ibx;
39                 }
40         });
41         \@list;
42 }
43
44 sub list_404 ($$) { [] }
45
46 # TODO: +cgit
47 my %VALID = (
48         all => *list_all,
49         'match=domain' => *list_match_domain,
50         404 => *list_404,
51 );
52
53 sub set_cb ($$$) {
54         my ($pi_config, $k, $default) = @_;
55         my $v = $pi_config->{lc $k} // $default;
56         $VALID{$v} || do {
57                 warn <<"";
58 `$v' is not a valid value for `$k'
59 $k be one of `all', `match=domain', or `404'
60
61                 $VALID{$default};
62         };
63 }
64
65 sub new {
66         my ($class, $www) = @_;
67         my $pi_config = $www->{pi_config};
68         bless {
69                 pi_config => $pi_config,
70                 style => $www->style("\0"),
71                 www_cb => set_cb($pi_config, 'publicInbox.wwwListing', 404),
72                 manifest_cb => set_cb($pi_config, 'publicInbox.grokManifest',
73                                         'match=domain'),
74         }, $class;
75 }
76
77 sub ibx_entry {
78         my ($mtime, $ibx, $env) = @_;
79         my $ts = PublicInbox::View::fmt_ts($mtime);
80         my $url = PublicInbox::Hval::prurl($env, $ibx->{url});
81         my $tmp = <<"";
82 * $ts - $url
83   ${\$ibx->description}
84
85         if (defined(my $info_url = $ibx->{info_url})) {
86                 $tmp .= "\n$info_url";
87         }
88         $tmp;
89 }
90
91 sub html ($$) {
92         my ($env, $list) = @_;
93         my $title = 'public-inbox';
94         my $out = '';
95         my $code = 404;
96         if (@$list) {
97                 $title .= ' - listing';
98                 $code = 200;
99
100                 # Schwartzian transform since Inbox->modified is expensive
101                 @$list = sort {
102                         $b->[0] <=> $a->[0]
103                 } map { [ $_->modified, $_ ] } @$list;
104
105                 my $tmp = join("\n", map { ibx_entry(@$_, $env) } @$list);
106                 my $l = PublicInbox::Linkify->new;
107                 $l->linkify_1($tmp);
108                 $out = '<pre>'.$l->linkify_2(ascii_html($tmp)).'</pre><hr>';
109         }
110         $out = "<html><head><title>$title</title></head><body>" . $out;
111         $out .= '<pre>'. PublicInbox::WwwStream::code_footer($env) .
112                 '</pre></body></html>';
113
114         my $h = [ 'Content-Type', 'text/html; charset=UTF-8' ];
115         [ $code, $h, [ $out ] ];
116 }
117
118 my $json;
119 sub _json () {
120         for my $mod (qw(JSON::MaybeXS JSON JSON::PP)) {
121                 eval "require $mod" or next;
122                 # ->ascii encodes non-ASCII to "\uXXXX"
123                 return $mod->new->ascii(1);
124         }
125         die;
126 }
127
128 sub fingerprint ($) {
129         my ($git) = @_;
130         # TODO: convert to qspawn for fairness when there's
131         # thousands of repos
132         my ($fh, $pid) = $git->popen('show-ref') or
133                 die "popen($git->{git_dir} show-ref) failed: $!";
134
135         my $dig = Digest::SHA->new(1);
136         while (read($fh, my $buf, 65536)) {
137                 $dig->add($buf);
138         }
139         close $fh;
140         waitpid($pid, 0);
141         return if $?; # empty, uninitialized git repo
142         $dig->hexdigest;
143 }
144
145 sub manifest_add ($$;$$) {
146         my ($manifest, $ibx, $epoch, $default_desc) = @_;
147         my $url_path = "/$ibx->{name}";
148         my $git_dir = $ibx->{inboxdir};
149         if (defined $epoch) {
150                 $git_dir .= "/git/$epoch.git";
151                 $url_path .= "/git/$epoch.git";
152         }
153         return unless -d $git_dir;
154         my $git = PublicInbox::Git->new($git_dir);
155         my $fingerprint = fingerprint($git) or return; # no empty repos
156
157         chomp(my $owner = $git->qx('config', 'gitweb.owner'));
158         chomp(my $desc = try_cat("$git_dir/description"));
159         $owner = undef if $owner eq '';
160         $desc = 'Unnamed repository' if $desc eq '';
161
162         # templates/hooks--update.sample and git-multimail in git.git
163         # only match "Unnamed repository", not the full contents of
164         # templates/this--description in git.git
165         if ($desc =~ /\AUnnamed repository/) {
166                 $desc = "$default_desc [epoch $epoch]" if defined($epoch);
167         }
168
169         my $reference;
170         chomp(my $alt = try_cat("$git_dir/objects/info/alternates"));
171         if ($alt) {
172                 # n.b.: GitPython doesn't seem to handle comments or C-quoted
173                 # strings like native git does; and we don't for now, either.
174                 my @alt = split(/\n+/, $alt);
175
176                 # grokmirror only supports 1 alternate for "reference",
177                 if (scalar(@alt) == 1) {
178                         my $objdir = "$git_dir/objects";
179                         $reference = File::Spec->rel2abs($alt[0], $objdir);
180                         $reference =~ s!/[^/]+/?\z!!; # basename
181                 }
182         }
183         $manifest->{-abs2urlpath}->{$git_dir} = $url_path;
184         my $modified = $git->modified;
185         if ($modified > $manifest->{-mtime}) {
186                 $manifest->{-mtime} = $modified;
187         }
188         $manifest->{$url_path} = {
189                 owner => $owner,
190                 reference => $reference,
191                 description => $desc,
192                 modified => $modified,
193                 fingerprint => $fingerprint,
194         };
195 }
196
197 # manifest.js.gz
198 sub js ($$) {
199         my ($env, $list) = @_;
200         eval { require IO::Compress::Gzip } or return [ 404, [], [] ];
201
202         my $manifest = { -abs2urlpath => {}, -mtime => 0 };
203         for my $ibx (@$list) {
204                 if (defined(my $max = $ibx->max_git_epoch)) {
205                         my $desc = $ibx->description;
206                         for my $epoch (0..$max) {
207                                 manifest_add($manifest, $ibx, $epoch, $desc);
208                         }
209                 } else {
210                         manifest_add($manifest, $ibx);
211                 }
212         }
213         my $abs2urlpath = delete $manifest->{-abs2urlpath};
214         my $mtime = delete $manifest->{-mtime};
215         while (my ($url_path, $repo) = each %$manifest) {
216                 defined(my $abs = $repo->{reference}) or next;
217                 $repo->{reference} = $abs2urlpath->{$abs};
218         }
219         my $out;
220         IO::Compress::Gzip::gzip(\(($json ||= _json())->encode($manifest)) =>
221                                  \$out);
222         $manifest = undef;
223         [ 200, [ qw(Content-Type application/gzip),
224                  'Last-Modified', time2str($mtime),
225                  'Content-Length', bytes::length($out) ], [ $out ] ];
226 }
227
228 # not really a stand-alone PSGI app, but maybe it could be...
229 sub call {
230         my ($self, $env) = @_;
231
232         if ($env->{PATH_INFO} eq '/manifest.js.gz') {
233                 # grokmirror uses relative paths, so it's domain-dependent
234                 my $list = $self->{manifest_cb}->($self, $env, 'manifest');
235                 js($env, $list);
236         } else { # /
237                 my $list = $self->{www_cb}->($self, $env, 'www');
238                 html($env, $list);
239         }
240 }
241
242 1;