#!/usr/bin/perl
# plexus -- the bind-stub for the HyperText Tranfer Protocol Daemon
#
# $Id: plexus,v 2.3 1993/07/16 18:50:19 sanders Exp $
#
# This does the critical root-stuff like binding to the port.
# Originally (httpd-stub.pl) by Marc VanHeyningen, March 1993
# Modified by Tony Sanders <sanders@bsdi.com>, April 1993
#

($#ARGV >= $[) && ($port = shift);		# get port from command line

chdir($http_root = $ENV{'HTTPD'} || "/usr/local/www")
    || die "chdir: $http_root: $!";
$http_config = $ENV{'HTTPD_CONF'} || "server/plexus.conf";
require "$http_config";

$running_as_root = ($< == 0);
$port || ($port = ($running_as_root ? ((getservbyname($http_service,
    $http_proto))[2] || $http_defaultport) : $http_userport));

$proto = (getprotobyname('tcp'))[2] || $http_defaultproto;
$this = pack($sockaddr, &AF_INET, $port, "\0\0\0\0");

socket(S, &AF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
setsockopt(S, &SOL_SOCKET, &SO_REUSEADDR, pack("l", 1));	# non-critical
bind(S, $this) || die "bind: $!";
listen(S, &SOMAXCONN) || die "listen: $!";
select(S); $| = 1; select(STDOUT);

$http_chroot && $running_as_root &&
    (chroot($http_root) || die "chroot: $http_root: $!");

if($running_as_root) {
    $( = $) = (getgrnam("$http_group"))[2] || die "getgrnam: $http_group: $!";
    $< = $> = (getpwnam("$http_user"))[2] || die "getpwnam: $http_user: $!";
}

# exec the server main loop
exec "$http_server", $http_config, $port, $running_as_root, fileno(S);
die "$http_server: $!";
