]> Sergey Matveev's repositories - public-inbox.git/blob - public-inbox.cgi
add example configs for Apache2 mod_perl and CGI
[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 PublicInbox::Config;
16 use URI::Escape qw(uri_escape_utf8 uri_unescape);
17 our $LISTNAME_RE = qr!\A/([\w\.\-]+)!;
18 our $NO_SCRIPT_NAME; # for prettier redirects with mod_perl2
19 our $pi_config;
20 BEGIN {
21         $pi_config = PublicInbox::Config->new;
22         # TODO: detect and reload config as needed
23         $NO_SCRIPT_NAME = 1 if $ENV{NO_SCRIPT_NAME};
24         if ($ENV{MOD_PERL}) {
25                 require CGI;
26                 no warnings;
27                 $CGI::NOSTICKY = 1;
28                 CGI->compile;
29         }
30 }
31
32 if ($ENV{PI_PLACKUP}) {
33         psgi_app();
34 } else {
35         # some servers (Ruby webrick) include scheme://host[:port] here,
36         # which confuses CGI.pm when generating self_url.
37         # RFC 3875 does not mention REQUEST_URI at all,
38         # so nuke it since CGI.pm functions without it.
39         require CGI;
40         delete $ENV{REQUEST_URI};
41         $ENV{SCRIPT_NAME} = '' if $NO_SCRIPT_NAME;
42         my $req = CGI->new;
43         my $ret = main($req, $req->request_method);
44         binmode STDOUT;
45         if (@ARGV && $ARGV[0] eq 'static') {
46                 print $ret->[2]->[0];
47         } else { # CGI
48                 cgi_print($ret);
49         }
50 }
51
52 # private functions below
53
54 sub main {
55         my ($cgi, $method) = @_;
56         my %ctx;
57         if ($method !~ /\AGET|HEAD\z/) {
58                 return r(405, 'Method Not Allowed');
59         }
60         my $path_info = $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'], [ join(' ', @_, "\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;
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);
112         $ctx->{mid} = uri_unescape($mid) unless $ret;
113         $ret;
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, [ '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, [ '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         require Digest::SHA;
150         my $hex = Digest::SHA::sha1_hex($ctx->{mid});
151         $hex =~ /\A([a-f0-9]{2})([a-f0-9]{38})\z/i or
152                         die "BUG: not a SHA-1 hex: $hex";
153
154         my @cmd = ('git', "--git-dir=$ctx->{git_dir}",
155                         qw(cat-file blob), "HEAD:$1/$2");
156         my $cmd = join(' ', @cmd);
157         my $pid = open my $fh, '-|';
158         defined $pid or die "fork failed: $!\n";
159         if ($pid == 0) {
160                 open STDERR, '>', '/dev/null'; # ignore errors
161                 exec @cmd or die "exec failed: $!\n";
162         } else {
163                 my $blob = eval { local $/; <$fh> };
164                 close $fh;
165                 $? == 0 ? \$blob : undef;
166         }
167 }
168
169 # /$LISTNAME/m/$MESSAGE_ID.txt                    -> raw original
170 sub get_mid_txt {
171         my ($ctx, $cgi) = @_;
172         my $x = mid2blob($ctx);
173         $x ? [ 200, [ 'Content-Type' => 'text/plain' ], [ $$x ] ] : r404();
174 }
175
176 # /$LISTNAME/m/$MESSAGE_ID.html                   -> HTML content (short quotes)
177 sub get_mid_html {
178         my ($ctx, $cgi) = @_;
179         my $x = mid2blob($ctx);
180         return r404() unless $x;
181
182         require PublicInbox::View;
183         my $mid_href = PublicInbox::Hval::ascii_html(
184                                                 uri_escape_utf8($ctx->{mid}));
185         my $pfx = "../f/$mid_href.html";
186         require Email::MIME;
187         [ 200, [ 'Content-Type' => 'text/html' ],
188                 [ PublicInbox::View->as_html(Email::MIME->new($$x), $pfx) ] ];
189 }
190
191 # /$LISTNAME/f/$MESSAGE_ID.html                   -> HTML content (fullquotes)
192 sub get_full_html {
193         my ($ctx, $cgi) = @_;
194         my $x = mid2blob($ctx);
195         return r404() unless $x;
196         require PublicInbox::View;
197         require Email::MIME;
198         [ 200, [ 'Content-Type' => 'text/html' ],
199                 [ PublicInbox::View->as_html(Email::MIME->new($$x))] ];
200 }
201
202 sub self_url {
203         my ($cgi) = @_;
204         ref($cgi) eq 'CGI' ? $cgi->self_url : $cgi->uri->as_string;
205 }
206
207 sub redirect_list_index {
208         my ($ctx, $cgi) = @_;
209         do_redirect(self_url($cgi) . "/");
210 }
211
212 sub redirect_mid {
213         my ($ctx, $cgi) = @_;
214         my $url = self_url($cgi);
215         $url =~ s!/f/!/m/!;
216         do_redirect($url . '.html');
217 }
218
219 sub do_redirect {
220         my ($url) = @_;
221         [ 301,
222           [ Location => $url, 'Content-Type' => 'text/plain' ],
223           [ "Redirecting to $url\n" ]
224         ]
225 }
226
227 sub psgi_app {
228         # preload so we are CoW friendly
229         require PublicInbox::Feed;
230         require PublicInbox::View;
231         require Mail::Thread;
232         require Digest::SHA;
233         require POSIX;
234         require XML::Atom::SimpleFeed;
235         require Plack::Request;
236         sub {
237                 my $req = Plack::Request->new(@_);
238                 main($req, $req->method);
239         };
240 }
241
242 sub cgi_print {
243         my ($ret) = @_;
244         my ($status, $headers, $body) = @$ret;
245         my %codes = (
246                 200 => 'OK',
247                 301 => 'Moved Permanently',
248                 404 => 'Not Found',
249                 405 => 'Method Not Allowed',
250         );
251
252         print "Status: $status $codes{$status}\r\n";
253         my @tmp = @$headers;
254         while (my ($k, $v) = splice(@tmp, 0, 2)) {
255                 print "$k: $v\r\n";
256         }
257         print "\r\n", $body->[0];
258 }