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