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