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