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