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