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