]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WWW.pm
wwwlisting: avoid hogging event loop
[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,40}!;
33
34 sub new {
35         my ($class, $pi_config) = @_;
36         $pi_config ||= PublicInbox::Config->new;
37         bless { pi_config => $pi_config }, $class;
38 }
39
40 # backwards compatibility, do not use
41 sub run {
42         my ($req, $method) = @_;
43         PublicInbox::WWW->new->call($req->env);
44 }
45
46 sub call {
47         my ($self, $env) = @_;
48         my $ctx = { env => $env, www => $self };
49
50         # we don't care about multi-value
51         %{$ctx->{qp}} = map {
52                 utf8::decode($_);
53                 tr/+/ /;
54                 my ($k, $v) = split('=', $_, 2);
55                 $v = uri_unescape($v // '');
56                 # none of the keys we care about will need escaping
57                 $k => $v;
58         } split(/[&;]+/, $env->{QUERY_STRING});
59
60         my $path_info = path_info_raw($env);
61         my $method = $env->{REQUEST_METHOD};
62
63         if ($method eq 'POST') {
64                 if ($path_info =~ m!$INBOX_RE/(?:(?:git/)?([0-9]+)(?:\.git)?/)?
65                                         (git-upload-pack)\z!x) {
66                         my ($epoch, $path) = ($2, $3);
67                         return invalid_inbox($ctx, $1) ||
68                                 serve_git($ctx, $epoch, $path);
69                 } elsif ($path_info =~ m!$INBOX_RE/(\w+)\.sql\.gz\z!o) {
70                         return get_altid_dump($ctx, $1, $2);
71                 } elsif ($path_info =~ m!$INBOX_RE/!o) {
72                         return invalid_inbox($ctx, $1) || mbox_results($ctx);
73                 }
74         }
75         elsif ($method !~ /\A(?:GET|HEAD)\z/) {
76                 return r(405);
77         }
78
79         # top-level indices and feeds
80         if ($path_info eq '/') {
81                 require PublicInbox::WwwListing;
82                 PublicInbox::WwwListing->response($ctx);
83         } elsif ($path_info eq '/manifest.js.gz') {
84                 require PublicInbox::ManifestJsGz;
85                 PublicInbox::ManifestJsGz->response($ctx);
86         } elsif ($path_info =~ m!$INBOX_RE\z!o) {
87                 invalid_inbox($ctx, $1) || r301($ctx, $1);
88         } elsif ($path_info =~ m!$INBOX_RE(?:/|/index\.html)?\z!o) {
89                 invalid_inbox($ctx, $1) || get_index($ctx);
90         } elsif ($path_info =~ m!$INBOX_RE/(?:atom\.xml|new\.atom)\z!o) {
91                 invalid_inbox($ctx, $1) || get_atom($ctx);
92         } elsif ($path_info =~ m!$INBOX_RE/new\.html\z!o) {
93                 invalid_inbox($ctx, $1) || get_new($ctx);
94         } elsif ($path_info =~ m!$INBOX_RE/description\z!o) {
95                 get_description($ctx, $1);
96         } elsif ($path_info =~ m!$INBOX_RE/(?:(?:git/)?([0-9]+)(?:\.git)?/)?
97                                 ($PublicInbox::GitHTTPBackend::ANY)\z!ox) {
98                 my ($epoch, $path) = ($2, $3);
99                 invalid_inbox($ctx, $1) || serve_git($ctx, $epoch, $path);
100         } elsif ($path_info =~ m!$INBOX_RE/([a-zA-Z0-9_\-]+).mbox\.gz\z!o) {
101                 serve_mbox_range($ctx, $1, $2);
102         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/$END_RE\z!o) {
103                 msg_page($ctx, $1, $2, $3);
104
105         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/$ATTACH_RE\z!o) {
106                 my ($idx, $fn) = ($3, $4);
107                 invalid_inbox_mid($ctx, $1, $2) || get_attach($ctx, $idx, $fn);
108         # in case people leave off the trailing slash:
109         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/(T|t)\z!o) {
110                 my ($inbox, $mid_ue, $suffix) = ($1, $2, $3);
111                 $suffix .= $suffix =~ /\A[tT]\z/ ? '/#u' : '/';
112                 r301($ctx, $inbox, $mid_ue, $suffix);
113
114         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/R/?\z!o) {
115                 my ($inbox, $mid_ue) = ($1, $2);
116                 r301($ctx, $inbox, $mid_ue, '#R');
117
118         } elsif ($path_info =~ m!$INBOX_RE/$MID_RE/f/?\z!o) {
119                 r301($ctx, $1, $2);
120         } elsif ($path_info =~ m!$INBOX_RE/_/text(?:/(.*))?\z!o) {
121                 get_text($ctx, $1, $2);
122         } elsif ($path_info =~ m!$INBOX_RE/([a-zA-Z0-9_\-\.]+)\.css\z!o) {
123                 get_css($ctx, $1, $2);
124         } elsif ($path_info =~ m!$INBOX_RE/manifest\.js\.gz\z!o) {
125                 get_inbox_manifest($ctx, $1, $2);
126         } elsif ($path_info =~ m!$INBOX_RE/($OID_RE)/s/\z!o) {
127                 get_vcs_object($ctx, $1, $2);
128         } elsif ($path_info =~ m!$INBOX_RE/($OID_RE)/s/
129                                 ($PublicInbox::Hval::FN)\z!ox) {
130                 get_vcs_object($ctx, $1, $2, $3);
131         } elsif ($path_info =~ m!$INBOX_RE/($OID_RE)/s\z!o) {
132                 r301($ctx, $1, $2, 's/');
133         } elsif ($path_info =~ m!$INBOX_RE/(\w+)\.sql\.gz\z!o) {
134                 get_altid_dump($ctx, $1, $2);
135         # convenience redirects order matters
136         } elsif ($path_info =~ m!$INBOX_RE/([^/]{2,})\z!o) {
137                 r301($ctx, $1, $2);
138
139         } else {
140                 legacy_redirects($ctx, $path_info);
141         }
142 }
143
144 # for CoW-friendliness, MOOOOO!  Even for single-process setups,
145 # we want to get all immortal allocations done early to avoid heap
146 # fragmentation since common allocators favor a large contiguous heap.
147 sub preload {
148         my ($self) = @_;
149
150         # populate caches used by Encode internally, since emails
151         # may show up with any encoding.
152         require Encode;
153         Encode::find_encoding($_) for Encode->encodings(':all');
154
155         require PublicInbox::ExtMsg;
156         require PublicInbox::Feed;
157         require PublicInbox::View;
158         require PublicInbox::SearchThread;
159         require PublicInbox::Eml;
160         require PublicInbox::Mbox;
161         require PublicInbox::ViewVCS;
162         require PublicInbox::WwwText;
163         require PublicInbox::WwwAttach;
164         eval {
165                 require PublicInbox::Search;
166                 PublicInbox::Search::load_xapian();
167         };
168         for (qw(SearchView MboxGz WwwAltId)) {
169                 eval "require PublicInbox::$_;";
170         }
171         if (ref($self)) {
172                 my $pi_config = $self->{pi_config};
173                 if (defined($pi_config->{'publicinbox.cgitrc'})) {
174                         $pi_config->limiter('-cgit');
175                 }
176                 $self->cgit;
177                 $self->stylesheets_prepare($_) for ('', '../', '../../');
178                 $self->news_www;
179                 $pi_config->each_inbox(\&preload_inbox);
180         }
181 }
182
183 sub preload_inbox {
184         my $ibx = shift;
185         $ibx->altid_map;
186         $ibx->cloneurl;
187         $ibx->description;
188         $ibx->base_url;
189 }
190
191 # private functions below
192
193 sub r404 {
194         my ($ctx) = @_;
195         if ($ctx && $ctx->{mid}) {
196                 require PublicInbox::ExtMsg;
197                 return PublicInbox::ExtMsg::ext_msg($ctx);
198         }
199         r(404);
200 }
201
202 sub news_cgit_fallback ($) {
203         my ($ctx) = @_;
204         my $www = $ctx->{www};
205         my $env = $ctx->{env};
206         my $res = $www->news_www->call($env);
207         $res->[0] == 404 ? $www->cgit->call($env) : $res;
208 }
209
210 # returns undef if valid, array ref response if invalid
211 sub invalid_inbox ($$) {
212         my ($ctx, $inbox) = @_;
213         my $ibx = $ctx->{www}->{pi_config}->lookup_name($inbox);
214         if (defined $ibx) {
215                 $ctx->{-inbox} = $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->{-inbox};
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->{-inbox}->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->{-inbox}->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->{-inbox}->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->{-inbox}->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->{-inbox};
416         unless ($ibx) {
417                 my $r404 = invalid_inbox($ctx, $inbox);
418                 return $r404 if $r404;
419                 $ibx = $ctx->{-inbox};
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->{-inbox};
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->{-inbox}->search 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_config});
484         }
485 }
486
487 sub cgit {
488         my ($self) = @_;
489         $self->{cgit} ||= do {
490                 my $pi_config = $self->{pi_config};
491
492                 if (defined($pi_config->{'publicinbox.cgitrc'})) {
493                         require PublicInbox::Cgit;
494                         PublicInbox::Cgit->new($pi_config);
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->response($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_config}->{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->{-inbox}, $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->{-inbox}->description . "\n";
657                 [ 200, [ 'Content-Length', bytes::length($d),
658                         'Content-Type', 'text/plain' ], [ $d ] ];
659         };
660 }
661
662 1;