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