NAME
Net::Daemon - Perl extension for portable daemons
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.
}
DESCRIPTION
Net::Daemon is an approach for writing daemons that are both portable and simple. It is designed for Perl 5.005 and threads, but can work with fork() and Perl 5.004.
The Net::Daemon class is an abstract class that offers methods for the most common tasks a daemon needs: Starting up, logging, accepting clients, authorization 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:
- chroot (--chroot)
-
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(). 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.
- debug (--debug)
-
Used for turning debugging mode on.
- facility (--facility)
-
Facility to use for Sys::Syslog (3) (Unix only). The default is daemon.
- forking
-
Creates a forking daemon instead of using the Thread library (Unix only). There are two good reasons for using fork(): You have no multithreaded Perl or you need to simplify porting existing applications.
- group (--group)
-
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.
- localaddr (--localaddr)
-
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.
- localport (--localport)
-
This attribute sets the port on which the daemon is listening.
- logfile (--logfile)
-
Be 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.
- options
-
Array ref of Command line options that have been passed to the server object via the new method.
- parent
-
When creating an object with Clone the original object becomes the parent of the new object. Objects created with new usually don't have a parent, thus this attribute is not set.
- pidfile (--pidfile)
-
If your daemon creates a PID file, you should use this location.
- single (--single)
-
Disables concurrent connections. In other words, the server waits for a conenction, enters the Run() method without creating a new thread or process and can accept further connections only after Run() returns. This is usefull for debugging purposes or if you have a system that neither supports threads nor fork().
- socket
-
The socket that is connected to the client; passed as $client argument to the Clone method. If the server object was created with new, this attribute can be undef, as long as the Bind method isn't called. Sockets are assumed to be IO::Socket objects.
- stderr (--stderr)
-
By default Logging is done via Sys::Syslog (3) (Unix) or Win32::EventLog (Windows NT). This attribute allows logging to be redirected to STDERR instead.
- user (--user)
-
After doing a bind(), change the real and effective UID 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 --group and the --chroot options.
- version (--version)
-
Supresses startup of the server; instead the version string will be printed and the program exits immediately.
Note that most of these attributes (facility, forking, 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 Parsing
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:
- template
-
An option template that can be passed to Getopt::Long::GetOptions.
- description
-
A description of this option, as used in Usage
The Usage method prints a list of all possible options and returns. It uses the Version method for printing program name and version.
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.
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 Handling
All methods are supposed to throw Perl exceptions in case of errors.
MULTITHREADING CONSIDERATIONS
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.
EXAMPLE
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 sucj 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($class, $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';
}
}
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;
}
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;
}
}
}
AUTHOR AND COPYRIGHT
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.