Net::Daemon(3pm)

πŸ’– NAME πŸ’–

Okay bestie, this is Net::Daemon(3pm) β€” a Perl extension for portable daemons. Yes, actual daemons, the little background server gremlins. We stan. ✨


πŸ¦‹ SYNOPSIS πŸ¦‹

Like, here's the whole vibe. You make a subclass, you write Run, you're done:

# 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 abstract base class for building portable server applications in a truly ridiculously simple way. It's designed for Perl 5.006 and ithreads, but it can work with fork() too. Versatile queen. πŸ‘‘

So basically the Net::Daemon class hands you methods for all the chores a daemon has to do:

  • starting up
  • logging
  • accepting clients
  • authorization
  • restricting its own environment for security
  • and doing the true work

You only override the methods that aren't it for you β€” but lowkey, just inheriting will save you a ton of work anyway. πŸ’…


πŸŽ€ Constructors πŸŽ€

$server = Net::Daemon->new($attr, $options);

$connection = $server->Clone($socket);

Two constructors, bestie, and they do different jobs:

The new method gets called on startup and makes an object that basically acts as an anchor over the entire program. It supports command line parsing via Getopt::Long (3). 🫢

The arguments of new are:

  • $attr β€” a hash ref of attributes (scroll down, they're all listed, I gotchu)
  • $options β€” an array ref of options, typically command line arguments (like \@ARGV) that get passed to Getopt::Long::GetOptions

The second constructor is Clone: it gets called whenever a client connects. It receives the main server object as input and returns a new object. That new object is what gets passed to the methods that finally do the true work of communicating with the client. The communication happens over the socket $socket, which is Clone's argument. 🌈

Heads up! Clone does not call new. It creates a shallow copy of the server object. If your subclass needs to initialize per-connection state, override the post_clone method instead of checking for "$self->{'parent'}" inside new. post_clone is called by Clone after the new object is created and blessed. The default implementation is a no-op. ✨

Possible object attributes and the corresponding command line arguments are:

  • catchint (--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 catchint option is on (and by default it is β€” use --nocatchint to turn this off), then the package will ignore EINTR errors wherever possible. πŸ›‘οΈ
  • chroot (--chroot=dir) β€” (UNIX only) After doing a bind(), change root directory to the given directory by doing a chroot(). This is useful 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. 🐚

  • clients β€” An array ref with a list of clients. Clients are hash refs, with the attributes accept (0 for denying access and 1 for permitting) and mask, a Perl regular expression for the client's IP number or its host name. See "Access control" below. πŸšͺ
  • configfile (--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 "Config File" section below for details on the config file. πŸ“
  • debug (--debug) β€” Turn debugging mode on. Mainly this asserts that logging messages of level "debug" are created. πŸ›
  • facility (--facility=mode) β€” (UNIX only) Facility to use for Sys::Syslog (3). The default is daemon.
  • group (--group=gid) β€” After doing a bind(), change the real and effective GID to the given. This is useful 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. πŸ‘―

  • localaddr (--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.
  • localpath (--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 --proto=unix. πŸ”Œ
  • localport (--localport=port) β€” This attribute sets the port on which the daemon is listening. It must be given somehow, as there's no default.
  • logfile (--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. πŸ“
  • loop-child (--loop-child) β€” This option forces creation of a new child for loops. (See the loop-timeout option.) By default the loops are serialized.
  • loop-timeout (--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 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. ⏰

  • mode (--mode=modename) β€” The Net::Daemon server can run in three different modes, depending on the environment.
    • If you are running Perl 5.10 or later with ithreads support on a non-Windows platform, 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 on Unix-like systems; you can force it with "--mode=ithreads".
Note: Ithreads mode is not auto-detected on Windows because Perl uses DuplicateHandle() to clone socket file descriptors into new threads, whereas Winsock requires WSADuplicateSocket(). The duplicated client sockets become corrupted, causing I/O errors. You may still pass "--mode=ithreads" explicitly, but expect failures under concurrent load. See https://github.com/cpan-authors/Net-Daemon/issues/19. πŸ’€
  • 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 Windows. 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". πŸ‘‘

  • childs β€” Use this parameter to let Net::Daemon run in prefork mode, which means it forks the number of childs processes you give with this parameter, and all child handle connections concurrently. The difference to fork mode is, that the child processes continue to run after a connection has terminated and are able to accept a new connection. This is useful for caching inside the childs process (e.g. DBI::ProxyServer connect_cached attribute).
  • 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=file) β€” (UNIX only) If this option is present, a PID file will be created at the given location.
  • proto (--proto=proto) β€” The transport layer to use, by default tcp or unix for a Unix socket. It is not yet possible to combine both. 🚫
  • 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.
  • user (--user=uid) β€” After doing a bind(), change the real and effective UID to the given. This is useful 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.

UID's can be passed as group names or numeric values. 🫢

  • 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, mode, localaddr, localport, pidfile, version) are meaningful 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. ✨

✨ Config File ✨

Okay bestie, so if the config file option is set β€” either in the command line options or in the "new" args β€” then this method gets called:

$server->ReadConfigFile($file, $options, $args)

By default the config file is expected to hold Perl source that returns a hash ref of options. Those options override the "new" args, and then they get overwritten again by the command line options sitting in the $options hash ref. Hierarchy, periodt.

A typical config file might look like this β€” we're using DBI::ProxyServer as our 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 control πŸ›‘οΈ

Net::Daemon supports a host based access control scheme, and by default access is open for anyone. Chill vibes. BUT β€” if you create an attribute $self->{'clients'}, typically in the config file, then access control is disabled by default instead. Lowkey counterintuitive but okay.

For any connection the client list gets processed, and the clients attribute is an array ref to a list of hash refs. Any of those hash refs may contain arbitrary attributes, including these:

  • mask β€” a Perl regular expression that has to match the client's IP number or its host name. The list is processed from the left to the right, and whenever a 'mask' attribute matches, then the related hash ref is chosen as client and processing the client list stops. First match wins, slay.
  • accept β€” this may be set to true or false (that's also the default when you omit the attribute), and the former means accepting the client.

πŸ“ 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). Its arguments are $level β€” a syslog level like debug, notice or err β€” plus a format string in the style of printf and the format string's arguments.

Debug and Error are shorthands for calling Log with a level of debug and err, respectively. Fatal is like Error, except it additionally throws the given message as an exception. Not just logging the drama β€” it IS the drama. πŸ’…

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 right after creating the server object $server. Bind usually never returns, except in case of errors. Iconic behaviour, honestly.

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 class's Accept method. That 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. That's it, that's the whole vibe.


🧡 MULTITHREADING CONSIDERATIONS 🧡

All methods are working with lexically scoped data and handle data only β€” the one exception being the OpenLog method, which is invoked before threading starts. So you're safe as long as you don't share handles between threads. The author strongly recommends your application behaves similarly. Respect the boundaries, bestie. 🫢

(This doesn't apply to mode 'ithreads'.)


🌸 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 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 server's output will use the given base.

# -*- perl -*-
#
# Calculator server
#
use strict;

require Net::Daemon;

package Calculator;

our $VERSION = '0.52';
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->{'options'}  &&  $self->{'options'}->{'base'}) {
        $self->{'base'} = $self->{'options'}->{'base'}
    }
    if (!$self->{'base'}) {
        $self->{'base'} = 'dec';
    }
    $self;
}

# Initialize per-connection state after Clone()
sub post_clone ($) {
    my($self) = @_;
    $self->{'base'} = $self->{'parent'}->{'base'};
}

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 PROBLEMS 😭

Most, or even any, known problems are related to the Sys::Syslog module, which is by default used for logging events under Unix. Here are some examples, quoted for you:

  • Usage: Sys::Syslog::_PATH_LOG at ... β€” this problem is treated in perl bug 20000712.003. A workaround is changing line 277 of Syslog.pm to:
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.


πŸ”— SEE ALSO πŸ”—

RPC::pServer(3), Netserver::Generic(3), Net::Daemon::Log(3), Net::Daemon::Test(3)


And that's a wrap on this one, bestie! πŸŽ€ This page came to you from perl v5.40.1, dated 2026-05-06 β€” go forth and build your little daemons, they're gonna eat. πŸ’–βœ¨

πŸ“¦ where this page comes from