Net::Daemon(3pm) | User Contributed Perl Documentation | Net::Daemon(3pm) |
Net::Daemon - Perl extension for portable daemons
# 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. }
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.
$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:
If you don't know chroot(), think of an FTP server where you can see a certain directory tree only after logging in.
GID's can be passed as group names or numeric values.
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 select function. If you need an exact interval, you should better try to use the alarm() function and a signal handler. (And don't forget to look at the catchint option!)
It is recommended to use the loop-child option in conjunction with loop-timeout.
If you are running Perl 5.005 and did compile it for threads, then the server will create a new thread for each connection. The thread will execute the server's Run() method and then terminate. This mode is the default, you can force it with "--mode=ithreads" or "--mode=threads".
If threads are not available, but you have a working fork(), then the server will behave similar by creating a new process for each connection. This mode will be used automatically in the absence of threads or if you use the "--mode=fork" option.
Finally there's a single-connection mode: If the server has accepted a connection, he will enter the Run() method. No other connections are accepted until the Run() method returns. This operation mode is useful if you have neither threads nor fork(), for example on the Macintosh. For debugging purposes you can force this mode with "--mode=single".
When running in mode single, you can still handle multiple clients at a time by preforking multiple child processes. The number of childs is configured with the option "--childs".
UID's can be passed as group names or numeric values.
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.
my $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.
If 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 } ] }
The 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:
$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.
$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.
All methods are supposed to throw Perl exceptions in case of errors.
All 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'.)
As 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 # use strict; require Net::Daemon; package Calculator; our $VERSION = '0.01'; our @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();
Most, 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:
my $syslog = &_PATH_LOG() || croak "_PATH_LOG not found in syslog.ph";
Net::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.
RPC::pServer(3), Netserver::Generic(3), Net::Daemon::Log(3), Net::Daemon::Test(3)
2022-10-13 | perl v5.34.0 |