]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WWW.pm
52630ae3eccc4d48c734e9cceca0b587b4f4f7a7
[public-inbox.git] / lib / PublicInbox / WWW.pm
1 # Copyright (C) 2014-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <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 #   and diff/syntax-highlighting (optional)
10 # - No JavaScript, graphics or icons allowed.
11 # - Must not rely on static content
12 # - UTF-8 is only for user-content, 7-bit US-ASCII for us
13 package PublicInbox::WWW;
14 use 5.010_001;
15 use strict;
16 use warnings;
17 use bytes (); # only for bytes::length
18 use PublicInbox::Config;
19 use PublicInbox::Hval;
20 use URI::Escape qw(uri_unescape);
21 use PublicInbox::MID qw(mid_escape);
22 use PublicInbox::GitHTTPBackend;
23 use PublicInbox::UserContent;
24 use PublicInbox::WwwStatic qw(r path_info_raw);
25 use PublicInbox::Eml;
26
27 # TODO: consider a routing tree now that we have more endpoints:
28 our $INBOX_RE = qr!\A/([\w\-][\w\.\-]*)!;
29 our $MID_RE = qr!([^/]+)!;
30 our $END_RE = qr!(T/|t/|t\.mbox(?:\.gz)?|t\.atom|raw|)!;
31 our $ATTACH_RE = qr!([0-9][0-9\.]*)-($PublicInbox::Hval::FN)!;
32 our $OID_RE = qr![a-f0-9]{7,}!;
33
34 sub new {
35         my ($class, $pi_cfg) = @_;
36         bless { pi_cfg => $pi_cfg // PublicInbox::Config->new }, $class;
37 }
38
39 # backwards compatibility, do not use
40 sub run {
41         my ($req, $method) = @_;
42         PublicInbox::WWW->new->call($req->env);
43 }
44
45 sub call {
46         my ($self, $env) = @_;
47         my $ctx = { env => $env, www => $self };
48
49         # we don't care about multi-value
50         %{$ctx->{qp}} = map {
51                 utf8::decode($_);
52                 tr/+/ /;
53                 my ($k, $v) = split('=', $_, 2);
54                 $v = uri_unescape($v // '');
55                 # none of the keys we care about will need escaping
56                 $k => $v;
57         } split(/[&;]+/, $env->{QUERY_STRING});
58
59         my $path_info = path_info_raw($env);
60         my $method = $env->{REQUEST_METHOD};
61
62         if ($method eq 'POST') {
63                 if ($path_info =~ m!$INBOX_RE/(?:(?:git/)?([0-9]+)(?:\.git)?/)?
64                                         (git-upload-pack)\z!x) {
65                         my ($epoch, $path) = ($2, $3);
66                         return invalid_inbox($ctx, $1) ||
67                                 serve_git($ctx, $epoch, $path);
68                 } elsif ($path_info =~ m!$INBOX_RE/(\w+)\.sql\.gz\z!o) {
69                         return get_altid_dump($ctx, $1, $2);
70                 } elsif ($path_info =~ m!$INBOX_RE/!o) {
71                         return invalid_inbox($ctx, $1) || mbox_results($ctx);
72                 }
73         }
74         elsif ($method !~ /\A(?:GET|HEAD)\z/) {
75                 return r(405);
76         }
77
78         # top-level indices and feeds
79         if ($path_info eq '/') {
80                 require PublicInbox::WwwListing;
81                 PublicInbox::WwwListing->response($ctx);
82         } elsif ($path_info eq '/manifest.js.gz') {
83                 require PublicInbox::ManifestJsGz;
84                 PublicInbox::ManifestJsGz->response($ctx);
85         } elsif ($path_info =~ m!$INBOX_RE\z!o) {
86                 invalid_inbox($ctx, $1) || r301($ctx, $1);
87         } elsif ($path_info =~ m!$INBOX_RE(?:/|/index\.html)?\z!o) {
88                 invalid_inbox($ctx, $1) || get_index($ctx);
89         } elsif ($path_info =~ m!$INBOX_RE/(?:atom\.xml|new\.atom)\z!o) {
90                 invalid_inbox($ctx, $1) || get_atom($ctx);
91         } elsif ($path_info =~ m!$INBOX_RE/new\.html\z!o) {
92                 invalid_inbox($ctx, $1) || get_new($ctx);
93         } elsif ($path_info =~ m!$INBOX_RE/description\z!o) {
94                 get_description($ctx, $1);
95         } elsif ($path_info =~ m!$INBOX_RE/(?:(?:git/)?([0-9]+)(?:\.git)?/)?
96                                 ($PublicInbox::GitHTTPBackend::ANY)\z!ox) {
97                 my ($epoch, $path) = ($2, $3);
98                 invalid_inbox($ctx, $1) || serve_git($ctx, $epoch, $path);
99         } elsif ($path_info =~ m!$INBOX_RE/([a-zA-Z0-9_\-]+).mbox\.gz\z!o) {
100                 serve_mbox_range($ctx, $1, $2);
101         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/$END_RE\z!o) {
102                 msg_page($ctx, $1, $2, $3);
103
104         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/$ATTACH_RE\z!o) {
105                 my ($idx, $fn) = ($3, $4);
106                 invalid_inbox_mid($ctx, $1, $2) || get_attach($ctx, $idx, $fn);
107         # in case people leave off the trailing slash:
108         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/(T|t)\z!o) {
109                 my ($inbox, $mid_ue, $suffix) = ($1, $2, $3);
110                 $suffix .= $suffix =~ /\A[tT]\z/ ? '/#u' : '/';
111                 r301($ctx, $inbox, $mid_ue, $suffix);
112
113         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/R/?\z!o) {
114                 my ($inbox, $mid_ue) = ($1, $2);
115                 r301($ctx, $inbox, $mid_ue, '#R');
116
117         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/f/?\z!o) {
118                 r301($ctx, $1, $2);
119         } elsif ($path_info =~ m!$INBOX_RE/_/text(?:/(.*))?\z!o) {
120                 get_text($ctx, $1, $2);
121         } elsif ($path_info =~ m!$INBOX_RE/([a-zA-Z0-9_\-\.]+)\.css\z!o) {
122                 get_css($ctx, $1, $2);
123         } elsif ($path_info =~ m!$INBOX_RE/manifest\.js\.gz\z!o) {
124                 get_inbox_manifest($ctx, $1, $2);
125         } elsif ($path_info =~ m!$INBOX_RE/($OID_RE)/s/\z!o) {
126                 get_vcs_object($ctx, $1, $2);
127         } elsif ($path_info =~ m!$INBOX_RE/($OID_RE)/s/
128                                 ($PublicInbox::Hval::FN)\z!ox) {
129                 get_vcs_object($ctx, $1, $2, $3);
130         } elsif ($path_info =~ m!$INBOX_RE/($OID_RE)/s\z!o) {
131                 r301($ctx, $1, $2, 's/');
132         } elsif ($path_info =~ m!$INBOX_RE/(\w+)\.sql\.gz\z!o) {
133                 get_altid_dump($ctx, $1, $2);
134         # convenience redirects order matters
135         } elsif ($path_info =~ m!$INBOX_RE/([^/]{2,})\z!o) {
136                 r301($ctx, $1, $2);
137
138         } else {
139                 legacy_redirects($ctx, $path_info);
140         }
141 }
142
143 # for CoW-friendliness, MOOOOO!  Even for single-process setups,
144 # we want to get all immortal allocations done early to avoid heap
145 # fragmentation since common allocators favor a large contiguous heap.
146 sub preload {
147         my ($self) = @_;
148
149         # populate caches used by Encode internally, since emails
150         # may show up with any encoding.
151         require Encode;
152         Encode::find_encoding($_) for Encode->encodings(':all');
153
154         require PublicInbox::ExtMsg;
155         require PublicInbox::Feed;
156         require PublicInbox::View;
157         require PublicInbox::SearchThread;
158         require PublicInbox::Eml;
159         require PublicInbox::Mbox;
160         require PublicInbox::ViewVCS;
161         require PublicInbox::WwwText;
162         require PublicInbox::WwwAttach;
163         eval {
164                 require PublicInbox::Search;
165                 PublicInbox::Search::load_xapian();
166         };
167         for (qw(SearchView MboxGz WwwAltId)) {
168                 eval "require PublicInbox::$_;";
169         }
170         if (ref($self)) {
171                 my $pi_cfg = $self->{pi_cfg};
172                 if (defined($pi_cfg->{'publicinbox.cgitrc'})) {
173                         $pi_cfg->limiter('-cgit');
174                 }
175                 $self->cgit;
176                 $self->stylesheets_prepare($_) for ('', '../', '../../');
177                 $self->news_www;
178                 $pi_cfg->each_inbox(\&preload_inbox);
179         }
180 }
181
182 sub preload_inbox {
183         my $ibx = shift;
184         $ibx->altid_map;
185         $ibx->cloneurl;
186         $ibx->description;
187         $ibx->base_url;
188 }
189
190 # private functions below
191
192 sub r404 {
193         my ($ctx) = @_;
194         if ($ctx && $ctx->{mid}) {
195                 require PublicInbox::ExtMsg;
196                 return PublicInbox::ExtMsg::ext_msg($ctx);
197         }
198         r(404);
199 }
200
201 sub news_cgit_fallback ($) {
202         my ($ctx) = @_;
203         my $www = $ctx->{www};
204         my $env = $ctx->{env};
205         my $res = $www->news_www->call($env);
206         $res->[0] == 404 ? $www->cgit->call($env) : $res;
207 }
208
209 # returns undef if valid, array ref response if invalid
210 sub invalid_inbox ($$) {
211         my ($ctx, $inbox) = @_;
212         my $ibx = $ctx->{www}->{pi_cfg}->lookup_name($inbox) //
213                         $ctx->{www}->{pi_cfg}->lookup_ei($inbox);
214         if (defined $ibx) {
215                 $ctx->{ibx} = $ibx;
216                 return;
217         }
218
219         # sometimes linkifiers (not ours!) screw up automatic link
220         # generation and link things intended for nntp:// to https?://,
221         # so try to infer links and redirect them to the appropriate
222         # list URL.
223         news_cgit_fallback($ctx);
224 }
225
226 # returns undef if valid, array ref response if invalid
227 sub invalid_inbox_mid {
228         my ($ctx, $inbox, $mid_ue) = @_;
229         my $ret = invalid_inbox($ctx, $inbox);
230         return $ret if $ret;
231
232         my $mid = $ctx->{mid} = uri_unescape($mid_ue);
233         my $ibx = $ctx->{ibx};
234         if ($mid =~ m!\A([a-f0-9]{2})([a-f0-9]{38})\z!) {
235                 my ($x2, $x38) = ($1, $2);
236                 # this is horrifically wasteful for legacy URLs:
237                 my $str = $ctx->{ibx}->msg_by_path("$x2/$x38") or return;
238                 my $s = PublicInbox::Eml->new($str);
239                 $mid = PublicInbox::MID::mid_clean($s->header_raw('Message-ID'));
240                 return r301($ctx, $inbox, mid_escape($mid));
241         }
242         undef;
243 }
244
245 # /$INBOX/new.atom                     -> Atom feed, includes replies
246 sub get_atom {
247         my ($ctx) = @_;
248         require PublicInbox::Feed;
249         PublicInbox::Feed::generate($ctx);
250 }
251
252 # /$INBOX/new.html                      -> HTML only
253 sub get_new {
254         my ($ctx) = @_;
255         require PublicInbox::Feed;
256         PublicInbox::Feed::new_html($ctx);
257 }
258
259 # /$INBOX/?r=$GIT_COMMIT                 -> HTML only
260 sub get_index {
261         my ($ctx) = @_;
262         require PublicInbox::Feed;
263         if ($ctx->{env}->{QUERY_STRING} =~ /(?:\A|[&;])q=/) {
264                 require PublicInbox::SearchView;
265                 PublicInbox::SearchView::sres_top_html($ctx);
266         } else {
267                 PublicInbox::Feed::generate_html_index($ctx);
268         }
269 }
270
271 # /$INBOX/$MESSAGE_ID/raw                    -> raw mbox
272 sub get_mid_txt {
273         my ($ctx) = @_;
274         require PublicInbox::Mbox;
275         PublicInbox::Mbox::emit_raw($ctx) || r404($ctx);
276 }
277
278 # /$INBOX/$MESSAGE_ID/                   -> HTML content (short quotes)
279 sub get_mid_html {
280         my ($ctx) = @_;
281         require PublicInbox::View;
282         PublicInbox::View::msg_page($ctx) || r404($ctx);
283 }
284
285 # /$INBOX/$MESSAGE_ID/t/
286 sub get_thread {
287         my ($ctx, $flat) = @_;
288         $ctx->{ibx}->over or return need($ctx, 'Overview');
289         $ctx->{flat} = $flat;
290         require PublicInbox::View;
291         PublicInbox::View::thread_html($ctx);
292 }
293
294 # /$INBOX/_/text/$KEY/
295 # /$INBOX/_/text/$KEY/raw
296 # KEY may contain slashes
297 sub get_text {
298         my ($ctx, $inbox, $key) = @_;
299         my $r404 = invalid_inbox($ctx, $inbox);
300         return $r404 if $r404;
301
302         require PublicInbox::WwwText;
303         PublicInbox::WwwText::get_text($ctx, $key);
304 }
305
306 # show git objects (blobs and commits)
307 # /$INBOX/$GIT_OBJECT_ID/s/
308 # /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
309 sub get_vcs_object ($$$;$) {
310         my ($ctx, $inbox, $oid, $filename) = @_;
311         my $r404 = invalid_inbox($ctx, $inbox);
312         return $r404 if $r404;
313         require PublicInbox::ViewVCS;
314         PublicInbox::ViewVCS::show($ctx, $oid, $filename);
315 }
316
317 sub get_altid_dump {
318         my ($ctx, $inbox, $altid_pfx) =@_;
319         my $r404 = invalid_inbox($ctx, $inbox);
320         return $r404 if $r404;
321         eval { require PublicInbox::WwwAltId } or return need($ctx, 'sqlite3');
322         PublicInbox::WwwAltId::sqldump($ctx, $altid_pfx);
323 }
324
325 sub need {
326         my ($ctx, $extra) = @_;
327         require PublicInbox::WwwStream;
328         PublicInbox::WwwStream::html_oneshot($ctx, 501, \<<EOF);
329 <pre>$extra is not available for this public-inbox
330 <a\nhref="../">Return to index</a></pre>
331 EOF
332 }
333
334 # /$INBOX/$MESSAGE_ID/t.mbox           -> thread as mbox
335 # /$INBOX/$MESSAGE_ID/t.mbox.gz        -> thread as gzipped mbox
336 # note: I'm not a big fan of other compression formats since they're
337 # significantly more expensive on CPU than gzip and less-widely available,
338 # especially on older systems.  Stick to zlib since that's what git uses.
339 sub get_thread_mbox {
340         my ($ctx, $sfx) = @_;
341         my $over = $ctx->{ibx}->over or return need($ctx, 'Overview');
342         require PublicInbox::Mbox;
343         PublicInbox::Mbox::thread_mbox($ctx, $over, $sfx);
344 }
345
346
347 # /$INBOX/$MESSAGE_ID/t.atom              -> thread as Atom feed
348 sub get_thread_atom {
349         my ($ctx) = @_;
350         $ctx->{ibx}->over or return need($ctx, 'Overview');
351         require PublicInbox::Feed;
352         PublicInbox::Feed::generate_thread_atom($ctx);
353 }
354
355 sub legacy_redirects {
356         my ($ctx, $path_info) = @_;
357
358         # single-message pages
359         if ($path_info =~ m!$INBOX_RE/m/(\S+)/\z!o) {
360                 r301($ctx, $1, $2);
361         } elsif ($path_info =~ m!$INBOX_RE/m/(\S+)/raw\z!o) {
362                 r301($ctx, $1, $2, 'raw');
363
364         } elsif ($path_info =~ m!$INBOX_RE/f/(\S+)/\z!o) {
365                 r301($ctx, $1, $2);
366
367         # thread display
368         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)/\z!o) {
369                 r301($ctx, $1, $2, 't/#u');
370
371         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)/mbox(\.gz)?\z!o) {
372                 r301($ctx, $1, $2, "t.mbox$3");
373
374         # even older legacy redirects
375         } elsif ($path_info =~ m!$INBOX_RE/m/(\S+)\.html\z!o) {
376                 r301($ctx, $1, $2);
377
378         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)\.html\z!o) {
379                 r301($ctx, $1, $2, 't/#u');
380
381         } elsif ($path_info =~ m!$INBOX_RE/f/(\S+)\.html\z!o) {
382                 r301($ctx, $1, $2);
383
384         } elsif ($path_info =~ m!$INBOX_RE/(?:m|f)/(\S+)\.txt\z!o) {
385                 r301($ctx, $1, $2, 'raw');
386
387         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)(\.mbox(?:\.gz)?)\z!o) {
388                 r301($ctx, $1, $2, "t$3");
389
390         # legacy convenience redirects, order still matters
391         } elsif ($path_info =~ m!$INBOX_RE/m/(\S+)\z!o) {
392                 r301($ctx, $1, $2);
393         } elsif ($path_info =~ m!$INBOX_RE/t/(\S+)\z!o) {
394                 r301($ctx, $1, $2, 't/#u');
395         } elsif ($path_info =~ m!$INBOX_RE/f/(\S+)\z!o) {
396                 r301($ctx, $1, $2);
397
398         # some Message-IDs have slashes in them and the HTTP server
399         # may try to be clever and unescape them :<
400         } elsif ($path_info =~ m!$INBOX_RE/(\S+/\S+)/$END_RE\z!o) {
401                 msg_page($ctx, $1, $2, $3);
402
403         # in case people leave off the trailing slash:
404         } elsif ($path_info =~ m!$INBOX_RE/(\S+/\S+)/(T|t)\z!o) {
405                 r301($ctx, $1, $2, $3 eq 't' ? 't/#u' : $3);
406         } elsif ($path_info =~ m!$INBOX_RE/(\S+/\S+)/f\z!o) {
407                 r301($ctx, $1, $2);
408         } else {
409                 news_cgit_fallback($ctx);
410         }
411 }
412
413 sub r301 {
414         my ($ctx, $inbox, $mid_ue, $suffix) = @_;
415         my $ibx = $ctx->{ibx};
416         unless ($ibx) {
417                 my $r404 = invalid_inbox($ctx, $inbox);
418                 return $r404 if $r404;
419                 $ibx = $ctx->{ibx};
420         }
421         my $url = $ibx->base_url($ctx->{env});
422         my $qs = $ctx->{env}->{QUERY_STRING};
423         if (defined $mid_ue) {
424                 # common, and much nicer as '@' than '%40':
425                 $mid_ue =~ s/%40/@/g;
426                 $url .= $mid_ue . '/';
427         }
428         $url .= $suffix if (defined $suffix);
429         $url .= "?$qs" if $qs ne '';
430
431         [ 301,
432           [ Location => $url, 'Content-Type' => 'text/plain' ],
433           [ "Redirecting to $url\n" ] ]
434 }
435
436 sub msg_page {
437         my ($ctx, $inbox, $mid_ue, $e) = @_;
438         my $ret;
439         $ret = invalid_inbox_mid($ctx, $inbox, $mid_ue) and return $ret;
440         '' eq $e and return get_mid_html($ctx);
441         'T/' eq $e and return get_thread($ctx, 1);
442         't/' eq $e and return get_thread($ctx);
443         't.atom' eq $e and return get_thread_atom($ctx);
444         't.mbox' eq $e and return get_thread_mbox($ctx);
445         't.mbox.gz' eq $e and return get_thread_mbox($ctx, '.gz');
446         'raw' eq $e and return get_mid_txt($ctx);
447
448         # legacy, but no redirect for compatibility:
449         'f/' eq $e and return get_mid_html($ctx);
450         r404($ctx);
451 }
452
453 sub serve_git {
454         my ($ctx, $epoch, $path) = @_;
455         my $env = $ctx->{env};
456         my $ibx = $ctx->{ibx};
457         my $git = defined $epoch ? $ibx->git_epoch($epoch) : $ibx->git;
458         $git ? PublicInbox::GitHTTPBackend::serve($env, $git, $path) : r404();
459 }
460
461 sub mbox_results {
462         my ($ctx) = @_;
463         if ($ctx->{env}->{QUERY_STRING} =~ /(?:\A|[&;])q=/) {
464                 $ctx->{ibx}->isrch or return need($ctx, 'search');
465                 require PublicInbox::SearchView;
466                 return PublicInbox::SearchView::mbox_results($ctx);
467         }
468         r404();
469 }
470
471 sub serve_mbox_range {
472         my ($ctx, $inbox, $range) = @_;
473         invalid_inbox($ctx, $inbox) || eval {
474                 require PublicInbox::Mbox;
475                 PublicInbox::Mbox::emit_range($ctx, $range);
476         }
477 }
478
479 sub news_www {
480         my ($self) = @_;
481         $self->{news_www} ||= do {
482                 require PublicInbox::NewsWWW;
483                 PublicInbox::NewsWWW->new($self->{pi_cfg});
484         }
485 }
486
487 sub cgit {
488         my ($self) = @_;
489         $self->{cgit} ||= do {
490                 my $pi_cfg = $self->{pi_cfg};
491
492                 if (defined($pi_cfg->{'publicinbox.cgitrc'})) {
493                         require PublicInbox::Cgit;
494                         PublicInbox::Cgit->new($pi_cfg);
495                 } else {
496                         require Plack::Util;
497                         Plack::Util::inline_object(call => sub { r404() });
498                 }
499         }
500 }
501
502 # GET $INBOX/manifest.js.gz
503 sub get_inbox_manifest ($$$) {
504         my ($ctx, $inbox, $key) = @_;
505         my $r404 = invalid_inbox($ctx, $inbox);
506         return $r404 if $r404;
507         require PublicInbox::ManifestJsGz;
508         PublicInbox::ManifestJsGz::per_inbox($ctx);
509 }
510
511 sub get_attach {
512         my ($ctx, $idx, $fn) = @_;
513         require PublicInbox::WwwAttach;
514         PublicInbox::WwwAttach::get_attach($ctx, $idx, $fn);
515 }
516
517 # User-generated content (UGC) may have excessively long lines
518 # and screw up rendering on some browsers, so we use pre-wrap.
519 #
520 # We also force everything to the same scaled font-size because GUI
521 # browsers (tested both Firefox and surf (webkit)) uses a larger font
522 # for the Search <form> element than the rest of the page.  Font size
523 # uniformity is important to people who rely on gigantic fonts.
524 # Finally, we use monospace to ensure the Search field and button
525 # has the same size and spacing as everything else which is
526 # <pre>-formatted anyways.
527 our $STYLE = 'pre{white-space:pre-wrap}*{font-size:100%;font-family:monospace}';
528
529 sub stylesheets_prepare ($$) {
530         my ($self, $upfx) = @_;
531         my $mini = eval {
532                 require CSS::Minifier;
533                 sub { CSS::Minifier::minify(input => $_[0]) };
534         } || eval {
535                 require CSS::Minifier::XS;
536                 sub { CSS::Minifier::XS::minify($_[0]) };
537         } || sub { $_[0] };
538
539         my $css_map = {};
540         my $stylesheets = $self->{pi_cfg}->{css} || [];
541         my $links = [];
542         my $inline_ok = 1;
543
544         foreach my $s (@$stylesheets) {
545                 my $attr = {};
546                 local $_ = $s;
547                 foreach my $k (qw(media title href)) {
548                         if (s/\s*$k='([^']+)'// || s/\s*$k=(\S+)//) {
549                                 $attr->{$k} = $1;
550                         }
551                 }
552
553                 if (defined $attr->{href}) {
554                         $inline_ok = 0;
555                 } else {
556                         my $fn = $_;
557                         my ($key) = (m!([^/]+?)(?:\.css)?\z!i);
558                         if ($key !~ /\A[a-zA-Z0-9_\-\.]+\z/) {
559                                 warn "ignoring $fn, non-ASCII word character\n";
560                                 next;
561                         }
562                         open(my $fh, '<', $fn) or do {
563                                 warn "failed to open $fn: $!\n";
564                                 next;
565                         };
566                         my $ctime = 0;
567                         my $local = do { local $/; <$fh> };
568                         if ($local =~ /\S/) {
569                                 $ctime = sprintf('%x',(stat($fh))[10]);
570                                 $local = $mini->($local);
571                         }
572
573                         # do not let BOFHs override userContent.css:
574                         if ($local =~ /!\s*important\b/i) {
575                                 warn "ignoring $fn since it uses `!important'\n";
576                                 next;
577                         }
578
579                         $css_map->{$key} = $local;
580                         $attr->{href} = "$upfx$key.css?$ctime";
581                         if (defined($attr->{title})) {
582                                 $inline_ok = 0;
583                         } elsif (($attr->{media}||'screen') eq 'screen') {
584                                 $attr->{-inline} = $local;
585                         }
586                 }
587                 push @$links, $attr;
588         }
589
590         my $buf = "<style>$STYLE";
591         if ($inline_ok) {
592                 my @ext; # for media=print and whatnot
593                 foreach my $attr (@$links) {
594                         if (defined(my $str = delete $attr->{-inline})) {
595                                 $buf .= $str;
596                         } else {
597                                 push @ext, $attr;
598                         }
599                 }
600                 $links = \@ext;
601         }
602         $buf .= '</style>';
603
604         if (@$links) {
605                 foreach my $attr (@$links) {
606                         delete $attr->{-inline};
607                         $buf .= "<link\ntype=text/css\nrel=stylesheet";
608                         while (my ($k, $v) = each %$attr) {
609                                 $v = qq{"$v"} if $v =~ /[\s=]/;
610                                 $buf .= qq{\n$k=$v};
611                         }
612                         $buf .= ' />';
613                 }
614                 $self->{"-style-$upfx"} = $buf;
615         } else {
616                 $self->{-style_inline} = $buf;
617         }
618         $self->{-css_map} = $css_map;
619 }
620
621 # returns an HTML fragment with <style> or <link> tags in them
622 # Called by WwwStream by nearly every HTML page
623 sub style {
624         my ($self, $upfx) = @_;
625         $self->{-style_inline} || $self->{"-style-$upfx"} || do {
626                 stylesheets_prepare($self, $upfx);
627                 $self->{-style_inline} || $self->{"-style-$upfx"}
628         };
629 }
630
631 # /$INBOX/$KEY.css endpoint
632 # CSS is configured globally for all inboxes, but we access them on
633 # a per-inbox basis.  This allows administrators to setup per-inbox
634 # static routes to intercept the request before it hits PSGI
635 sub get_css ($$$) {
636         my ($ctx, $inbox, $key) = @_;
637         my $r404 = invalid_inbox($ctx, $inbox);
638         return $r404 if $r404;
639         my $self = $ctx->{www};
640         my $css_map = $self->{-css_map} || stylesheets_prepare($self, '');
641         my $css = $css_map->{$key};
642         if (!defined($css) && $key eq 'userContent') {
643                 my $env = $ctx->{env};
644                 $css = PublicInbox::UserContent::sample($ctx->{ibx}, $env);
645         }
646         defined $css or return r404();
647         my $h = [ 'Content-Length', bytes::length($css),
648                 'Content-Type', 'text/css' ];
649         PublicInbox::GitHTTPBackend::cache_one_year($h);
650         [ 200, $h, [ $css ] ];
651 }
652
653 sub get_description {
654         my ($ctx, $inbox) = @_;
655         invalid_inbox($ctx, $inbox) || do {
656                 my $d = $ctx->{ibx}->description . "\n";
657                 [ 200, [ 'Content-Length', bytes::length($d),
658                         'Content-Type', 'text/plain' ], [ $d ] ];
659         };
660 }
661
662 1;