|
NAMENet::Daemon - Perl extension for portable daemonsSYNOPSIS# 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. } DESCRIPTIONNet::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. Constructors$server = Net::Daemon->new($attr, $options); $connection = $server->Clone($socket); Two constructors are available: The new 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 Getopt::Long (3). Arguments of new are $attr, an hash ref of attributes (see below) and $options an array ref of options, typically command line arguments (for example \@ARGV) that will be passed to Getopt::Long::GetOptions. The second constructor is Clone: 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 $socket, Clone's argument. Possible object attributes and the corresponding command line arguments are:
Note that most of these attributes (facility, mode, localaddr, localport, pidfile, version) are meaningfull only at startup. If you set them later, they will be simply ignored. As almost all attributes have appropriate defaults, you will typically use the localport attribute only. Command Line Parsingmy $optionsAvailable = Net::Daemon->Options(); print Net::Daemon->Version(), "\n"; Net::Daemon->Usage(); The Options method returns a hash ref of possible command line options. The keys are option names, the values are again hash refs with the following keys:
The Usage method prints a list of all possible options and returns. It uses the Version method for printing program name and version. Config FileIf the config file option is set in the command line options or in the in the "new" args, then the method$server->ReadConfigFile($file, $options, $args) is invoked. By default the config file is expected to contain Perl source that returns a hash ref of options. These options override the "new" args and will in turn be overwritten by the command line options, as present in the $options hash ref. A typical config file might look as follows, we use the DBI::ProxyServer as an example: # Load external modules; this is not required unless you use # the chroot() option. #require DBD::mysql; #require DBD::CSV; { # 'chroot' => '/var/dbiproxy', 'facility' => 'daemon', 'pidfile' => '/var/dbiproxy/dbiproxy.pid', 'user' => 'nobody', 'group' => 'nobody', 'localport' => '1003', 'mode' => 'fork' # Access control 'clients' => [ # Accept the local { 'mask' => '^192\.168\.1\.\d+$', 'accept' => 1 }, # Accept myhost.company.com { 'mask' => '^myhost\.company\.com$', 'accept' => 1 } # Deny everything else { 'mask' => '.*', 'accept' => 0 } ] } Access controlThe Net::Daemon package supports a host based access control scheme. By default access is open for anyone. However, if you create an attribute $self->{'clients'}, typically in the config file, then access control is disabled by default. For any connection the client list is processed: The clients attribute is an array ref to a list of hash refs. Any of the hash refs may contain arbitrary attributes, including the following:
Event logging$server->Log($level, $format, @args); $server->Debug($format, @args); $server->Error($format, @args); $server->Fatal($format, @args); The Log method is an interface to Sys::Syslog (3) or Win32::EventLog (3). It's arguments are $level, a syslog level like debug, notice or err, a format string in the style of printf and the format strings arguments. The Debug and Error methods are shorthands for calling Log with a level of debug and err, respectively. The Fatal method is like Error, except it additionally throws the given message as exception. See Net::Daemon::Log(3) for details. Flow of control$server->Bind(); # The following inside Bind(): if ($connection->Accept()) { $connection->Run(); } else { $connection->Log('err', 'Connection refused'); } The Bind method is called by the application when the server should start. Typically this can be done right after creating the server object $server. Bind usually never returns, except in case of errors. When a client connects, the server uses Clone to derive a connection object $connection from the server object. A new thread or process is created that uses the connection object to call your classes Accept method. This method is intended for host authorization and should return either FALSE (refuse the client) or TRUE (accept the client). If the client is accepted, the Run method is called which does the true work. The connection is closed when Run returns and the corresponding thread or process exits. Error HandlingAll methods are supposed to throw Perl exceptions in case of errors.MULTITHREADING CONSIDERATIONSAll methods are working with lexically scoped data and handle data only, the exception being the OpenLog method which is invoked before threading starts. Thus you are safe as long as you don't share handles between threads. I strongly recommend that your application behaves similar. (This doesn't apply to mode 'ithreads'.)EXAMPLEAs an example we'll write a simple calculator server. After connecting to this server you may type expressions, one per line. The server evaluates the expressions and prints the result. (Note this is an example, in real life we'd never implement such a security hole. :-)For the purpose of example we add a command line option --base that takes 'hex', 'oct' or 'dec' as values: The servers output will use the given base. # -*- perl -*- # # Calculator server # require 5.004; use strict; require Net::Daemon; package Calculator; use vars qw($VERSION @ISA); $VERSION = '0.01'; @ISA = qw(Net::Daemon); # to inherit from Net::Daemon sub Version ($) { 'Calculator Example Server, 0.01'; } # Add a command line option "--base" sub Options ($) { my($self) = @_; my($options) = $self->SUPER::Options(); $options->{'base'} = { 'template' => 'base=s', 'description' => '--base ' . 'dec (default), hex or oct' }; $options; } # Treat command line option in the constructor sub new ($$;$) { my($class, $attr, $args) = @_; my($self) = $class->SUPER::new($attr, $args); if ($self->{'parent'}) { # Called via Clone() $self->{'base'} = $self->{'parent'}->{'base'}; } else { # Initial call if ($self->{'options'} && $self->{'options'}->{'base'}) { $self->{'base'} = $self->{'options'}->{'base'} } } if (!$self->{'base'}) { $self->{'base'} = 'dec'; } $self; } sub Run ($) { my($self) = @_; my($line, $sock); $sock = $self->{'socket'}; while (1) { if (!defined($line = $sock->getline())) { if ($sock->error()) { $self->Error("Client connection error %s", $sock->error()); } $sock->close(); return; } $line =~ s/\s+$//; # Remove CRLF my($result) = eval $line; my($rc); if ($self->{'base'} eq 'hex') { $rc = printf $sock ("%x\n", $result); } elsif ($self->{'base'} eq 'oct') { $rc = printf $sock ("%o\n", $result); } else { $rc = printf $sock ("%d\n", $result); } if (!$rc) { $self->Error("Client connection error %s", $sock->error()); $sock->close(); return; } } } package main; my $server = Calculator->new({'pidfile' => 'none', 'localport' => 2000}, \@ARGV); $server->Bind(); KNOWN PROBLEMSMost, or even any, known problems are related to the Sys::Syslog module which is by default used for logging events under Unix. I'll quote some examples:
AUTHOR AND COPYRIGHTNet::Daemon is 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. SEE ALSORPC::pServer(3), Netserver::Generic(3), Net::Daemon::Log(3), Net::Daemon::Test(3)
Visit the GSP FreeBSD Man Page Interface. |