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 toGetopt::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!Clonedoes not callnew. It creates a shallow copy of the server object. If your subclass needs to initialize per-connection state, override thepost_clonemethod instead of checking for"$self->{'parent'}"insidenew.post_cloneis called byCloneafter 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 functionsaccept(),read()and so on are not safe against interrupts by signals. For example, if the user raises aUSR1signal (as typically used to reread config files), then the function returns an errorEINTR. If thecatchintoption is on (and by default it is β use--nocatchintto turn this off), then the package will ignoreEINTRerrors wherever possible. π‘οΈchroot(--chroot=dir) β (UNIX only) After doing abind(), change root directory to the given directory by doing achroot(). This is useful for security operations, but it restricts programming a lot. For example, you typically have to load external Perl extensions before doing achroot(), or you need to create hard links to Unix sockets. This is typically done in the config file, see the--configfileoption. See also the--groupand--useroptions.
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 attributesaccept(0for denying access and1for permitting) andmask, a Perl regular expression for the client's IP number or its host name. See "Access control" below. πͺconfigfile(--configfile=file) βNet::Daemonsupports the use of config files. These files are assumed to contain a single hash ref that overrides the arguments of thenewmethod. 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 forSys::Syslog(3). The default isdaemon.group(--group=gid) β After doing abind(), 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--useroption.
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 theloop-timeoutoption.) By default the loops are serialized.loop-timeout(--loop-timeout=secs) β Some servers need to take an action from time to time. For example theNet::Daemon::Spoolerattempts 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 itsLoopmethod 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 theLoop()method. The loop is implemented by using theselectfunction. If you need an exact interval, you should better try to use thealarm()function and a signal handler. (And don't forget to look at thecatchintoption!) π
It is recommended to use the loop-child option in conjunction with loop-timeout. β°
mode(--mode=modename) β TheNet::Daemonserver 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".
- 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
Note: Ithreads mode is not auto-detected on Windows because Perl usesDuplicateHandle()to clone socket file descriptors into new threads, whereas Winsock requiresWSADuplicateSocket(). The duplicated client sockets become corrupted, causing I/O errors. You may still pass"--mode=ithreads"explicitly, but expect failures under concurrent load. Seehttps://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 theRun()method returns. This operation mode is useful if you have neither threads norfork(), 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 letNet::Daemonrun 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::ProxyServerconnect_cachedattribute).optionsβ Array ref of Command line options that have been passed to the server object via thenewmethod.parentβ When creating an object withClonethe original object becomes the parent of the new object. Objects created withnewusually 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 defaulttcporunixfor a Unix socket. It is not yet possible to combine both. π«socketβ The socket that is connected to the client; passed as$clientargument to theClonemethod. If the server object was created withnew, this attribute can beundef, as long as theBindmethod isn't called. Sockets are assumed to beIO::Socketobjects.user(--user=uid) β After doing abind(), 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--groupand the--chrootoptions.
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 thelocalportattribute 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 toGetopt::Long::GetOptions.descriptionβ A description of this option, as used inUsage. π¬
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 ofSyslog.pmto:
my $syslog = &_PATH_LOG() || croak "_PATH_LOG not found in syslog.ph";
π 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.
π 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
- ubuntu stonking: libnet-daemon-perl 0.52-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms