Net-Daemon-0.49/0000755000000000000000000000000013733426140012076 5ustar rootrootNet-Daemon-0.49/t/0000755000000000000000000000000013733426140012341 5ustar rootrootNet-Daemon-0.49/t/unix.t0000644000000000000000000000341013732471340013510 0ustar rootroot# -*- perl -*- # # $Id: unix.t,v 1.2 1999/08/12 14:28:59 joe Exp $ # require 5.004; use strict; use IO::Socket (); use Config (); use Net::Daemon::Test (); if ( $^O eq "MSWin32" ) { print "1..0\n"; exit 0; } my $numTests = 5; my ( $handle, $port ) = Net::Daemon::Test->Child( $numTests, $^X, '-Iblib/lib', '-Iblib/arch', 't/server', '--localpath=mysock', '--mode=fork', '--timeout', 60 ); print "Making first connection to port $port...\n"; my $fh = IO::Socket::UNIX->new( 'Peer' => $port ); if ( !$fh ) { print "Failed to connect: " . ( $@ || $! ) . "\n"; } printf( "%s 1\n", $fh ? "ok" : "not ok" ); printf( "%s 2\n", $fh->close() ? "ok" : "not ok" ); print "Making second connection to port $port...\n"; $fh = IO::Socket::UNIX->new( 'Peer' => $port ); if ( !$fh ) { print "Failed to connect: " . ( $@ || $! ) . "\n"; } printf( "%s 3\n", $fh ? "ok" : "not ok" ); eval { for ( my $i = 0; $i < 20; $i++ ) { print "Writing number: $i\n"; if ( !$fh->print("$i\n") || !$fh->flush() ) { die "Client: Error while writing number $i: " . $fh->error() . " ($!)"; } print "Written.\n"; my ($line) = $fh->getline(); if ( !defined($line) ) { die "Client: Error while reading number $i: " . $fh->error() . " ($!)"; } if ( $line !~ /(\d+)/ || $1 != $i * 2 ) { die "Wrong response, exptected " . ( $i * 2 ) . ", got $line"; } } }; if ($@) { print STDERR "$@\n"; print "not ok 4\n"; } else { print "ok 4\n"; } printf( "%s 5\n", $fh->close() ? "ok" : "not ok" ); END { if ($handle) { $handle->Terminate() } unlink "ndtest.prt" if -e "ndtest.prt"; unlink "mysock" if -e "mysock"; exit 0; } Net-Daemon-0.49/t/fork.t0000644000000000000000000000374213732510212013466 0ustar rootroot# -*- perl -*- # # $Id: fork.t,v 1.2 1999/08/12 14:28:59 joe Exp $ # require 5.004; use strict; use IO::Socket (); use Config (); use Net::Daemon::Test (); my $ok; eval { if ( $^O ne "MSWin32" ) { my $pid = fork(); if ( defined($pid) ) { if ( !$pid ) { exit 0; } # Child } $ok = 1; } }; if ( !$ok ) { print "1..0 # SKIP This test requires a system with working forks.\n"; exit; } my $numTests = 5; my ( $handle, $port ); if (@ARGV) { $port = shift @ARGV; } else { ( $handle, $port ) = Net::Daemon::Test->Child( $numTests, $^X, '-Iblib/lib', '-Iblib/arch', 't/server', '--mode=fork', '--debug', '--timeout', 60 ); } print "Making first connection to port $port...\n"; my $fh = IO::Socket::INET->new( 'PeerAddr' => '127.0.0.1', 'PeerPort' => $port ); printf( "%s 1\n", $fh ? "ok" : "not ok" ); printf( "%s 2\n", $fh->close() ? "ok" : "not ok" ); print "Making second connection to port $port...\n"; $fh = IO::Socket::INET->new( 'PeerAddr' => '127.0.0.1', 'PeerPort' => $port ); printf( "%s 3\n", $fh ? "ok" : "not ok" ); eval { for ( my $i = 0; $i < 20; $i++ ) { print "Writing number: $i\n"; if ( !$fh->print("$i\n") || !$fh->flush() ) { die "Client: Error while writing number $i: " . $fh->error() . " ($!)"; } print "Written.\n"; my ($line) = $fh->getline(); if ( !defined($line) ) { die "Client: Error while reading number $i: " . $fh->error() . " ($!)"; } if ( $line !~ /(\d+)/ || $1 != $i * 2 ) { die "Wrong response, exptected " . ( $i * 2 ) . ", got $line"; } } }; if ($@) { print STDERR "$@\n"; print "not ok 4\n"; } else { print "ok 4\n"; } printf( "%s 5\n", $fh->close() ? "ok" : "not ok" ); END { if ($handle) { $handle->Terminate() } if ( -f "ndtest.prt" ) { unlink "ndtest.prt" } exit 0; } Net-Daemon-0.49/t/base.t0000644000000000000000000000015413732510212013431 0ustar rootrootuse Test::More tests => 3; use_ok('Net::Daemon'); use_ok('Net::Daemon::Log'); use_ok('Net::Daemon::Test'); Net-Daemon-0.49/t/config.t0000644000000000000000000000534213733422726014005 0ustar rootroot# -*- perl -*- # # $Id: config.t,v 1.2 1999/08/12 14:28:59 joe Exp $ # require 5.004; use strict; use IO::Socket (); use Config (); use Net::Daemon::Test (); use Socket (); my $CONFIG_FILE = "t/config"; my $numTests = 5; sub RunTest ($$) { my $config = shift; my $numTests = shift; if ( !open( CF, ">$CONFIG_FILE" ) || !( print CF $config ) || !close(CF) ) { die "Error while creating config file $CONFIG_FILE: $!"; } my ( $handle, $port ) = Net::Daemon::Test->Child( $numTests, $^X, '-Iblib/lib', '-Iblib/arch', 't/server', '--debug', '--mode=single', '--configfile', $CONFIG_FILE ); my $fh = IO::Socket::INET->new( 'PeerAddr' => '127.0.0.1', 'PeerPort' => $port ); my $result; my $success = $fh && $fh->print("1\n") && defined( $result = $fh->getline() ) && $result =~ /2/; $handle->Terminate(); $success ? "" : "not "; } print "Testing config file with open client list.\n"; my $ok = RunTest( q/{'mode' => 'single', 'timeout' => 60}/, $numTests ); print "${ok}ok 1\n"; print "Testing config file with client 127.0.0.1.\n"; $ok = RunTest( q/ { 'mode' => 'single', 'timeout' => 60, 'clients' => [ { 'mask' => '^127\.0\.0\.1$', 'accept' => 1 }, { 'mask' => '.*', 'accept' => 0 } ] }/, undef ); print "${ok}ok 2\n"; print "Testing config file with client !127.0.0.1.\n"; $ok = RunTest( q/ { 'mode' => 'single', 'timeout' => 60, 'clients' => [ { 'mask' => '^127\.0\.0\.1$', 'accept' => 0 }, { 'mask' => '.*', 'accept' => 1 } ] }/, undef ); print( ( $ok ? "" : "not " ), "ok 3\n" ); my $hostname = gethostbyaddr( Socket::inet_aton("127.0.0.1"), Socket::AF_INET() ); if ($hostname) { my $regexp = $hostname; $regexp =~ s/\./\\\./g; print "Testing config file with client $hostname.\n"; $ok = RunTest( q/ { 'mode' => 'single', 'timeout' => 60, 'clients' => [ { 'mask' => '^/ . $regexp . q/$', 'accept' => 1 }, { 'mask' => '.*', 'accept' => 0 } ] }/, undef ); print "${ok}ok 4\n"; print "Testing config file with client !$hostname\n"; $ok = RunTest( q/ { 'mode' => 'single', 'timeout' => 60, 'clients' => [ { 'mask' => '^/ . $regexp . q/$', 'accept' => 0 }, { 'mask' => '.*', 'accept' => 1 } ] }/, undef ); print( ( $ok ? "" : "not " ), "ok 5\n" ); } else { print "ok 4 # skip\n"; print "ok 5 # skip\n"; } END { if ( -f "ndtest.prt" ) { unlink "ndtest.prt" } } Net-Daemon-0.49/t/ithreadm.t0000644000000000000000000000447213733420721014331 0ustar rootroot#!perl use strict; use warnings; use IO::Socket (); use Config (); use Net::Daemon::Test (); use Fcntl (); use Config; $| = 1; $^W = 1; if ( !$Config{useithreads} ) { print "1..0 # SKIP This test requires a perl with working ithreads.\n"; exit 0; } if ( $^O eq "MSWin32" ) { print "1..0 # SKIP This test is failing on windows I think due to Win32-Process but it needs help right now.\n"; exit 0; } require threads; my ( $handle, $port ); if (@ARGV) { $port = shift @ARGV; } else { ( $handle, $port ) = Net::Daemon::Test->Child( 10, $^X, '-Iblib/lib', '-Iblib/arch', 't/server', '--mode=ithreads', 'logfile=stderr', 'debug' ); } sub IsNum { my $str = shift; ( defined($str) && $str =~ /(\d+)/ ) ? $1 : undef; } sub ReadWrite { my $fh = shift; my $i = shift; my $j = shift; die "Child $i: Error while writing $j: $!" unless $fh->print("$j\n") and $fh->flush(); my $line = $fh->getline(); die "Child $i: Error while reading: " . $fh->error() . " ($!)" unless defined($line); my $num = IsNum($line); die "Child $i: Cannot parse result: $line" unless defined($num); die "Child $i: Expected " . ( $j * 2 ) . ", got $num" unless ( $num == $j * 2 ); } sub MyChild { my $i = shift; eval { my $fh = IO::Socket::INET->new( 'PeerAddr' => '127.0.0.1', 'PeerPort' => $port ); die "Cannot connect: $!" unless defined($fh); for ( my $j = 0; $j < 1000; $j++ ) { ReadWrite( $fh, $i, $j ); } }; if ($@) { print STDERR $@; return 0; } return 1; } my @threads; for ( my $i = 0; $i < 10; $i++ ) { #print "Spawning child $i.\n"; my $tid = threads->new( \&MyChild, $i ); if ( !$tid ) { print STDERR "Failed to create new thread: $!\n"; exit 1; } push( @threads, $tid ); } eval { alarm 1; alarm 0 }; alarm 120 unless $@; for ( my $i = 1; $i <= 10; $i++ ) { my $tid = shift @threads; if ( $tid->join() ) { print "ok $i\n"; } else { print "not ok $i\n"; } } END { if ($handle) { print "Terminating server.\n"; $handle->Terminate(); undef $handle; } unlink "ndtest.prt"; } Net-Daemon-0.49/t/ithread.t0000644000000000000000000000314113732510212014136 0ustar rootroot# -*- perl -*- # # $Id: thread.t,v 1.2 1999/08/12 14:28:59 joe Exp $ # require 5.004; use strict; use Config; use IO::Socket (); use Net::Daemon::Test (); my $numTests = 5; # Check whether threads are available, otherwise skip this test. if ( !$Config{useithreads} ) { print "1..0 # SKIP This test requires a perl with working ithreads.\n"; exit 0; } require threads; my ( $handle, $port ) = Net::Daemon::Test->Child( $numTests, $^X, 't/server', '--timeout', 20, '--mode=ithreads' ); print "Making first connection to port $port...\n"; my $fh = IO::Socket::INET->new( 'PeerAddr' => '127.0.0.1', 'PeerPort' => $port ); printf( "%s 1\n", $fh ? "ok" : "not ok" ); printf( "%s 2\n", $fh->close() ? "ok" : "not ok" ); print "Making second connection to port $port...\n"; $fh = IO::Socket::INET->new( 'PeerAddr' => '127.0.0.1', 'PeerPort' => $port ); printf( "%s 3\n", $fh ? "ok" : "not ok" ); eval { for ( my $i = 0; $i < 20; $i++ ) { if ( !$fh->print("$i\n") || !$fh->flush() ) { die "Error while writing $i: " . $fh->error() . " ($!)"; } my $line = $fh->getline(); die "Error while reading $i: " . $fh->error() . " ($!)" unless defined($line); die "Result error: Expected " . ( $i * 2 ) . ", got $line" unless ( $line =~ /(\d+)/ && $1 == $i * 2 ); } }; if ($@) { print STDERR "$@\n"; print "not ok 4\n"; } else { print "ok 4\n"; } printf( "%s 5\n", $fh->close() ? "ok" : "not ok" ); END { if ($handle) { $handle->Terminate() } if ( -f "ndtest.prt" ) { unlink "ndtest.prt" } } Net-Daemon-0.49/t/single.t0000644000000000000000000000274313732471340014016 0ustar rootroot# -*- perl -*- # # $Id: single.t,v 1.2 1999/08/12 14:28:59 joe Exp $ # require 5.004; use strict; use IO::Socket (); use Config (); use Net::Daemon::Test (); my $numTests = 5; my ( $handle, $port ); if (@ARGV) { $port = shift @ARGV; } else { ( $handle, $port ) = Net::Daemon::Test->Child( $numTests, $^X, '-Iblib/lib', '-Iblib/arch', 't/server', '--mode=single', '--timeout', 60 ); } print "Making first connection to port $port...\n"; my $fh = IO::Socket::INET->new( 'PeerAddr' => '127.0.0.1', 'PeerPort' => $port ); printf( "%s 1\n", $fh ? "ok" : "not ok" ); printf( "%s 2\n", $fh->close() ? "ok" : "not ok" ); print "Making second connection to port $port...\n"; $fh = IO::Socket::INET->new( 'PeerAddr' => '127.0.0.1', 'PeerPort' => $port ); printf( "%s 3\n", $fh ? "ok" : "not ok" ); my ($ok) = $fh ? 1 : 0; for ( my $i = 0; $ok && $i < 20; $i++ ) { print "Writing number: $i\n"; if ( !$fh->print("$i\n") || !$fh->flush() ) { $ok = 0; last; } print "Written.\n"; my ($line) = $fh->getline(); print "line = ", ( defined($line) ? $line : "undef" ), "\n"; if ( !defined($line) ) { $ok = 0; last; } if ( $line !~ /(\d+)/ || $1 != $i * 2 ) { $ok = 0; last; } } printf( "%s 4\n", $ok ? "ok" : "not ok" ); printf( "%s 5\n", $fh->close() ? "ok" : "not ok" ); END { if ($handle) { $handle->Terminate() } if ( -f "ndtest.prt" ) { unlink "ndtest.prt" } } Net-Daemon-0.49/t/loop-child.t0000644000000000000000000000343513732471340014566 0ustar rootroot# -*- perl -*- # # $Id: loop-child.t,v 1.1 1999/08/12 14:28:59 joe Exp $ # require 5.004; use strict; use IO::Socket (); use Config (); use Net::Daemon::Test (); my $numTests = 6; my ( $handle, $port ); if (@ARGV) { $port = shift; } else { ( $handle, $port ) = Net::Daemon::Test->Child( $numTests, $^X, '-Iblib/lib', '-Iblib/arch', 't/server', '--mode=single', '--loop-timeout=2', '--loop-child', '--debug', '--timeout', 60 ); } print "Making first connection to port $port...\n"; my $fh = IO::Socket::INET->new( 'PeerAddr' => '127.0.0.1', 'PeerPort' => $port ); printf( "%s 1\n", $fh ? "ok" : "not ok" ); printf( "%s 2\n", $fh->close() ? "ok" : "not ok" ); print "Making second connection to port $port...\n"; $fh = IO::Socket::INET->new( 'PeerAddr' => '127.0.0.1', 'PeerPort' => $port ); printf( "%s 3\n", $fh ? "ok" : "not ok" ); my ($ok) = $fh ? 1 : 0; for ( my $i = 0; $ok && $i < 20; $i++ ) { print "Writing number: $i\n"; if ( !$fh->print("$i\n") || !$fh->flush() ) { $ok = 0; last; } print "Written.\n"; my ($line) = $fh->getline(); print "line = ", ( defined($line) ? $line : "undef" ), "\n"; if ( !defined($line) ) { $ok = 0; last; } if ( $line !~ /(\d+)/ || $1 != $i * 2 ) { $ok = 0; last; } } printf( "%s 4\n", $ok ? "ok" : "not ok" ); printf( "%s 5\n", $fh->close() ? "ok" : "not ok" ); $ok = 0; for ( my $i = 0; $i < 30; $i++ ) { my $num; if ( open( CNT, " ) and $num eq "10\n" ) { $ok = 1; last; } sleep 1; } printf( "%s 6\n", $ok ? "ok" : "not ok" ); END { if ($handle) { $handle->Terminate() } unlink "ndtest.prt", "ndtest.cnt"; } Net-Daemon-0.49/t/loop.t0000644000000000000000000000320713732471340013502 0ustar rootroot# -*- perl -*- # # $Id: loop.t,v 1.2 1999/08/12 14:28:59 joe Exp $ # require 5.004; use strict; use IO::Socket (); use Config (); use Net::Daemon::Test (); my $numTests = 6; my ( $handle, $port ) = Net::Daemon::Test->Child( $numTests, $^X, '-Iblib/lib', '-Iblib/arch', 't/server', '--mode=single', '--loop-timeout=2', '--timeout', 60 ); print "Making first connection to port $port...\n"; my $fh = IO::Socket::INET->new( 'PeerAddr' => '127.0.0.1', 'PeerPort' => $port ); printf( "%s 1\n", $fh ? "ok" : "not ok" ); printf( "%s 2\n", $fh->close() ? "ok" : "not ok" ); print "Making second connection to port $port...\n"; $fh = IO::Socket::INET->new( 'PeerAddr' => '127.0.0.1', 'PeerPort' => $port ); printf( "%s 3\n", $fh ? "ok" : "not ok" ); my ($ok) = $fh ? 1 : 0; for ( my $i = 0; $ok && $i < 20; $i++ ) { print "Writing number: $i\n"; if ( !$fh->print("$i\n") || !$fh->flush() ) { $ok = 0; last; } print "Written.\n"; my ($line) = $fh->getline(); print "line = ", ( defined($line) ? $line : "undef" ), "\n"; if ( !defined($line) ) { $ok = 0; last; } if ( $line !~ /(\d+)/ || $1 != $i * 2 ) { $ok = 0; last; } } printf( "%s 4\n", $ok ? "ok" : "not ok" ); printf( "%s 5\n", $fh->close() ? "ok" : "not ok" ); $ok = 0; for ( my $i = 0; $i < 30; $i++ ) { my $num; if ( open( CNT, " ) and $num eq "10\n" ) { $ok = 1; last; } sleep 1; } printf( "%s 6\n", $ok ? "ok" : "not ok" ); END { if ($handle) { $handle->Terminate() } unlink "ndtest.prt", "ndtest.cnt"; } Net-Daemon-0.49/t/server0000644000000000000000000000460613732475004013602 0ustar rootroot# -*- perl -*- # # $Id: server,v 1.2 1999/08/12 14:28:59 joe Exp $ # # This example implements a very simple server, let's call it # multiplier. When a client connects, it waits for decimal numbers # as input. These numbers are written back, multiplied by 2. # require 5.004; use strict; use lib qw(blib/arch blib/lib); $| = 1; use Net::Daemon::Test (); use IO::Socket (); package Multiplier; our $VERSION = '0.01'; our @ISA = qw(Net::Daemon::Test); sub Version ($) { return "Multiplier - A simple network calculator; 1998, Jochen Wiedmann"; } sub GetLine { my $sock = shift; $sock->getline(); } sub Print { my $sock = shift; $sock->print(@_) && $sock->flush(); } sub Loop { my $self = shift; if ( $self->{'loop-timeout'} ) { my $count = $self->{'loop-count'} || 0; if ( ( $self->{'loop-count'} = ++$count ) == 10 ) { $self->Done(); open( COUNT, ">ndtest.cnt" ); print COUNT "10\n"; close(COUNT); } } } sub Run ($) { my $self = shift; sleep 1 if $self->{'mode'} eq "fork"; # Waiting one second sometimes helps the parent to catch # children nicely, if they die immediately my ( $line, $sock ); $sock = $self->{'socket'}; eval { while (1) { if ( !defined( $line = GetLine($sock) ) ) { if ( $sock->error() ) { die "Client connection error " . $sock->error() . " ($!)"; } last; } my $num; { my $lock = lock($Net::Daemon::RegExpLock) if ( $self->{'mode'} eq 'threads' ); if ( $line =~ /(\d+)/ ) { $num = $1; } } if ( defined($num) ) { if ( !Print( $sock, $num * 2, "\n" ) ) { die "Client connection error " . $sock->error() . " ($!) while writing."; } } else { die "Server cannot parse input: $line"; } } }; if ($@) { print STDERR "$@\n"; $self->Error($@); } $sock->close(); } package main; my $server = Multiplier->new( { 'pidfile' => 'none' }, \@ARGV ); eval { $server->Bind() }; print STDERR "Unexpected return from Bind().\n" if ( !$server->Done() ); print STDERR "Server died: $@\n" if $@; Net-Daemon-0.49/t/forkm.t0000644000000000000000000001124613732510617013652 0ustar rootroot# -*- perl -*- # require 5.004; use strict; use IO::Socket (); use Config (); use Net::Daemon::Test (); use Fcntl (); use Config (); use POSIX qw/WNOHANG/; my $debug = 0; my $dh; if ($debug) { $dh = Symbol::gensym(); open( $dh, ">", "forkm.log" ) or die "Failed to open forkm.log: $!"; } sub DEBUG { my $msg = shift; print $dh "$$: $msg\n" if $dh; } DEBUG("Start"); my $ok; eval { if ( $^O ne "MSWin32" ) { my $pid = fork(); if ( defined($pid) ) { if ( !$pid ) { exit 0; } # Child } wait; $ok = 1; } }; if ( !$ok ) { DEBUG("!ok"); print "1..0 # SKIP This test requires a system with working forks.\n"; exit; } $| = 1; $^W = 1; my ( $handle, $port ); if (@ARGV) { $port = shift @ARGV; } else { ( $handle, $port ) = Net::Daemon::Test->Child( 10, $^X, '-Iblib/lib', '-Iblib/arch', 't/server', '--mode=fork', 'logfile=stderr', 'debug' ); } sub IsNum { my $str = shift; ( defined($str) && $str =~ /(\d+)/ ) ? $1 : undef; } sub ReadWrite { my $fh = shift; my $i = shift; my $j = shift; DEBUG("ReadWrite: -> fh=$fh, i=$i, j=$j"); if ( !$fh->print("$j\n") || !$fh->flush() ) { die "Child $i: Error while writing $j: " . $fh->error() . " ($!)"; } my $line = $fh->getline(); DEBUG("ReadWrite: line=$line"); die "Child $i: Error while reading: " . $fh->error() . " ($!)" unless defined($line); my $num; die "Child $i: Cannot parse result: $line" unless defined( $num = IsNum($line) ); die "Child $i: Expected " . ( $j * 2 ) . ", got $num" unless $j * 2 == $num; DEBUG("ReadWrite: <-"); } sub MyChild { my $i = shift; DEBUG("MyChild: -> $i"); eval { my $fh = IO::Socket::INET->new( 'PeerAddr' => '127.0.0.1', 'PeerPort' => $port ); if ( !$fh ) { DEBUG("MyChild: Cannot connect: $!"); die "Cannot connect: $!"; } for ( my $j = 0; $j < 1000; $j++ ) { ReadWrite( $fh, $i, $j ); } }; if ($@) { print STDERR "Client: Error $@\n"; DEBUG("MyChild: Client: Error $@"); return 0; } DEBUG("MyChild: <-"); return 1; } sub ShowResults { DEBUG("ShowResults: ->"); my @results; for ( my $i = 1; $i <= 10; $i++ ) { $results[ $i - 1 ] = "not ok $i\n"; } if ( open( LOG, " ) ) { if ( $line =~ /(\d+)/ ) { $results[ $1 - 1 ] = $line; } } } for ( my $i = 1; $i <= 10; $i++ ) { print $results[ $i - 1 ]; } DEBUG("ShowResults: <-"); exit 0; } my %childs; sub CatchChild { DEBUG("CatchChild: ->"); for ( ;; ) { my $pid = waitpid -1, WNOHANG; last if $pid <= 0; if ( $pid > 0 ) { DEBUG("CatchChild: $pid"); if ( exists $childs{$pid} ) { delete $childs{$pid}; if ( keys(%childs) == 0 ) { # We ae done when the last of our ten childs are gone. ShowResults(); last; } } } } $SIG{'CHLD'} = \&CatchChild; DEBUG("CatchChild: <-"); } $SIG{'CHLD'} = \&CatchChild; # Spawn 10 childs, each of them running a series of test unlink "log"; DEBUG("Spawning childs"); for ( my $i = 0; $i < 10; $i++ ) { if ( defined( my $pid = fork() ) ) { if ($pid) { # This is the parent $childs{$pid} = $i; } else { DEBUG("Child starting"); # This is the child undef $handle; %childs = (); my $result = MyChild($i); my $fh = Symbol::gensym(); if ( !open( $fh, ">>log" ) || !flock( $fh, 2 ) || !seek( $fh, 0, 2 ) || !( print $fh ( ( $result ? "ok " : "not ok " ), ( $i + 1 ), "\n" ) ) || !close($fh) ) { print STDERR "Error while writing log file: $!\n"; exit 1; } exit 0; } } else { print STDERR "Failed to create new child: $!\n"; exit 1; } } my $secs = 120; while ( $secs > 0 ) { $secs -= sleep $secs; } END { DEBUG( "END: -> handle=" . ( defined($handle) ? $handle : "undef" ) ); if ($handle) { $handle->Terminate(); undef $handle; } while ( my ( $var, $val ) = each %childs ) { kill 'TERM', $var; } %childs = (); unlink "ndtest.prt"; DEBUG("END: <-"); exit 0; } Net-Daemon-0.49/lib/0000755000000000000000000000000013733426140012644 5ustar rootrootNet-Daemon-0.49/lib/Net/0000755000000000000000000000000013733426140013372 5ustar rootrootNet-Daemon-0.49/lib/Net/Daemon.pm0000644000000000000000000011744713733423632015154 0ustar rootroot############################################################################ # # Net::Daemon - Base class for implementing TCP/IP daemons # # Copyright (C) 1998, Jochen Wiedmann # Am Eisteich 9 # 72555 Metzingen # Germany # # Phone: +49 7123 14887 # Email: joe@ispsoft.de # # All rights reserved. # # You may distribute this package under the terms of either the GNU # General Public License or the Artistic License, as specified in the # Perl README file. # ############################################################################ package Net::Daemon; use strict; use warnings; use Config; use Getopt::Long (); use Symbol (); use IO::Socket (); use Net::Daemon::Log (); use POSIX (); use File::Spec (); our $VERSION = '0.49'; our @ISA = qw(Net::Daemon::Log); our $RegExpLock = 1; # Dummy share() in case we're >= 5.10. If we are, require/import of # threads::shared will replace it appropriately. # But ONLY if we are built with threads and forks has not already been loaded. my $use_ithreads = ( $^V ge v5.10.0 && $Config{'useithreads'} && !$INC{'forks.pm'} ) ? 1 : 0; if ($use_ithreads) { eval { require threads; }; eval { require threads::shared; }; threads::shared::share( $RegExpLock ) if $forks::threads; # Assuming this isn't threads masquerading as forks. } our $exit; ############################################################################ # # Name: Options (Class method) # # Purpose: Returns a hash ref of command line options # # Inputs: $class - This class # # Result: Options array; any option is represented by a hash ref; # used keys are 'template', a string suitable for describing # the option to Getopt::Long::GetOptions and 'description', # a string for the Usage message # ############################################################################ sub Options ($) { { 'catchint' => { 'template' => 'catchint!', 'description' => '--nocatchint ' . "Try to catch interrupts when calling system\n" . ' ' . 'functions like bind(), recv()), ...' }, 'childs' => { 'template' => 'childs=i', 'description' => '--childs ' . 'Set number of preforked childs, implies mode=single.' }, 'chroot' => { 'template' => 'chroot=s', 'description' => '--chroot ' . 'Change rootdir to given after binding to port.' }, 'configfile' => { 'template' => 'configfile=s', 'description' => '--configfile ' . 'Read options from config file .' }, 'debug' => { 'template' => 'debug', 'description' => '--debug ' . 'Turn debugging mode on' }, 'facility' => { 'template' => 'facility=s', 'description' => '--facility ' . 'Syslog facility; defaults to \'daemon\'' }, 'group' => { 'template' => 'group=s', 'description' => '--group ' . 'Change gid to given group after binding to port.' }, 'help' => { 'template' => 'help', 'description' => '--help ' . 'Print this help message' }, 'localaddr' => { 'template' => 'localaddr=s', 'description' => '--localaddr ' . 'IP number to bind to; defaults to INADDR_ANY' }, 'localpath' => { 'template' => 'localpath=s', 'description' => '--localpath ' . 'UNIX socket domain path to bind to' }, 'localport' => { 'template' => 'localport=s', 'description' => '--localport ' . 'Port number to bind to' }, 'logfile' => { 'template' => 'logfile=s', 'description' => '--logfile ' . 'Force logging to ' }, 'loop-child' => { 'template' => 'loop-child', 'description' => '--loop-child ' . 'Create a child process for loops' }, 'loop-timeout' => { 'template' => 'loop-timeout=f', 'description' => '--loop-timeout ' . 'Looping mode, seconds per loop' }, 'mode' => { 'template' => 'mode=s', 'description' => '--mode ' . 'Operation mode (threads, fork or single)' }, 'pidfile' => { 'template' => 'pidfile=s', 'description' => '--pidfile ' . 'Use as PID file' }, 'proto' => { 'template' => 'proto=s', 'description' => '--proto ' . 'transport layer protocol: tcp (default) or unix' }, 'user' => { 'template' => 'user=s', 'description' => '--user ' . 'Change uid to given user after binding to port.' }, 'version' => { 'template' => 'version', 'description' => '--version ' . 'Print version number and exit' } } } ############################################################################ # # Name: Version (Class method) # # Purpose: Returns version string # # Inputs: $class - This class # # Result: Version string; suitable for printed by "--version" # ############################################################################ sub Version ($) { "Net::Daemon server, Copyright (C) 1998, Jochen Wiedmann"; } ############################################################################ # # Name: Usage (Class method) # # Purpose: Prints usage message # # Inputs: $class - This class # # Result: Nothing; aborts with error status # ############################################################################ sub Usage ($) { my ($class) = shift; my ($options) = $class->Options(); my (@options) = sort ( keys %$options ); print STDERR "Usage: $0 \n\nPossible options are:\n\n"; my ($key); foreach $key ( sort ( keys %$options ) ) { my ($o) = $options->{$key}; print STDERR " ", $o->{'description'}, "\n" if $o->{'description'}; } print STDERR "\n", $class->Version(), "\n"; exit(1); } ############################################################################ # # Name: ReadConfigFile (Instance method) # # Purpose: Reads the config file. # # Inputs: $self - Instance # $file - config file name # $options - Hash of command line options; these are not # really for being processed by this method. We pass # it just in case. The new() method will process them # at a later time. # $args - Array ref of other command line options. # ############################################################################ sub ReadConfigFile { my ( $self, $file, $options, $args ) = @_; if ( !-f $file ) { $self->Fatal("No such config file: $file"); } my $copts = do File::Spec->rel2abs($file); if ($@) { $self->Fatal("Error while processing config file $file: $@"); } if ( !$copts || ref($copts) ne 'HASH' ) { $self->Fatal("Config file $file did not return a hash ref."); } # Override current configuration with config file options. while ( my ( $var, $val ) = each %$copts ) { $self->{$var} = $val; } } ############################################################################ # # Name: new (Class method) # # Purpose: Constructor # # Inputs: $class - This class # $attr - Hash ref of attributes # $args - Array ref of command line arguments # # Result: Server object for success, error message otherwise # ############################################################################ sub new ($$;$) { my ( $class, $attr, $args ) = @_; my ($self) = $attr ? \%$attr : {}; bless( $self, ( ref($class) || $class ) ); my $options = ( $self->{'options'} ||= {} ); $self->{'args'} ||= []; if ($args) { my @optList = map { $_->{'template'} } values( %{ $class->Options() } ); local @ARGV = @$args; if ( !Getopt::Long::GetOptions( $options, @optList ) ) { $self->Usage(); } @{ $self->{'args'} } = @ARGV; if ( $options->{'help'} ) { $self->Usage(); } if ( $options->{'version'} ) { print STDERR $self->Version(), "\n"; exit 1; } } my $file = $options->{'configfile'} || $self->{'configfile'}; if ($file) { $self->ReadConfigFile( $file, $options, $args ); } while ( my ( $var, $val ) = each %$options ) { $self->{$var} = $val; } if ( $self->{'childs'} ) { $self->{'mode'} = 'single'; } elsif ( !defined( $self->{'mode'} ) ) { if ( eval { require threads } ) { $self->{'mode'} = 'ithreads'; } else { my $fork = 0; if ( $^O ne "MSWin32" ) { my $pid = eval { fork() }; if ( defined($pid) ) { if ( !$pid ) { exit; } # Child $fork = 1; wait; } } if ($fork) { $self->{'mode'} = 'fork'; } else { $self->{'mode'} = 'single'; } } } if ( $self->{'mode'} eq 'ithreads' ) { no warnings 'redefine'; require threads; use warnings 'redefine'; } elsif ( $self->{'mode'} eq 'fork' ) { # Initialize forking mode ... } elsif ( $self->{'mode'} eq 'single' ) { # Initialize single mode ... } else { $self->Fatal("Unknown operation mode: $self->{'mode'}"); } $self->{'catchint'} = 1 unless exists( $self->{'catchint'} ); $self->Debug("Server starting in operation mode $self->{'mode'}"); if ( $self->{'childs'} ) { $self->Debug("Preforking $self->{'childs'} child processes ..."); } $self; } sub Clone ($$) { my ( $proto, $client ) = @_; my $self = {%$proto}; $self->{'socket'} = $client; $self->{'parent'} = $proto; bless( $self, ref($proto) ); $self; } ############################################################################ # # Name: Accept (Instance method) # # Purpose: Called for authentication purposes # # Inputs: $self - Server instance # # Result: TRUE, if the client has successfully authorized, FALSE # otherwise. # ############################################################################ sub Accept ($) { my $self = shift; my $socket = $self->{'socket'}; my $clients = $self->{'clients'}; my $from = $self->{'proto'} eq 'unix' ? "Unix socket" : sprintf( "%s, port %s", $socket->peerhost(), $socket->peerport() ); # Host based authorization if ( $self->{'clients'} ) { my ( $name, $aliases, $addrtype, $length, @addrs ); if ( $self->{'proto'} eq 'unix' ) { ( $name, $aliases, $addrtype, $length, @addrs ) = ( 'localhost', '', Socket::AF_INET(), length( Socket::IN_ADDR_ANY() ), Socket::inet_aton('127.0.0.1') ); } else { ( $name, $aliases, $addrtype, $length, @addrs ) = gethostbyaddr( $socket->peeraddr(), Socket::AF_INET() ); } my @patterns = @addrs ? map { Socket::inet_ntoa($_) } @addrs : $socket->peerhost(); push( @patterns, $name ) if ($name); push( @patterns, split( / /, $aliases ) ) if $aliases; my $found; OUTER: foreach my $client (@$clients) { if ( !$client->{'mask'} ) { $found = $client; last; } my $masks = ref( $client->{'mask'} ) ? $client->{'mask'} : [ $client->{'mask'} ]; # # Regular expressions aren't thread safe, as of # 5.00502 :-( # my $lock; $lock = lock($RegExpLock) if ( $self->{'mode'} eq 'threads' ); foreach my $mask (@$masks) { foreach my $alias (@patterns) { if ( $alias =~ /$mask/ ) { $found = $client; last OUTER; } } } } if ( !$found || !$found->{'accept'} ) { $self->Error("Access not permitted from $from"); return 0; } $self->{'client'} = $found; } $self->Debug("Accepting client from $from"); 1; } ############################################################################ # # Name: Run (Instance method) # # Purpose: Does the real work # # Inputs: $self - Server instance # # Result: Nothing; returning will make the connection to be closed # ############################################################################ sub Run ($) { } ############################################################################ # # Name: Done (Instance method) # # Purpose: Called by the server before doing an accept(); a TRUE # value makes the server terminate. # # Inputs: $self - Server instance # # Result: TRUE or FALSE # # Bugs: Doesn't work in forking mode. # ############################################################################ sub Done ($;$) { my $self = shift; $self->{'done'} = shift if @_; $self->{'done'}; } ############################################################################ # # Name: Loop (Instance method) # # Purpose: If $self->{'loop-timeout'} option is set, then this method # will be called every "loop-timeout" seconds. # # Inputs: $self - Server instance # # Result: Nothing; aborts in case of trouble. Note, that this is *not* # trapped and forces the server to exit. # ############################################################################ sub Loop { } ############################################################################ # # Name: ChildFunc (Instance method) # # Purpose: If possible, spawn a child process which calls a given # method. In server mode single the method is called # directly. # # Inputs: $self - Instance # $method - Method name # @args - Method arguments # # Returns: Nothing; aborts in case of problems. # ############################################################################ sub ChildFunc { my ( $self, $method, @args ) = @_; if ( $self->{'mode'} eq 'single' ) { $self->$method(@args); } elsif ( $self->{'mode'} eq 'ithreads' ) { my $startfunc = sub { my $self = shift; my $method = shift; $self->$method(@_); }; threads->new( $startfunc, $self, $method, @args ) or die "Failed to create a new thread: $!"; } else { my $pid = fork(); die "Cannot fork: $!" unless defined $pid; return if $pid; # Parent $self->$method(@args); # Child exit(0); } } ############################################################################ # # Name: Bind (Instance method) # # Purpose: Binds to a port; if successfull, it never returns. Instead # it accepts connections. For any connection a new thread is # created and the Accept method is executed. # # Inputs: $self - Server instance # # Result: Error message in case of failure # ############################################################################ sub HandleChild { my $self = shift; $self->Debug("New child starting ($self)."); eval { if ( !$self->Accept() ) { $self->Error('Refusing client'); } else { $self->Debug('Accepting client'); $self->Run(); } }; $self->Error("Child died: $@") if $@; $self->Debug("Child terminating."); $self->Close(); } sub SigChildHandler { my $self = shift; my $ref = shift; return 'IGNORE' if $self->{'mode'} eq 'fork' || $self->{'childs'}; return undef; # Don't care for childs. } sub Bind ($) { my $self = shift; my $fh; my $child_pid; my $reaper = $self->SigChildHandler( \$child_pid ); $SIG{'CHLD'} = $reaper if $reaper; if ( !$self->{'socket'} ) { $self->{'proto'} ||= ( $self->{'localpath'} ) ? 'unix' : 'tcp'; if ( $self->{'proto'} eq 'unix' ) { my $path = $self->{'localpath'} or $self->Fatal('Missing option: localpath'); unlink $path; $self->Fatal("Can't remove stale Unix socket ($path): $!") if -e $path; my $old_umask = umask 0; $self->{'socket'} = IO::Socket::UNIX->new( 'Local' => $path, 'Listen' => $self->{'listen'} || 10 ) or $self->Fatal("Cannot create Unix socket $path: $!"); umask $old_umask; } else { $self->{'socket'} = IO::Socket::INET->new( 'LocalAddr' => $self->{'localaddr'}, 'LocalPort' => $self->{'localport'}, 'Proto' => $self->{'proto'} || 'tcp', 'Listen' => $self->{'listen'} || 10, 'Reuse' => 1 ) or $self->Fatal("Cannot create socket: $!"); } } $self->Log( 'notice', "Server starting" ); if ( ( my $pidfile = ( $self->{'pidfile'} || '' ) ) ne 'none' ) { $self->Debug("Writing PID to $pidfile"); my $fh = Symbol::gensym(); $self->Fatal("Cannot write to $pidfile: $!") unless ( open( OUT, ">$pidfile" ) and ( print OUT "$$\n" ) and close(OUT) ); } if ( my $dir = $self->{'chroot'} ) { $self->Debug("Changing root directory to $dir"); if ( !chroot($dir) ) { $self->Fatal("Cannot change root directory to $dir: $!"); } } if ( my $group = $self->{'group'} ) { $self->Debug("Changing GID to $group"); my $gid; if ( $group !~ /^\d+$/ ) { if ( defined( my $gid = getgrnam($group) ) ) { $group = $gid; } else { $self->Fatal("Cannot determine gid of $group: $!"); } } $( = ( $) = $group ); } if ( my $user = $self->{'user'} ) { $self->Debug("Changing UID to $user"); my $uid; if ( $user !~ /^\d+$/ ) { if ( defined( my $uid = getpwnam($user) ) ) { $user = $uid; } else { $self->Fatal("Cannot determine uid of $user: $!"); } } $< = ( $> = $user ); } if ( $self->{'childs'} ) { my $pid; my $childpids = $self->{'childpids'} = {}; for ( my $n = 0; $n < $self->{'childs'}; $n++ ) { $pid = fork(); die "Cannot fork: $!" unless defined $pid; if ( !$pid ) { #Child $self->{'mode'} = 'single'; last; } # Parent $childpids->{$pid} = 1; } if ($pid) { # Parent waits for childs in a loop, then exits ... # We could also terminate the parent process, but # if the parent is still running we can kill the # whole group by killing the childs. my $childpid; $exit = 0; $SIG{'TERM'} = sub { die }; $SIG{'INT'} = sub { die }; eval { do { $childpid = wait; delete $childpids->{$childpid}; $self->Debug("Child $childpid has exited"); } until ( $childpid <= 0 || $exit || keys(%$childpids) == 0 ); }; my @pids = keys %{ $self->{'childpids'} }; if (@pids) { $self->Debug( "kill TERM childs: " . join( ",", @pids ) ); kill 'TERM', @pids if @pids; # send a TERM to all childs } exit(0); } } my $time = $self->{'loop-timeout'} ? ( time() + $self->{'loop-timeout'} ) : 0; my $client; while ( !$self->Done() ) { undef $child_pid; my $rin = ''; vec( $rin, $self->{'socket'}->fileno(), 1 ) = 1; my ( $rout, $t ); if ($time) { my $tm = time(); $t = $time - $tm; $t = 0 if $t < 0; $self->Debug("Loop time: time=$time now=$tm, t=$t"); } my ($nfound) = select( $rout = $rin, undef, undef, $t ); if ( $nfound < 0 ) { if ( !$child_pid and ( $! != POSIX::EINTR() or !$self->{'catchint'} ) ) { $self->Fatal( "%s server failed to select(): %s", ref($self), $self->{'socket'}->error() || $! ); } } elsif ($nfound) { my $client = $self->{'socket'}->accept(); if ( !$client ) { if ( !$child_pid and ( $! != POSIX::EINTR() or !$self->{'catchint'} ) ) { $self->Error( "%s server failed to accept: %s", ref($self), $self->{'socket'}->error() || $! ); } } else { if ( $self->{'debug'} ) { my $from = $self->{'proto'} eq 'unix' ? 'Unix socket' : sprintf( '%s, port %s', # SE 19990917: display client data!! $client->peerhost(), $client->peerport() ); $self->Debug("Connection from $from"); } my $sth = $self->Clone($client); $self->Debug("Child clone: $sth\n"); $sth->ChildFunc('HandleChild') if $sth; if ( $self->{'mode'} eq 'fork' ) { $self->ServClose($client); } } } if ($time) { my $t = time(); if ( $t >= $time ) { $time = $t; if ( $self->{'loop-child'} ) { $self->ChildFunc('Loop'); } else { $self->Loop(); } $time += $self->{'loop-timeout'}; } } } $self->Log( 'notice', "%s server terminating", ref($self) ); } sub Close { my $socket = shift->{'socket'}; $socket->close() if $socket; } sub ServClose { my $self = shift; my $socket = shift; $socket->close() if $socket; } 1; __END__ =head1 NAME Net::Daemon - Perl extension for portable daemons =head1 SYNOPSIS # Create a subclass of Net::Daemon require Net::Daemon; package MyDaemon; @MyDaemon::ISA = qw(Net::Daemon); sub Run ($) { # This function does the real work; it is invoked whenever a # new connection is made. } =head1 DESCRIPTION Net::Daemon is an abstract base class for implementing portable server applications in a very simple way. The module is designed for Perl 5.005 and threads, but can work with fork() and Perl 5.004. The Net::Daemon class offers methods for the most common tasks a daemon needs: Starting up, logging, accepting clients, authorization, restricting its own environment for security and doing the true work. You only have to override those methods that aren't appropriate for you, but typically inheriting will safe you a lot of work anyways. =head2 Constructors $server = Net::Daemon->new($attr, $options); $connection = $server->Clone($socket); Two constructors are available: The B method is called upon startup and creates an object that will basically act as an anchor over the complete program. It supports command line parsing via L. Arguments of B are I<$attr>, an hash ref of attributes (see below) and I<$options> an array ref of options, typically command line arguments (for example B<\@ARGV>) that will be passed to B. The second constructor is B: It is called whenever a client connects. It receives the main server object as input and returns a new object. This new object will be passed to the methods that finally do the true work of communicating with the client. Communication occurs over the socket B<$socket>, B's argument. Possible object attributes and the corresponding command line arguments are: =over 4 =item I (B<--nocatchint>) On some systems, in particular Solaris, the functions accept(), read() and so on are not safe against interrupts by signals. For example, if the user raises a USR1 signal (as typically used to reread config files), then the function returns an error EINTR. If the I option is on (by default it is, use B<--nocatchint> to turn this off), then the package will ignore EINTR errors whereever possible. =item I (B<--chroot=dir>) (UNIX only) After doing a bind(), change root directory to the given directory by doing a chroot(). This is usefull for security operations, but it restricts programming a lot. For example, you typically have to load external Perl extensions before doing a chroot(), or you need to create hard links to Unix sockets. This is typically done in the config file, see the --configfile option. See also the --group and --user options. If you don't know chroot(), think of an FTP server where you can see a certain directory tree only after logging in. =item I An array ref with a list of clients. Clients are hash refs, the attributes I (0 for denying access and 1 for permitting) and I, a Perl regular expression for the clients IP number or its host name. See L<"Access control"> below. =item I (B<--configfile=file>) Net::Daemon supports the use of config files. These files are assumed to contain a single hash ref that overrides the arguments of the new method. However, command line arguments in turn take precedence over the config file. See the L<"Config File"> section below for details on the config file. =item I (B<--debug>) Turn debugging mode on. Mainly this asserts that logging messages of level "debug" are created. =item I (B<--facility=mode>) (UNIX only) Facility to use for L. The default is B. =item I (B<--group=gid>) After doing a bind(), change the real and effective GID to the given. This is usefull, if you want your server to bind to a privileged port (<1024), but don't want the server to execute as root. See also the --user option. GID's can be passed as group names or numeric values. =item I (B<--localaddr=ip>) By default a daemon is listening to any IP number that a machine has. This attribute allows to restrict the server to the given IP number. =item I (B<--localpath=path>) If you want to restrict your server to local services only, you'll prefer using Unix sockets, if available. In that case you can use this option for setting the path of the Unix socket being created. This option implies B<--proto=unix>. =item I (B<--localport=port>) This attribute sets the port on which the daemon is listening. It must be given somehow, as there's no default. =item I (B<--logfile=file>) By default logging messages will be written to the syslog (Unix) or to the event log (Windows NT). On other operating systems you need to specify a log file. The special value "STDERR" forces logging to stderr. =item I (B<--loop-child>) This option forces creation of a new child for loops. (See the I option.) By default the loops are serialized. =item I (B<--loop-timeout=secs>) Some servers need to take an action from time to time. For example the Net::Daemon::Spooler attempts to empty its spooling queue every 5 minutes. If this option is set to a positive value (zero being the default), then the server will call its Loop method every "loop-timeout" seconds. Don't trust too much on the precision of the interval: It depends on a number of factors, in particular the execution time of the Loop() method. The loop is implemented by using the I