]> Sergey Matveev's repositories - public-inbox.git/blob - public-inbox.cgi
1fcc04fa195bcb18a318080fbad6ced743c72d71
[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 use strict;
5 use warnings;
6 use IO::Handle;
7 use PublicInbox::WWW;
8 use CGI qw/-nosticky/;
9 our $NO_SCRIPT_NAME;
10 our %HTTP_CODES;
11 BEGIN {
12         $NO_SCRIPT_NAME = 1 if $ENV{NO_SCRIPT_NAME};
13         if ($ENV{MOD_PERL}) {
14                 CGI->compile;
15                 PublicInbox::WWW->preload;
16         }
17
18         %HTTP_CODES = (
19                 200 => 'OK',
20                 301 => 'Moved Permanently',
21                 302 => 'Found',
22                 404 => 'Not Found',
23                 405 => 'Method Not Allowed',
24                 501 => 'Not Implemented',
25         );
26 }
27
28 # some servers (Ruby webrick) include scheme://host[:port] here,
29 # which confuses CGI.pm when generating self_url.
30 # RFC 3875 does not mention REQUEST_URI at all,
31 # so nuke it since CGI.pm functions without it.
32 delete $ENV{REQUEST_URI};
33 $ENV{SCRIPT_NAME} = '' if $NO_SCRIPT_NAME;
34 my $req = CGI->new;
35 my $ret = PublicInbox::WWW::run($req, $req->request_method);
36
37 my $out = select;
38 $out->binmode;
39
40 if (ref($ret) eq 'CODE') {
41         $ret->(*dump_header);
42 } else {
43         my ($status, $headers, $body) = @$ret;
44
45         dump_header([$status, $headers])->write($body->[0]);
46 }
47
48 sub dump_header {
49         my ($res) = @_;
50         my $fh = select;
51         my ($status, $headers) = @$res;
52         $fh->write("Status: $status $HTTP_CODES{$status}\r\n");
53         my @tmp = @$headers;
54         while (my ($k, $v) = splice(@tmp, 0, 2)) {
55                 $fh->write("$k: $v\r\n");
56         }
57         $fh->write("\r\n");
58         $fh;
59 }