2 # Copyright (C) 2016 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
5 # Standalone HTTP server for public-inbox.
9 use PublicInbox::Daemon;
10 use PublicInbox::HTTP;
17 eval { $app = Plack::Util::load_psgi(@ARGV) };
20 "$0 runs in /, command-line paths must be absolute\n";
23 require PublicInbox::WWW;
24 PublicInbox::WWW->preload;
25 my $www = PublicInbox::WWW->new;
38 "Plack::Middleware::Deflater missing, bandwidth will be wasted\n";
40 eval { enable 'ReverseProxy' };
42 "Plack::Middleware::ReverseProxy missing,\n",
43 "URL generation for redirects may be wrong if behind a reverse proxy\n";
46 sub { $www->call(@_) };
52 PublicInbox::Daemon::run('0.0.0.0:8080', $refresh,
53 sub ($$$) { # post_accept
54 my ($client, $addr, $srv) = @_;
55 my $fd = fileno($srv);
56 my $h = $httpds{$fd} ||= PublicInbox::HTTPD->new($srv, $app);
57 PublicInbox::HTTP->new($client, $addr, $h),
62 # XXX This is a totally unstable API for public-inbox internal use only
63 # This is exposed via the 'pi-httpd.async' key in the PSGI env hash.
64 # The name of this key is not even stable!
65 # Currently is is intended for use with read-only pipes.
66 package PublicInbox::HTTPD::Async;
69 use base qw(Danga::Socket);
73 my ($class, $io, $cb) = @_;
74 my $self = fields::new($class);
75 IO::Handle::blocking($io, 0);
76 $self->SUPER::new($io);
82 sub event_read { $_[0]->{cb}->() }
83 sub event_hup { $_[0]->{cb}->() }
84 sub event_err { $_[0]->{cb}->() }
85 sub sysread { shift->{sock}->sysread(@_) }
89 package PublicInbox::HTTPD;
96 PublicInbox::HTTPD::Async->new($io, $cb);
100 my ($class, $sock, $app) = @_;
101 my $n = getsockname($sock) or die "not a socket: $sock $!\n";
103 if (length($n) >= 28) {
105 ($port, $addr) = Socket6::unpack_sockaddr_in6($n);
107 ($port, $addr) = Socket::unpack_sockaddr_in($n);
113 SERVER_NAME => $addr,
114 SERVER_PORT => $port,
116 'psgi.version' => [ 1, 1 ],
117 'psgi.errors' => \*STDERR,
118 'psgi.url_scheme' => 'http',
119 'psgi.nonblocking' => Plack::Util::TRUE,
120 'psgi.streaming' => Plack::Util::TRUE,
121 'psgi.run_once' => Plack::Util::FALSE,
122 'psgi.multithread' => Plack::Util::FALSE,
123 'psgi.multiprocess' => Plack::Util::TRUE,
124 'psgix.harakiri'=> Plack::Util::FALSE,
125 'psgix.input.buffered' => Plack::Util::TRUE,
126 'pi-httpd.async' => do {