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