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