1Net::Daemon(3)        User Contributed Perl Documentation       Net::Daemon(3)
2
3
4

NAME

6       Net::Daemon - Perl extension for portable daemons
7

SYNOPSIS

9         # Create a subclass of Net::Daemon
10         require Net::Daemon;
11         package MyDaemon;
12         @MyDaemon::ISA = qw(Net::Daemon);
13
14         sub Run ($) {
15           # This function does the real work; it is invoked whenever a
16           # new connection is made.
17         }
18

DESCRIPTION

20       Net::Daemon is an abstract base class for implementing portable server
21       applications in a very simple way. The module is designed for Perl
22       5.005 and threads, but can work with fork() and Perl 5.004.
23
24       The Net::Daemon class offers methods for the most common tasks a daemon
25       needs: Starting up, logging, accepting clients, authorization,
26       restricting its own environment for security and doing the true work.
27       You only have to override those methods that aren't appropriate for
28       you, but typically inheriting will safe you a lot of work anyways.
29
30   Constructors
31         $server = Net::Daemon->new($attr, $options);
32
33         $connection = $server->Clone($socket);
34
35       Two constructors are available: The new method is called upon startup
36       and creates an object that will basically act as an anchor over the
37       complete program. It supports command line parsing via Getopt::Long
38       (3).
39
40       Arguments of new are $attr, an hash ref of attributes (see below) and
41       $options an array ref of options, typically command line arguments (for
42       example \@ARGV) that will be passed to Getopt::Long::GetOptions.
43
44       The second constructor is Clone: It is called whenever a client
45       connects. It receives the main server object as input and returns a new
46       object. This new object will be passed to the methods that finally do
47       the true work of communicating with the client. Communication occurs
48       over the socket $socket, Clone's argument.
49
50       Possible object attributes and the corresponding command line arguments
51       are:
52
53       catchint (--nocatchint)
54           On some systems, in particular Solaris, the functions accept(),
55           read() and so on are not safe against interrupts by signals. For
56           example, if the user raises a USR1 signal (as typically used to
57           reread config files), then the function returns an error EINTR.  If
58           the catchint option is on (by default it is, use --nocatchint to
59           turn this off), then the package will ignore EINTR errors whereever
60           possible.
61
62       chroot (--chroot=dir)
63           (UNIX only)  After doing a bind(), change root directory to the
64           given directory by doing a chroot(). This is usefull for security
65           operations, but it restricts programming a lot. For example, you
66           typically have to load external Perl extensions before doing a
67           chroot(), or you need to create hard links to Unix sockets. This is
68           typically done in the config file, see the --configfile option. See
69           also the --group and --user options.
70
71           If you don't know chroot(), think of an FTP server where you can
72           see a certain directory tree only after logging in.
73
74       clients
75           An array ref with a list of clients. Clients are hash refs, the
76           attributes accept (0 for denying access and 1 for permitting) and
77           mask, a Perl regular expression for the clients IP number or its
78           host name. See "Access control" below.
79
80       configfile (--configfile=file)
81           Net::Daemon supports the use of config files. These files are
82           assumed to contain a single hash ref that overrides the arguments
83           of the new method. However, command line arguments in turn take
84           precedence over the config file. See the "Config File" section
85           below for details on the config file.
86
87       debug (--debug)
88           Turn debugging mode on. Mainly this asserts that logging messages
89           of level "debug" are created.
90
91       facility (--facility=mode)
92           (UNIX only) Facility to use for Sys::Syslog (3). The default is
93           daemon.
94
95       group (--group=gid)
96           After doing a bind(), change the real and effective GID to the
97           given.  This is usefull, if you want your server to bind to a
98           privileged port (<1024), but don't want the server to execute as
99           root. See also the --user option.
100
101           GID's can be passed as group names or numeric values.
102
103       localaddr (--localaddr=ip)
104           By default a daemon is listening to any IP number that a machine
105           has. This attribute allows to restrict the server to the given IP
106           number.
107
108       localpath (--localpath=path)
109           If you want to restrict your server to local services only, you'll
110           prefer using Unix sockets, if available. In that case you can use
111           this option for setting the path of the Unix socket being created.
112           This option implies --proto=unix.
113
114       localport (--localport=port)
115           This attribute sets the port on which the daemon is listening. It
116           must be given somehow, as there's no default.
117
118       logfile (--logfile=file)
119           By default logging messages will be written to the syslog (Unix) or
120           to the event log (Windows NT). On other operating systems you need
121           to specify a log file. The special value "STDERR" forces logging to
122           stderr.
123
124       loop-child (--loop-child)
125           This option forces creation of a new child for loops. (See the
126           loop-timeout option.) By default the loops are serialized.
127
128       loop-timeout (--loop-timeout=secs)
129           Some servers need to take an action from time to time. For example
130           the Net::Daemon::Spooler attempts to empty its spooling queue every
131           5 minutes. If this option is set to a positive value (zero being
132           the default), then the server will call its Loop method every
133           "loop-timeout" seconds.
134
135           Don't trust too much on the precision of the interval: It depends
136           on a number of factors, in particular the execution time of the
137           Loop() method. The loop is implemented by using the select
138           function. If you need an exact interval, you should better try to
139           use the alarm() function and a signal handler. (And don't forget to
140           look at the catchint option!)
141
142           It is recommended to use the loop-child option in conjunction with
143           loop-timeout.
144
145       mode (--mode=modename)
146           The Net::Daemon server can run in three different modes, depending
147           on the environment.
148
149           If you are running Perl 5.005 and did compile it for threads, then
150           the server will create a new thread for each connection. The thread
151           will execute the server's Run() method and then terminate. This
152           mode is the default, you can force it with "--mode=ithreads" or
153           "--mode=threads".
154
155           If threads are not available, but you have a working fork(), then
156           the server will behave similar by creating a new process for each
157           connection.  This mode will be used automatically in the absence of
158           threads or if you use the "--mode=fork" option.
159
160           Finally there's a single-connection mode: If the server has
161           accepted a connection, he will enter the Run() method. No other
162           connections are accepted until the Run() method returns. This
163           operation mode is useful if you have neither threads nor fork(),
164           for example on the Macintosh.  For debugging purposes you can force
165           this mode with "--mode=single".
166
167           When running in mode single, you can still handle multiple clients
168           at a time by preforking multiple child processes. The number of
169           childs is configured with the option "--childs".
170
171       childs
172           Use this parameter to let Net::Daemon run in prefork mode, which
173           means it forks the number of childs processes you give with this
174           parameter, and all child handle connections concurrently. The
175           difference to fork mode is, that the child processes continue to
176           run after a connection has terminated and are able to accept a new
177           connection.  This is useful for caching inside the childs process
178           (e.g.  DBI::ProxyServer connect_cached attribute)
179
180       options
181           Array ref of Command line options that have been passed to the
182           server object via the new method.
183
184       parent
185           When creating an object with Clone the original object becomes the
186           parent of the new object. Objects created with new usually don't
187           have a parent, thus this attribute is not set.
188
189       pidfile (--pidfile=file)
190           (UNIX only) If this option is present, a PID file will be created
191           at the given location.
192
193       proto (--proto=proto)
194           The transport layer to use, by default tcp or unix for a Unix
195           socket. It is not yet possible to combine both.
196
197       socket
198           The socket that is connected to the client; passed as $client
199           argument to the Clone method. If the server object was created with
200           new, this attribute can be undef, as long as the Bind method isn't
201           called.  Sockets are assumed to be IO::Socket objects.
202
203       user (--user=uid)
204           After doing a bind(), change the real and effective UID to the
205           given.  This is usefull, if you want your server to bind to a
206           privileged port (<1024), but don't want the server to execute as
207           root. See also the --group and the --chroot options.
208
209           UID's can be passed as group names or numeric values.
210
211       version (--version)
212           Supresses startup of the server; instead the version string will be
213           printed and the program exits immediately.
214
215       Note that most of these attributes (facility, mode, localaddr,
216       localport, pidfile, version) are meaningfull only at startup. If you
217       set them later, they will be simply ignored. As almost all attributes
218       have appropriate defaults, you will typically use the localport
219       attribute only.
220
221   Command Line Parsing
222         my $optionsAvailable = Net::Daemon->Options();
223
224         print Net::Daemon->Version(), "\n";
225
226         Net::Daemon->Usage();
227
228       The Options method returns a hash ref of possible command line options.
229       The keys are option names, the values are again hash refs with the
230       following keys:
231
232       template
233           An option template that can be passed to Getopt::Long::GetOptions.
234
235       description
236           A description of this option, as used in Usage
237
238       The Usage method prints a list of all possible options and returns.  It
239       uses the Version method for printing program name and version.
240
241   Config File
242       If the config file option is set in the command line options or in the
243       in the "new" args, then the method
244
245         $server->ReadConfigFile($file, $options, $args)
246
247       is invoked. By default the config file is expected to contain Perl
248       source that returns a hash ref of options. These options override the
249       "new" args and will in turn be overwritten by the command line options,
250       as present in the $options hash ref.
251
252       A typical config file might look as follows, we use the
253       DBI::ProxyServer as an example:
254
255           # Load external modules; this is not required unless you use
256           # the chroot() option.
257           #require DBD::mysql;
258           #require DBD::CSV;
259
260           {
261               # 'chroot' => '/var/dbiproxy',
262               'facility' => 'daemon',
263               'pidfile' => '/var/dbiproxy/dbiproxy.pid',
264               'user' => 'nobody',
265               'group' => 'nobody',
266               'localport' => '1003',
267               'mode' => 'fork'
268
269               # Access control
270               'clients' => [
271                   # Accept the local
272                   {
273                       'mask' => '^192\.168\.1\.\d+$',
274                       'accept' => 1
275                   },
276                   # Accept myhost.company.com
277                   {
278                       'mask' => '^myhost\.company\.com$',
279                       'accept' => 1
280                   }
281                   # Deny everything else
282                   {
283                       'mask' => '.*',
284                       'accept' => 0
285                   }
286               ]
287           }
288
289   Access control
290       The Net::Daemon package supports a host based access control scheme. By
291       default access is open for anyone. However, if you create an attribute
292       $self->{'clients'}, typically in the config file, then access control
293       is disabled by default. For any connection the client list is
294       processed: The clients attribute is an array ref to a list of hash
295       refs. Any of the hash refs may contain arbitrary attributes, including
296       the following:
297
298       mask    A Perl regular expression that has to match the clients IP
299               number or its host name. The list is processed from the left to
300               the right, whenever a 'mask' attribute matches, then the
301               related hash ref is choosen as client and processing the client
302               list stops.
303
304       accept  This may be set to true or false (default when omitting the
305               attribute), the former means accepting the client.
306
307   Event logging
308         $server->Log($level, $format, @args);
309         $server->Debug($format, @args);
310         $server->Error($format, @args);
311         $server->Fatal($format, @args);
312
313       The Log method is an interface to Sys::Syslog (3) or Win32::EventLog
314       (3). It's arguments are $level, a syslog level like debug, notice or
315       err, a format string in the style of printf and the format strings
316       arguments.
317
318       The Debug and Error methods are shorthands for calling Log with a level
319       of debug and err, respectively. The Fatal method is like Error, except
320       it additionally throws the given message as exception.
321
322       See Net::Daemon::Log(3) for details.
323
324   Flow of control
325         $server->Bind();
326         # The following inside Bind():
327         if ($connection->Accept()) {
328             $connection->Run();
329         } else {
330             $connection->Log('err', 'Connection refused');
331         }
332
333       The Bind method is called by the application when the server should
334       start. Typically this can be done right after creating the server
335       object $server. Bind usually never returns, except in case of errors.
336
337       When a client connects, the server uses Clone to derive a connection
338       object $connection from the server object. A new thread or process is
339       created that uses the connection object to call your classes Accept
340       method. This method is intended for host authorization and should
341       return either FALSE (refuse the client) or TRUE (accept the client).
342
343       If the client is accepted, the Run method is called which does the true
344       work. The connection is closed when Run returns and the corresponding
345       thread or process exits.
346
347   Error Handling
348       All methods are supposed to throw Perl exceptions in case of errors.
349

MULTITHREADING CONSIDERATIONS

351       All methods are working with lexically scoped data and handle data
352       only, the exception being the OpenLog method which is invoked before
353       threading starts. Thus you are safe as long as you don't share handles
354       between threads. I strongly recommend that your application behaves
355       similar. (This doesn't apply to mode 'ithreads'.)
356

EXAMPLE

358       As an example we'll write a simple calculator server. After connecting
359       to this server you may type expressions, one per line. The server
360       evaluates the expressions and prints the result. (Note this is an
361       example, in real life we'd never implement such a security hole. :-)
362
363       For the purpose of example we add a command line option --base that
364       takes 'hex', 'oct' or 'dec' as values: The servers output will use the
365       given base.
366
367         # -*- perl -*-
368         #
369         # Calculator server
370         #
371         require 5.004;
372         use strict;
373
374         require Net::Daemon;
375
376
377         package Calculator;
378
379         use vars qw($VERSION @ISA);
380         $VERSION = '0.01';
381         @ISA = qw(Net::Daemon); # to inherit from Net::Daemon
382
383         sub Version ($) { 'Calculator Example Server, 0.01'; }
384
385         # Add a command line option "--base"
386         sub Options ($) {
387             my($self) = @_;
388             my($options) = $self->SUPER::Options();
389             $options->{'base'} = { 'template' => 'base=s',
390                                    'description' => '--base                  '
391                                           . 'dec (default), hex or oct'
392                                     };
393             $options;
394         }
395
396         # Treat command line option in the constructor
397         sub new ($$;$) {
398             my($class, $attr, $args) = @_;
399             my($self) = $class->SUPER::new($attr, $args);
400             if ($self->{'parent'}) {
401                 # Called via Clone()
402                 $self->{'base'} = $self->{'parent'}->{'base'};
403             } else {
404                 # Initial call
405                 if ($self->{'options'}  &&  $self->{'options'}->{'base'}) {
406                     $self->{'base'} = $self->{'options'}->{'base'}
407                 }
408             }
409             if (!$self->{'base'}) {
410                 $self->{'base'} = 'dec';
411             }
412             $self;
413         }
414
415         sub Run ($) {
416             my($self) = @_;
417             my($line, $sock);
418             $sock = $self->{'socket'};
419             while (1) {
420                 if (!defined($line = $sock->getline())) {
421                     if ($sock->error()) {
422                         $self->Error("Client connection error %s",
423                                      $sock->error());
424                     }
425                     $sock->close();
426                     return;
427                 }
428                 $line =~ s/\s+$//; # Remove CRLF
429                 my($result) = eval $line;
430                 my($rc);
431                 if ($self->{'base'} eq 'hex') {
432                     $rc = printf $sock ("%x\n", $result);
433                 } elsif ($self->{'base'} eq 'oct') {
434                     $rc = printf $sock ("%o\n", $result);
435                 } else {
436                     $rc = printf $sock ("%d\n", $result);
437                 }
438                 if (!$rc) {
439                     $self->Error("Client connection error %s",
440                                  $sock->error());
441                     $sock->close();
442                     return;
443                 }
444             }
445         }
446
447         package main;
448
449         my $server = Calculator->new({'pidfile' => 'none',
450                                       'localport' => 2000}, \@ARGV);
451         $server->Bind();
452

KNOWN PROBLEMS

454       Most, or even any, known problems are related to the Sys::Syslog module
455       which is by default used for logging events under Unix. I'll quote some
456       examples:
457
458       Usage: Sys::Syslog::_PATH_LOG at ...
459           This problem is treated in perl bug 20000712.003. A workaround is
460           changing line 277 of Syslog.pm to
461
462             my $syslog = &_PATH_LOG() || croak "_PATH_LOG not found in syslog.ph";
463
465         Net::Daemon is Copyright (C) 1998, Jochen Wiedmann
466                                            Am Eisteich 9
467                                            72555 Metzingen
468                                            Germany
469
470                                            Phone: +49 7123 14887
471                                            Email: joe@ispsoft.de
472
473         All rights reserved.
474
475         You may distribute this package under the terms of either the GNU
476         General Public License or the Artistic License, as specified in the
477         Perl README file.
478

SEE ALSO

480       RPC::pServer(3), Netserver::Generic(3), Net::Daemon::Log(3),
481       Net::Daemon::Test(3)
482
483
484
485perl v5.16.3                      2011-03-09                    Net::Daemon(3)
Impressum