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