]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WWW.pm
www_stream: add response wrapper sub
[public-inbox.git] / lib / PublicInbox / WWW.pm
1 # Copyright (C) 2014-2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 #
4 # Main web interface for mailing list archives
5 #
6 # We focus on the lowest common denominators here:
7 # - targeted at text-only console browsers (w3m, links, etc..)
8 # - Only basic HTML, CSS only for line-wrapping <pre> text content for GUIs
9 # - No JavaScript, graphics or icons allowed.
10 # - Must not rely on static content
11 # - UTF-8 is only for user-content, 7-bit US-ASCII for us
12 package PublicInbox::WWW;
13 use 5.008;
14 use strict;
15 use warnings;
16 use Plack::Request;
17 use PublicInbox::Config;
18 use PublicInbox::Hval;
19 use URI::Escape qw(uri_escape_utf8 uri_unescape);
20 use constant SSOMA_URL => '//ssoma.public-inbox.org/';
21 use constant PI_URL => '//public-inbox.org/';
22 require PublicInbox::Git;
23 use PublicInbox::GitHTTPBackend;
24 our $INBOX_RE = qr!\A/([\w\.\-]+)!;
25 our $MID_RE = qr!([^/]+)!;
26 our $END_RE = qr!(T/|t/|t\.mbox(?:\.gz)?|t\.atom|raw|)!;
27 our $ATTACH_RE = qr!(\d[\.\d]*)-([[:alnum:]][\w\.-]+[[:alnum:]])!i;
28
29 sub new {
30         my ($class, $pi_config) = @_;
31         $pi_config ||= PublicInbox::Config->new;
32         bless { pi_config => $pi_config }, $class;
33 }
34
35 # backwards compatibility, do not use
36 sub run {
37         my ($req, $method) = @_;
38         PublicInbox::WWW->new->call($req->env);
39 }
40
41 sub call {
42         my ($self, $env) = @_;
43         my $cgi = Plack::Request->new($env);
44         my $ctx = { cgi => $cgi, env => $env, www => $self,
45                 pi_config => $self->{pi_config} };
46
47         # we don't care about multi-value
48         my %qp = map {
49                 my ($k, $v) = split('=', $_, 2);
50                 $v = '' unless defined $v;
51                 $v =~ tr/+/ /;
52                 ($k, $v)
53         } split(/[&;]/, uri_unescape($env->{QUERY_STRING}));
54         $ctx->{qp} = \%qp;
55
56         my $path_info = $env->{PATH_INFO};
57         my $method = $env->{REQUEST_METHOD};
58
59         if ($method eq 'POST' &&
60                  $path_info =~ m!$INBOX_RE/(git-upload-pack)\z!) {
61                 my $path = $2;
62                 return (invalid_inbox($self, $ctx, $1) ||
63                         serve_git($env, $ctx->{git}, $path));
64         }
65         elsif ($method !~ /\AGET|HEAD\z/) {
66                 return r(405, 'Method Not Allowed');
67         }
68
69         # top-level indices and feeds
70         if ($path_info eq '/') {
71                 r404();
72         } elsif ($path_info =~ m!$INBOX_RE\z!o) {
73                 invalid_inbox($self, $ctx, $1) || r301($ctx, $1);
74         } elsif ($path_info =~ m!$INBOX_RE(?:/|/index\.html)?\z!o) {
75                 invalid_inbox($self, $ctx, $1) || get_index($ctx);
76         } elsif ($path_info =~ m!$INBOX_RE/(?:atom\.xml|new\.atom)\z!o) {
77                 invalid_inbox($self, $ctx, $1) || get_atom($ctx);
78         } elsif ($path_info =~ m!$INBOX_RE/new\.html\z!o) {
79                 invalid_inbox($self, $ctx, $1) || get_new($ctx);
80         } elsif ($path_info =~ m!$INBOX_RE/
81                                 ($PublicInbox::GitHTTPBackend::ANY)\z!ox) {
82                 my $path = $2;
83                 invalid_inbox($self, $ctx, $1) ||
84                         serve_git($env, $ctx->{git}, $path);
85         } elsif ($path_info =~ m!$INBOX_RE/([\w-]+).mbox\.gz\z!o) {
86                 serve_mbox_range($self, $ctx, $1, $2);
87         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/$END_RE\z!o) {
88                 msg_page($self, $ctx, $1, $2, $3);
89
90         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/$ATTACH_RE\z!o) {
91                 my ($idx, $fn) = ($3, $4);
92                 invalid_inbox_mid($self, $ctx, $1, $2) ||
93                         get_attach($ctx, $idx, $fn);
94         # in case people leave off the trailing slash:
95         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/(T|t)\z!o) {
96                 my ($inbox, $mid, $suffix) = ($1, $2, $3);
97                 $suffix .= $suffix =~ /\A[tT]\z/ ? '/#u' : '/';
98                 r301($ctx, $inbox, $mid, $suffix);
99
100         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/R/?\z!o) {
101                 my ($inbox, $mid) = ($1, $2);
102                 r301($ctx, $inbox, $mid, '#R');
103
104         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/f/?\z!o) {
105                 r301($ctx, $1, $2);
106
107         # convenience redirects order matters
108         } elsif ($path_info =~ m!$INBOX_RE/([^/]{2,})\z!o) {
109                 r301($ctx, $1, $2);
110
111         } else {
112                 legacy_redirects($self, $ctx, $path_info);
113         }
114 }
115
116 # for CoW-friendliness, MOOOOO!
117 sub preload {
118         require PublicInbox::Feed;
119         require PublicInbox::View;
120         require PublicInbox::Thread;
121         require Email::MIME;
122         require Digest::SHA;
123         require POSIX;
124
125         foreach (qw(PublicInbox::Search PublicInbox::SearchView
126                         PublicInbox::Mbox IO::Compress::Gzip
127                         PublicInbox::NewsWWW)) {
128                 eval "require $_;";
129         }
130 }
131
132 # private functions below
133
134 sub r404 {
135         my ($ctx) = @_;
136         if ($ctx && $ctx->{mid}) {
137                 require PublicInbox::ExtMsg;
138                 searcher($ctx);
139                 return PublicInbox::ExtMsg::ext_msg($ctx);
140         }
141         r(404, 'Not Found');
142 }
143
144 # simple response for errors
145 sub r { [ $_[0], ['Content-Type' => 'text/plain'], [ join(' ', @_, "\n") ] ] }
146
147 # returns undef if valid, array ref response if invalid
148 sub invalid_inbox {
149         my ($self, $ctx, $inbox) = @_;
150         my $obj = $ctx->{pi_config}->lookup_name($inbox);
151         if (defined $obj) {
152                 $ctx->{git_dir} = $obj->{mainrepo};
153                 $ctx->{git} = $obj->git;
154                 # for PublicInbox::HTTP::weaken_task:
155                 $ctx->{cgi}->{env}->{'pi-httpd.inbox'} = $obj;
156                 $ctx->{-inbox} = $obj;
157                 $ctx->{inbox} = $inbox;
158                 return;
159         }
160
161         # sometimes linkifiers (not ours!) screw up automatic link
162         # generation and link things intended for nntp:// to https?://,
163         # so try to infer links and redirect them to the appropriate
164         # list URL.
165         $self->news_www->call($ctx->{cgi}->{env});
166 }
167
168 # returns undef if valid, array ref response if invalid
169 sub invalid_inbox_mid {
170         my ($self, $ctx, $inbox, $mid) = @_;
171         my $ret = invalid_inbox($self, $ctx, $inbox);
172         return $ret if $ret;
173
174         $ctx->{mid} = $mid = uri_unescape($mid);
175         if ($mid =~ /\A[a-f0-9]{40}\z/) {
176                 # this is horiffically wasteful for legacy URLs:
177                 if ($mid = mid2blob($ctx)) {
178                         require Email::Simple;
179                         use PublicInbox::MID qw/mid_clean/;
180                         my $s = Email::Simple->new($mid);
181                         $ctx->{mid} = mid_clean($s->header('Message-ID'));
182                 }
183         }
184         undef;
185 }
186
187 # /$INBOX/new.atom                     -> Atom feed, includes replies
188 sub get_atom {
189         my ($ctx) = @_;
190         require PublicInbox::Feed;
191         PublicInbox::Feed::generate($ctx);
192 }
193
194 # /$INBOX/new.html                      -> HTML only
195 sub get_new {
196         my ($ctx) = @_;
197         require PublicInbox::Feed;
198         PublicInbox::Feed::new_html($ctx);
199 }
200
201 # /$INBOX/?r=$GIT_COMMIT                 -> HTML only
202 sub get_index {
203         my ($ctx) = @_;
204         require PublicInbox::Feed;
205         my $srch = searcher($ctx);
206         footer($ctx);
207         if ($ctx->{env}->{QUERY_STRING} =~ /(?:\A|[&;])q=/) {
208                 require PublicInbox::SearchView;
209                 PublicInbox::SearchView::sres_top_html($ctx);
210         } else {
211                 PublicInbox::Feed::generate_html_index($ctx);
212         }
213 }
214
215 # just returns a string ref for the blob in the current ctx
216 sub mid2blob {
217         my ($ctx) = @_;
218         $ctx->{-inbox}->msg_by_mid($ctx->{mid});
219 }
220
221 # /$INBOX/$MESSAGE_ID/raw                    -> raw mbox
222 sub get_mid_txt {
223         my ($ctx) = @_;
224         my $x = mid2blob($ctx) or return r404($ctx);
225         require PublicInbox::Mbox;
226         PublicInbox::Mbox::emit1($ctx, $x);
227 }
228
229 # /$INBOX/$MESSAGE_ID/                   -> HTML content (short quotes)
230 sub get_mid_html {
231         my ($ctx) = @_;
232         my $x = mid2blob($ctx) or return r404($ctx);
233
234         require PublicInbox::View;
235         my $foot = footer($ctx);
236         require Email::MIME;
237         my $mime = Email::MIME->new($x);
238         searcher($ctx);
239         PublicInbox::View::msg_html($ctx, $mime, $foot);
240 }
241
242 # /$INBOX/$MESSAGE_ID/t/
243 sub get_thread {
244         my ($ctx, $flat) = @_;
245         searcher($ctx) or return need_search($ctx);
246         $ctx->{flat} = $flat;
247         require PublicInbox::View;
248         PublicInbox::View::thread_html($ctx);
249 }
250
251 sub ctx_get {
252         my ($ctx, $key) = @_;
253         my $val = $ctx->{$key};
254         (defined $val && $val ne '') or die "BUG: bad ctx, $key unusable";
255         $val;
256 }
257
258 sub footer {
259         my ($ctx) = @_;
260         return '' unless $ctx;
261         my $obj = $ctx->{-inbox} or return '';
262
263         # auto-generate a footer
264         chomp(my $desc = $obj->description);
265         $desc = PublicInbox::Hval::ascii_html($desc);
266
267         my $urls;
268         my @urls = @{$obj->cloneurl};
269         my %seen = map { $_ => 1 } @urls;
270         my $cgi = $ctx->{cgi};
271         my $http = $cgi->base->as_string . $obj->{name};
272         $seen{$http} or unshift @urls, $http;
273         my $ssoma_url = PublicInbox::Hval::prurl($ctx->{env}, SSOMA_URL);
274         if (scalar(@urls) == 1) {
275                 $urls = "URL for <a\nhref=\"" . $ssoma_url .
276                         qq(">ssoma</a> or <b>git clone --mirror $urls[0]</b>);
277         } else {
278                 $urls = "URLs for <a\nhref=\"" . $ssoma_url .
279                         qq(">ssoma</a> or <b>git clone --mirror</b>\n) .
280                         join("\n", map { "\tgit clone --mirror $_" } @urls);
281         }
282
283         my $addr = $obj->{-primary_address};
284         $ctx->{footer} = join("\n",
285                 '- ' . $desc,
286                 "A <a\nhref=\"" .
287                         PublicInbox::Hval::prurl($ctx->{cgi}->{env}, PI_URL) .
288                         '">public-inbox</a>, ' .
289                         'anybody may post in plain-text (not HTML):',
290                 $addr,
291                 $urls
292         );
293 }
294
295 # search support is optional, returns undef if Xapian is not installed
296 # or not configured for the given GIT_DIR
297 sub searcher {
298         my ($ctx) = @_;
299         eval {
300                 require PublicInbox::Search;
301                 $ctx->{srch} = $ctx->{-inbox}->search;
302         };
303 }
304
305 sub need_search {
306         my ($ctx) = @_;
307         my $msg = <<EOF;
308 <html><head><title>Search not available for this
309 public-inbox</title><body><pre>Search is not available for this public-inbox
310 <a href="../">Return to index</a></pre></body></html>
311 EOF
312         [ 501, [ 'Content-Type' => 'text/html; charset=UTF-8' ], [ $msg ] ];
313 }
314
315 # /$INBOX/$MESSAGE_ID/t.mbox           -> thread as mbox
316 # /$INBOX/$MESSAGE_ID/t.mbox.gz        -> thread as gzipped mbox
317 # note: I'm not a big fan of other compression formats since they're
318 # significantly more expensive on CPU than gzip and less-widely available,
319 # especially on older systems.  Stick to zlib since that's what git uses.
320 sub get_thread_mbox {
321         my ($ctx, $sfx) = @_;
322         my $srch = searcher($ctx) or return need_search($ctx);
323         require PublicInbox::Mbox;
324         PublicInbox::Mbox::thread_mbox($ctx, $srch, $sfx);
325 }
326
327
328 # /$INBOX/$MESSAGE_ID/t.atom              -> thread as Atom feed
329 sub get_thread_atom {
330         my ($ctx) = @_;
331         searcher($ctx) or return need_search($ctx);
332         $ctx->{self_url} = $ctx->{cgi}->uri->as_string;
333         require PublicInbox::Feed;
334         PublicInbox::Feed::generate_thread_atom($ctx);
335 }
336
337 sub legacy_redirects {
338         my ($self, $ctx, $path_info) = @_;
339
340         # single-message pages
341         if ($path_info =~ m!$INBOX_RE/m/(\S+)/\z!o) {
342                 r301($ctx, $1, $2);
343         } elsif ($path_info =~ m!$INBOX_RE/m/(\S+)/raw\z!o) {
344                 r301($ctx, $1, $2, 'raw');
345
346         } elsif ($path_info =~ m!$INBOX_RE/f/(\S+)/\z!o) {
347                 r301($ctx, $1, $2);
348
349         # thread display
350         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)/\z!o) {
351                 r301($ctx, $1, $2, 't/#u');
352
353         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)/mbox(\.gz)?\z!o) {
354                 r301($ctx, $1, $2, "t.mbox$3");
355
356         # even older legacy redirects
357         } elsif ($path_info =~ m!$INBOX_RE/m/(\S+)\.html\z!o) {
358                 r301($ctx, $1, $2);
359
360         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)\.html\z!o) {
361                 r301($ctx, $1, $2, 't/#u');
362
363         } elsif ($path_info =~ m!$INBOX_RE/f/(\S+)\.html\z!o) {
364                 r301($ctx, $1, $2);
365
366         } elsif ($path_info =~ m!$INBOX_RE/(?:m|f)/(\S+)\.txt\z!o) {
367                 r301($ctx, $1, $2, 'raw');
368
369         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)(\.mbox(?:\.gz)?)\z!o) {
370                 r301($ctx, $1, $2, "t$3");
371
372         # legacy convenience redirects, order still matters
373         } elsif ($path_info =~ m!$INBOX_RE/m/(\S+)\z!o) {
374                 r301($ctx, $1, $2);
375         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)\z!o) {
376                 r301($ctx, $1, $2, 't/#u');
377         } elsif ($path_info =~ m!$INBOX_RE/f/(\S+)\z!o) {
378                 r301($ctx, $1, $2);
379
380         # some Message-IDs have slashes in them and the HTTP server
381         # may try to be clever and unescape them :<
382         } elsif ($path_info =~ m!$INBOX_RE/(\S+/\S+)/$END_RE\z!o) {
383                 msg_page($self, $ctx, $1, $2, $3);
384
385         # in case people leave off the trailing slash:
386         } elsif ($path_info =~ m!$INBOX_RE/(\S+/\S+)/(T|t)\z!o) {
387                 r301($ctx, $1, $2, $3 eq 't' ? 't/#u' : $3);
388         } elsif ($path_info =~ m!$INBOX_RE/(\S+/\S+)/f\z!o) {
389                 r301($ctx, $1, $2);
390         } else {
391                 $self->news_www->call($ctx->{cgi}->{env});
392         }
393 }
394
395 sub r301 {
396         my ($ctx, $inbox, $mid, $suffix) = @_;
397         my $cgi = $ctx->{cgi};
398         my $obj = $ctx->{-inbox};
399         unless ($obj) {
400                 my $r404 = invalid_inbox($ctx->{www}, $ctx, $inbox);
401                 return $r404 if $r404;
402                 $obj = $ctx->{-inbox};
403         }
404         my $url = $obj->base_url($cgi);
405         my $qs = $ctx->{env}->{QUERY_STRING};
406         $url .= (uri_escape_utf8($mid) . '/') if (defined $mid);
407         $url .= $suffix if (defined $suffix);
408         $url .= "?$qs" if $qs ne '';
409
410         [ 301,
411           [ Location => $url, 'Content-Type' => 'text/plain' ],
412           [ "Redirecting to $url\n" ] ]
413 }
414
415 sub msg_page {
416         my ($self, $ctx, $inbox, $mid, $e) = @_;
417         my $ret;
418         $ret = invalid_inbox_mid($self, $ctx, $inbox, $mid) and return $ret;
419         '' eq $e and return get_mid_html($ctx);
420         'T/' eq $e and return get_thread($ctx, 1);
421         't/' eq $e and return get_thread($ctx);
422         't.atom' eq $e and return get_thread_atom($ctx);
423         't.mbox' eq $e and return get_thread_mbox($ctx);
424         't.mbox.gz' eq $e and return get_thread_mbox($ctx, '.gz');
425         'raw' eq $e and return get_mid_txt($ctx);
426
427         # legacy, but no redirect for compatibility:
428         'f/' eq $e and return get_mid_html($ctx);
429         r404($ctx);
430 }
431
432 sub serve_git {
433         my ($env, $git, $path) = @_;
434         PublicInbox::GitHTTPBackend::serve($env, $git, $path);
435 }
436
437 sub serve_mbox_range {
438         my ($self, $ctx, $inbox, $range) = @_;
439         invalid_inbox($self, $ctx, $inbox) || eval {
440                 require PublicInbox::Mbox;
441                 searcher($ctx);
442                 PublicInbox::Mbox::emit_range($ctx, $range);
443         }
444 }
445
446 sub news_www {
447         my ($self) = @_;
448         my $nw = $self->{news_www};
449         return $nw if $nw;
450         require PublicInbox::NewsWWW;
451         $self->{news_www} = PublicInbox::NewsWWW->new($self->{pi_config});
452 }
453
454 sub get_attach {
455         my ($ctx, $idx, $fn) = @_;
456         require PublicInbox::WwwAttach;
457         PublicInbox::WwwAttach::get_attach($ctx, $idx, $fn);
458 }
459
460 1;