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