]> Sergey Matveev's repositories - public-inbox.git/blob - public-inbox.cgi
huge refactor of encoding handling
[public-inbox.git] / public-inbox.cgi
1 #!/usr/bin/perl -w
2 # Copyright (C) 2014, Eric Wong <normalperson@yhbt.net> and all contributors
3 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
4 #
5 # We focus on the lowest common denominators here:
6 # - targeted at text-only console browsers (lynx, w3m, etc..)
7 # - Only basic HTML, CSS only for line-wrapping <pre> text content for GUIs
8 # - No JavaScript, graphics or icons allowed.
9 # - Must not rely on static content
10 # - UTF-8 is only for user-content, 7-bit US-ASCII for us
11
12 use 5.008;
13 use strict;
14 use warnings;
15 use CGI qw(:cgi -nosticky); # PSGI/FastCGI/mod_perl compat
16 use Encode qw(find_encoding);
17 use PublicInbox::Config;
18 use URI::Escape qw(uri_escape uri_unescape);
19 my $enc_utf8 = find_encoding('UTF-8');
20 our $LISTNAME_RE = qr!\A/([\w\.\-]+)!;
21 our $pi_config;
22 BEGIN {
23         $pi_config = PublicInbox::Config->new;
24         # TODO: detect and reload config as needed
25         if ($ENV{MOD_PERL}) {
26                 CGI->compile;
27         }
28 }
29
30 my $ret = main();
31
32 my ($status, $headers, $body) = @$ret;
33 set_binmode($headers);
34 if (@ARGV && $ARGV[0] eq 'static') {
35         print $body;
36 } else { # CGI
37         print "Status: $status\r\n";
38         while (my ($k, $v) = each %$headers) {
39                 print "$k: $v\r\n";
40         }
41         print "\r\n", $body;
42 }
43
44 # TODO: plack support
45
46 # private functions below
47
48 sub main {
49         # some servers (Ruby webrick) include scheme://host[:port] here,
50         # which confuses CGI.pm when generating self_url.
51         # RFC 3875 does not mention REQUEST_URI at all,
52         # so nuke it since CGI.pm functions without it.
53         delete $ENV{REQUEST_URI};
54
55         my $cgi = CGI->new;
56         my %ctx;
57         if ($cgi->request_method !~ /\AGET|HEAD\z/) {
58                 return r("405 Method Not Allowed");
59         }
60         my $path_info = $enc_utf8->decode($cgi->path_info);
61
62         # top-level indices and feeds
63         if ($path_info eq "/") {
64                 r404();
65         } elsif ($path_info =~ m!$LISTNAME_RE\z!o) {
66                 invalid_list(\%ctx, $1) || redirect_list_index(\%ctx, $cgi);
67         } elsif ($path_info =~ m!$LISTNAME_RE(?:/|/index\.html)?\z!o) {
68                 invalid_list(\%ctx, $1) || get_index(\%ctx, $cgi, 0);
69         } elsif ($path_info =~ m!$LISTNAME_RE/atom\.xml\z!o) {
70                 invalid_list(\%ctx, $1) || get_atom(\%ctx, $cgi, 0);
71
72         # single-message pages
73         } elsif ($path_info =~ m!$LISTNAME_RE/m/(\S+)\.txt\z!o) {
74                 invalid_list_mid(\%ctx, $1, $2) || get_mid_txt(\%ctx, $cgi);
75         } elsif ($path_info =~ m!$LISTNAME_RE/m/(\S+)\.html\z!o) {
76                 invalid_list_mid(\%ctx, $1, $2) || get_mid_html(\%ctx, $cgi);
77
78         # full-message page
79         } elsif ($path_info =~ m!$LISTNAME_RE/f/(\S+)\.html\z!o) {
80                 invalid_list_mid(\%ctx, $1, $2) || get_full_html(\%ctx, $cgi);
81
82         # convenience redirects, order matters
83         } elsif ($path_info =~ m!$LISTNAME_RE/(?:m|f)/(\S+)\z!o) {
84                 invalid_list_mid(\%ctx, $1, $2) || redirect_mid(\%ctx, $cgi);
85
86         } else {
87                 r404();
88         }
89 }
90
91 sub r404 { r("404 Not Found") }
92
93 # simple response for errors
94 sub r { [ $_[0], { 'Content-Type' => 'text/plain' }, $_[0]."\n" ] }
95
96 # returns undef if valid, array ref response if invalid
97 sub invalid_list {
98         my ($ctx, $listname) = @_;
99         my $git_dir = $pi_config->get($listname, "mainrepo");
100         if (defined $git_dir) {
101                 $ctx->{git_dir} = $git_dir;
102                 $ctx->{listname} = $listname;
103                 return undef;
104         }
105         r404();
106 }
107
108 # returns undef if valid, array ref response if invalid
109 sub invalid_list_mid {
110         my ($ctx, $listname, $mid) = @_;
111         my $ret = invalid_list($ctx, $listname, $mid) and return $ret;
112         $ctx->{mid} = uri_unescape($mid);
113         undef;
114 }
115
116 # /$LISTNAME/atom.xml                       -> Atom feed, includes replies
117 sub get_atom {
118         my ($ctx, $cgi, $top) = @_;
119         require PublicInbox::Feed;
120         [ '200 OK', { 'Content-Type' => 'application/xml' },
121           PublicInbox::Feed->generate({
122                         git_dir => $ctx->{git_dir},
123                         listname => $ctx->{listname},
124                         pi_config => $pi_config,
125                         cgi => $cgi,
126                         top => $top,
127                 })
128         ];
129 }
130
131 # /$LISTNAME/?r=$GIT_COMMIT                 -> HTML only
132 sub get_index {
133         my ($ctx, $cgi, $top) = @_;
134         require PublicInbox::Feed;
135         [ '200 OK', { 'Content-Type' => 'text/html' },
136           PublicInbox::Feed->generate_html_index({
137                         git_dir => $ctx->{git_dir},
138                         listname => $ctx->{listname},
139                         pi_config => $pi_config,
140                         cgi => $cgi,
141                         top => $top,
142                 })
143         ];
144 }
145
146 # just returns a string ref for the blob in the current ctx
147 sub mid2blob {
148         my ($ctx) = @_;
149         local $ENV{GIT_DIR} = $ctx->{git_dir};
150         require Digest::SHA;
151         my $hex = Digest::SHA::sha1_hex($ctx->{mid});
152         $hex =~ /\A([a-f0-9]{2})([a-f0-9]{38})\z/i or
153                         die "BUG: not a SHA-1 hex: $hex";
154         my $blob = `git cat-file blob HEAD:$1/$2 2>/dev/null`;
155         $? == 0 ? \$blob : undef;
156 }
157
158 # /$LISTNAME/m/$MESSAGE_ID.txt                    -> raw original
159 sub get_mid_txt {
160         my ($ctx, $cgi) = @_;
161         my $x = mid2blob($ctx);
162         $x ? [ "200 OK", {'Content-Type' => 'text/plain'}, $$x ] : r404();
163 }
164
165 # /$LISTNAME/m/$MESSAGE_ID.html                   -> HTML content (short quotes)
166 sub get_mid_html {
167         my ($ctx, $cgi) = @_;
168         my $x = mid2blob($ctx);
169         return r404() unless $x;
170
171         require PublicInbox::View;
172         my $mid_href = PublicInbox::Hval::ascii_html(uri_escape($ctx->{mid}));
173         my $pfx = "../f/$mid_href.html";
174         require Email::MIME;
175         [ "200 OK", {'Content-Type' => 'text/html'},
176                 PublicInbox::View->as_html(Email::MIME->new($$x), $pfx)];
177 }
178
179 # /$LISTNAME/f/$MESSAGE_ID.html                   -> HTML content (fullquotes)
180 sub get_full_html {
181         my ($ctx, $cgi) = @_;
182         my $x = mid2blob($ctx);
183         return r404() unless $x;
184         require PublicInbox::View;
185         require Email::MIME;
186         [ "200 OK", {'Content-Type' => 'text/html'},
187                 PublicInbox::View->as_html(Email::MIME->new($$x))];
188 }
189
190 sub redirect_list_index {
191         my ($ctx, $cgi) = @_;
192         do_redirect($cgi->self_url . "/");
193 }
194
195 sub redirect_mid {
196         my ($ctx, $cgi) = @_;
197         my $url = $cgi->self_url;
198         $url =~ s!/f/!/m/!;
199         do_redirect($url . '.html');
200 }
201
202 sub do_redirect {
203         my ($url) = @_;
204         [ '301 Moved Permanently',
205           { Location => $url, 'Content-Type' => 'text/plain' },
206           "Redirecting to $url\n"
207         ]
208 }
209
210 # only used for CGI and static file generation modes
211 sub set_binmode {
212         my ($headers) = @_;
213         if ($headers->{'Content-Type'} eq 'text/plain') {
214                 # no way to validate raw messages, mixed encoding is possible.
215                 binmode STDOUT;
216         } else { # strict encoding for HTML and XML
217                 binmode STDOUT, ':encoding(us-ascii)';
218         }
219 }