1Net::Daemon(3) User Contributed Perl Documentation Net::Daemon(3)
2
3
4
6 Net::Daemon - Perl extension for portable daemons
7
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
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.006 and ithreads, 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.006 and did compile it for ithreads, 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".
153
154 If threads are not available, but you have a working fork(), then
155 the server will behave similar by creating a new process for each
156 connection. This mode will be used automatically in the absence of
157 threads or if you use the "--mode=fork" option.
158
159 Finally there's a single-connection mode: If the server has
160 accepted a connection, he will enter the Run() method. No other
161 connections are accepted until the Run() method returns. This
162 operation mode is useful if you have neither ithreads nor fork(),
163 for example on the Macintosh. For debugging purposes you can force
164 this mode with "--mode=single".
165
166 When running in mode single, you can still handle multiple clients
167 at a time by preforking multiple child processes. The number of
168 childs is configured with the option "--childs".
169
170 childs
171 Use this parameter to let Net::Daemon run in prefork mode, which
172 means it forks the number of childs processes you give with this
173 parameter, and all child handle connections concurrently. The
174 difference to fork mode is, that the child processes continue to
175 run after a connection has terminated and are able to accept a new
176 connection. This is useful for caching inside the childs process
177 (e.g. DBI::ProxyServer connect_cached attribute)
178
179 options
180 Array ref of Command line options that have been passed to the
181 server object via the new method.
182
183 parent
184 When creating an object with Clone the original object becomes the
185 parent of the new object. Objects created with new usually don't
186 have a parent, thus this attribute is not set.
187
188 pidfile (--pidfile=file)
189 (UNIX only) If this option is present, a PID file will be created
190 at the given location.
191
192 proto (--proto=proto)
193 The transport layer to use, by default tcp or unix for a Unix
194 socket. It is not yet possible to combine both.
195
196 socket
197 The socket that is connected to the client; passed as $client
198 argument to the Clone method. If the server object was created with
199 new, this attribute can be undef, as long as the Bind method isn't
200 called. Sockets are assumed to be IO::Socket objects.
201
202 user (--user=uid)
203 After doing a bind(), change the real and effective UID to the
204 given. This is usefull, if you want your server to bind to a
205 privileged port (<1024), but don't want the server to execute as
206 root. See also the --group and the --chroot options.
207
208 UID's can be passed as group names or numeric values.
209
210 version (--version)
211 Supresses startup of the server; instead the version string will be
212 printed and the program exits immediately.
213
214 Note that most of these attributes (facility, mode, localaddr,
215 localport, pidfile, version) are meaningfull only at startup. If you
216 set them later, they will be simply ignored. As almost all attributes
217 have appropriate defaults, you will typically use the localport
218 attribute only.
219
220 Command Line Parsing
221 my $optionsAvailable = Net::Daemon->Options();
222
223 print Net::Daemon->Version(), "\n";
224
225 Net::Daemon->Usage();
226
227 The Options method returns a hash ref of possible command line options.
228 The keys are option names, the values are again hash refs with the
229 following keys:
230
231 template
232 An option template that can be passed to Getopt::Long::GetOptions.
233
234 description
235 A description of this option, as used in Usage
236
237 The Usage method prints a list of all possible options and returns. It
238 uses the Version method for printing program name and version.
239
240 Config File
241 If the config file option is set in the command line options or in the
242 in the "new" args, then the method
243
244 $server->ReadConfigFile($file, $options, $args)
245
246 is invoked. By default the config file is expected to contain Perl
247 source that returns a hash ref of options. These options override the
248 "new" args and will in turn be overwritten by the command line options,
249 as present in the $options hash ref.
250
251 A typical config file might look as follows, we use the
252 DBI::ProxyServer as an example:
253
254 # Load external modules; this is not required unless you use
255 # the chroot() option.
256 #require DBD::mysql;
257 #require DBD::CSV;
258
259 {
260 # 'chroot' => '/var/dbiproxy',
261 'facility' => 'daemon',
262 'pidfile' => '/var/dbiproxy/dbiproxy.pid',
263 'user' => 'nobody',
264 'group' => 'nobody',
265 'localport' => '1003',
266 'mode' => 'fork'
267
268 # Access control
269 'clients' => [
270 # Accept the local
271 {
272 'mask' => '^192\.168\.1\.\d+$',
273 'accept' => 1
274 },
275 # Accept myhost.company.com
276 {
277 'mask' => '^myhost\.company\.com$',
278 'accept' => 1
279 }
280 # Deny everything else
281 {
282 'mask' => '.*',
283 'accept' => 0
284 }
285 ]
286 }
287
288 Access control
289 The Net::Daemon package supports a host based access control scheme. By
290 default access is open for anyone. However, if you create an attribute
291 $self->{'clients'}, typically in the config file, then access control
292 is disabled by default. For any connection the client list is
293 processed: The clients attribute is an array ref to a list of hash
294 refs. Any of the hash refs may contain arbitrary attributes, including
295 the following:
296
297 mask A Perl regular expression that has to match the clients IP
298 number or its host name. The list is processed from the left to
299 the right, whenever a 'mask' attribute matches, then the
300 related hash ref is choosen as client and processing the client
301 list stops.
302
303 accept This may be set to true or false (default when omitting the
304 attribute), the former means accepting the client.
305
306 Event logging
307 $server->Log($level, $format, @args);
308 $server->Debug($format, @args);
309 $server->Error($format, @args);
310 $server->Fatal($format, @args);
311
312 The Log method is an interface to "Sys::Syslog (3)" or "Win32::EventLog
313 (3)". It's arguments are $level, a syslog level like debug, notice or
314 err, a format string in the style of printf and the format strings
315 arguments.
316
317 The Debug and Error methods are shorthands for calling Log with a level
318 of debug and err, respectively. The Fatal method is like Error, except
319 it additionally throws the given message as exception.
320
321 See Net::Daemon::Log(3) for details.
322
323 Flow of control
324 $server->Bind();
325 # The following inside Bind():
326 if ($connection->Accept()) {
327 $connection->Run();
328 } else {
329 $connection->Log('err', 'Connection refused');
330 }
331
332 The Bind method is called by the application when the server should
333 start. Typically this can be done right after creating the server
334 object $server. Bind usually never returns, except in case of errors.
335
336 When a client connects, the server uses Clone to derive a connection
337 object $connection from the server object. A new thread or process is
338 created that uses the connection object to call your classes Accept
339 method. This method is intended for host authorization and should
340 return either FALSE (refuse the client) or TRUE (accept the client).
341
342 If the client is accepted, the Run method is called which does the true
343 work. The connection is closed when Run returns and the corresponding
344 thread or process exits.
345
346 Error Handling
347 All methods are supposed to throw Perl exceptions in case of errors.
348
350 All methods are working with lexically scoped data and handle data
351 only, the exception being the OpenLog method which is invoked before
352 threading starts. Thus you are safe as long as you don't share handles
353 between threads. I strongly recommend that your application behaves
354 similar. (This doesn't apply to mode 'ithreads'.)
355
357 As an example we'll write a simple calculator server. After connecting
358 to this server you may type expressions, one per line. The server
359 evaluates the expressions and prints the result. (Note this is an
360 example, in real life we'd never implement such a security hole. :-)
361
362 For the purpose of example we add a command line option --base that
363 takes 'hex', 'oct' or 'dec' as values: The servers output will use the
364 given base.
365
366 # -*- perl -*-
367 #
368 # Calculator server
369 #
370 require 5.004;
371 use strict;
372
373 require Net::Daemon;
374
375
376 package Calculator;
377
378 use vars qw($VERSION @ISA);
379 $VERSION = '0.01';
380 @ISA = qw(Net::Daemon); # to inherit from Net::Daemon
381
382 sub Version ($) { 'Calculator Example Server, 0.01'; }
383
384 # Add a command line option "--base"
385 sub Options ($) {
386 my($self) = @_;
387 my($options) = $self->SUPER::Options();
388 $options->{'base'} = { 'template' => 'base=s',
389 'description' => '--base '
390 . 'dec (default), hex or oct'
391 };
392 $options;
393 }
394
395 # Treat command line option in the constructor
396 sub new ($$;$) {
397 my($class, $attr, $args) = @_;
398 my($self) = $class->SUPER::new($attr, $args);
399 if ($self->{'parent'}) {
400 # Called via Clone()
401 $self->{'base'} = $self->{'parent'}->{'base'};
402 } else {
403 # Initial call
404 if ($self->{'options'} && $self->{'options'}->{'base'}) {
405 $self->{'base'} = $self->{'options'}->{'base'}
406 }
407 }
408 if (!$self->{'base'}) {
409 $self->{'base'} = 'dec';
410 }
411 $self;
412 }
413
414 sub Run ($) {
415 my($self) = @_;
416 my($line, $sock);
417 $sock = $self->{'socket'};
418 while (1) {
419 if (!defined($line = $sock->getline())) {
420 if ($sock->error()) {
421 $self->Error("Client connection error %s",
422 $sock->error());
423 }
424 $sock->close();
425 return;
426 }
427 $line =~ s/\s+$//; # Remove CRLF
428 my($result) = eval $line;
429 my($rc);
430 if ($self->{'base'} eq 'hex') {
431 $rc = printf $sock ("%x\n", $result);
432 } elsif ($self->{'base'} eq 'oct') {
433 $rc = printf $sock ("%o\n", $result);
434 } else {
435 $rc = printf $sock ("%d\n", $result);
436 }
437 if (!$rc) {
438 $self->Error("Client connection error %s",
439 $sock->error());
440 $sock->close();
441 return;
442 }
443 }
444 }
445
446 package main;
447
448 my $server = Calculator->new({'pidfile' => 'none',
449 'localport' => 2000}, \@ARGV);
450 $server->Bind();
451
453 Most, or even any, known problems are related to the Sys::Syslog module
454 which is by default used for logging events under Unix. I'll quote some
455 examples:
456
457 Usage: Sys::Syslog::_PATH_LOG at ...
458 This problem is treated in perl bug 20000712.003. A workaround is
459 changing line 277 of Syslog.pm to
460
461 my $syslog = &_PATH_LOG() || croak "_PATH_LOG not found in syslog.ph";
462
464 Net::Daemon is Copyright (C) 1998, Jochen Wiedmann
465 Am Eisteich 9
466 72555 Metzingen
467 Germany
468
469 Phone: +49 7123 14887
470 Email: joe@ispsoft.de
471
472 All rights reserved.
473
474 You may distribute this package under the terms of either the GNU
475 General Public License or the Artistic License, as specified in the
476 Perl README file.
477
479 RPC::pServer(3), Netserver::Generic(3), Net::Daemon::Log(3),
480 Net::Daemon::Test(3)
481
482
483
484perl v5.12.0 2010-05-04 Net::Daemon(3)