#!/usr/local/bin/perl
#
#	Server to translate direct connections to port 9100 to
#	a lpr job.
#	Invoke with -i if not running from inetd.
#	Edit the lprcmd and port number if necessary.
#

require 'sys/socket.ph';

$port = 9100;
$lprcmd = "| lpr";

$sockaddr = 'S n a4 x8';

if ($#ARGV >= 0 && $ARGV[0] eq "-i")
{
	&standalone();
}
else
{
	&serve(*stdin);
}
exit 0;

sub serve
{
	local(*F)	= @_;

	$addr = getpeername(F);
	($af, $port, $inetaddr) = unpack($sockaddr, $addr);
#	print STDERR "$af $port @inetaddr\n";
	($name, $aliases, $addrtype, $length, @addrs) = gethostbyaddr($inetaddr, &AF_INET);
	open(L, $lprcmd) || die "open: $!";
	for (;;)
	{
		$nread = read(F, $buffer, 1024);
		last if $nread == 0;
		print(L $buffer);
	}
	close(L);
}

sub standalone
{
	($name, $aliases, $proto) = getprotobyname('tcp');
	$this = pack($sockaddr, &AF_INET, $port, "\0\0\0\0");
	select(NS); $| = 1; select(stdout);
	socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
	bind(S, $this) || die "bind: $!";
	listen(S, 5) || die "connect: $!";
	select(S); $| = 1; select(stdout);
	for (;;)
	{
#		print STDERR "Listening again\n";
		($addr = accept(NS,S)) || die $!;
#		print STDERR "Accept ok\n";
		($af,$port,$inetaddr) = unpack($sockaddr,$addr);
		@inetaddr = unpack('C4',$inetaddr);
#		print STDERR "$af $port @inetaddr\n";
		&serve(*NS);
	}
}
