1NAME 2 Net::Daemon - Perl extension for portable daemons 3 4SYNOPSIS 5 # Create a subclass of Net::Daemon 6 require Net::Daemon; 7 package MyDaemon; 8 @MyDaemon::ISA = qw(Net::Daemon); 9 10 sub Run ($) { 11 # This function does the real work; it is invoked whenever a 12 # new connection is made. 13 } 14 15DESCRIPTION 16 Net::Daemon is an abstract base class for implementing portable server 17 applications in a very simple way. The module is designed for Perl 5.005 18 and threads, but can work with fork() and Perl 5.004. 19 20 The Net::Daemon class offers methods for the most common tasks a daemon 21 needs: Starting up, logging, accepting clients, authorization, 22 restricting its own environment for security and doing the true work. 23 You only have to override those methods that aren't appropriate for you, 24 but typically inheriting will safe you a lot of work anyways. 25 26 Constructors 27 $server = Net::Daemon->new($attr, $options); 28 29 $connection = $server->Clone($socket); 30 31 Two constructors are available: The new method is called upon startup 32 and creates an object that will basically act as an anchor over the 33 complete program. It supports command line parsing via "Getopt::Long 34 (3)". 35 36 Arguments of new are *$attr*, an hash ref of attributes (see below) and 37 *$options* an array ref of options, typically command line arguments 38 (for example \@ARGV) that will be passed to Getopt::Long::GetOptions. 39 40 The second constructor is Clone: It is called whenever a client 41 connects. It receives the main server object as input and returns a new 42 object. This new object will be passed to the methods that finally do 43 the true work of communicating with the client. Communication occurs 44 over the socket $socket, Clone's argument. 45 46 Possible object attributes and the corresponding command line arguments 47 are: 48 49 *catchint* (--nocatchint) 50 On some systems, in particular Solaris, the functions accept(), 51 read() and so on are not safe against interrupts by signals. For 52 example, if the user raises a USR1 signal (as typically used to 53 reread config files), then the function returns an error EINTR. If 54 the *catchint* option is on (by default it is, use --nocatchint to 55 turn this off), then the package will ignore EINTR errors whereever 56 possible. 57 58 *chroot* (--chroot=dir) 59 (UNIX only) After doing a bind(), change root directory to the given 60 directory by doing a chroot(). This is usefull for security 61 operations, but it restricts programming a lot. For example, you 62 typically have to load external Perl extensions before doing a 63 chroot(), or you need to create hard links to Unix sockets. This is 64 typically done in the config file, see the --configfile option. See 65 also the --group and --user options. 66 67 If you don't know chroot(), think of an FTP server where you can see 68 a certain directory tree only after logging in. 69 70 *clients* 71 An array ref with a list of clients. Clients are hash refs, the 72 attributes *accept* (0 for denying access and 1 for permitting) and 73 *mask*, a Perl regular expression for the clients IP number or its 74 host name. See "Access control" below. 75 76 *configfile* (--configfile=file) 77 Net::Daemon supports the use of config files. These files are 78 assumed to contain a single hash ref that overrides the arguments of 79 the new method. However, command line arguments in turn take 80 precedence over the config file. See the "Config File" section below 81 for details on the config file. 82 83 *debug* (--debug) 84 Turn debugging mode on. Mainly this asserts that logging messages of 85 level "debug" are created. 86 87 *facility* (--facility=mode) 88 (UNIX only) Facility to use for "Sys::Syslog (3)". The default is 89 daemon. 90 91 *group* (--group=gid) 92 After doing a bind(), change the real and effective GID to the 93 given. This is usefull, if you want your server to bind to a 94 privileged port (<1024), but don't want the server to execute as 95 root. See also the --user option. 96 97 GID's can be passed as group names or numeric values. 98 99 *localaddr* (--localaddr=ip) 100 By default a daemon is listening to any IP number that a machine 101 has. This attribute allows to restrict the server to the given IP 102 number. 103 104 *localpath* (--localpath=path) 105 If you want to restrict your server to local services only, you'll 106 prefer using Unix sockets, if available. In that case you can use 107 this option for setting the path of the Unix socket being created. 108 This option implies --proto=unix. 109 110 *localport* (--localport=port) 111 This attribute sets the port on which the daemon is listening. It 112 must be given somehow, as there's no default. 113 114 *logfile* (--logfile=file) 115 By default logging messages will be written to the syslog (Unix) or 116 to the event log (Windows NT). On other operating systems you need 117 to specify a log file. The special value "STDERR" forces logging to 118 stderr. 119 120 *loop-child* (--loop-child) 121 This option forces creation of a new child for loops. (See the 122 *loop-timeout* option.) By default the loops are serialized. 123 124 *loop-timeout* (--loop-timeout=secs) 125 Some servers need to take an action from time to time. For example 126 the Net::Daemon::Spooler attempts to empty its spooling queue every 127 5 minutes. If this option is set to a positive value (zero being the 128 default), then the server will call its Loop method every 129 "loop-timeout" seconds. 130 131 Don't trust too much on the precision of the interval: It depends on 132 a number of factors, in particular the execution time of the Loop() 133 method. The loop is implemented by using the *select* function. If 134 you need an exact interval, you should better try to use the alarm() 135 function and a signal handler. (And don't forget to look at the 136 *catchint* option!) 137 138 It is recommended to use the *loop-child* option in conjunction with 139 *loop-timeout*. 140 141 *mode* (--mode=modename) 142 The Net::Daemon server can run in three different modes, depending 143 on the environment. 144 145 If you are running Perl 5.005 and did compile it for threads, then 146 the server will create a new thread for each connection. The thread 147 will execute the server's Run() method and then terminate. This mode 148 is the default, you can force it with "--mode=ithreads" or 149 "--mode=threads". 150 151 If threads are not available, but you have a working fork(), then 152 the server will behave similar by creating a new process for each 153 connection. This mode will be used automatically in the absence of 154 threads or if you use the "--mode=fork" option. 155 156 Finally there's a single-connection mode: If the server has accepted 157 a connection, he will enter the Run() method. No other connections 158 are accepted until the Run() method returns. This operation mode is 159 useful if you have neither threads nor fork(), for example on the 160 Macintosh. For debugging purposes you can force this mode with 161 "--mode=single". 162 163 When running in mode single, you can still handle multiple clients 164 at a time by preforking multiple child processes. The number of 165 childs is configured with the option "--childs". 166 167 *childs* 168 Use this parameter to let Net::Daemon run in prefork mode, which 169 means it forks the number of childs processes you give with this 170 parameter, and all child handle connections concurrently. The 171 difference to fork mode is, that the child processes continue to run 172 after a connection has terminated and are able to accept a new 173 connection. This is useful for caching inside the childs process 174 (e.g. DBI::ProxyServer connect_cached attribute) 175 176 *options* 177 Array ref of Command line options that have been passed to the 178 server object via the new method. 179 180 *parent* 181 When creating an object with Clone the original object becomes the 182 parent of the new object. Objects created with new usually don't 183 have a parent, thus this attribute is not set. 184 185 *pidfile* (--pidfile=file) 186 (UNIX only) If this option is present, a PID file will be created at 187 the given location. 188 189 *proto* (--proto=proto) 190 The transport layer to use, by default *tcp* or *unix* for a Unix 191 socket. It is not yet possible to combine both. 192 193 *socket* 194 The socket that is connected to the client; passed as $client 195 argument to the Clone method. If the server object was created with 196 new, this attribute can be undef, as long as the Bind method isn't 197 called. Sockets are assumed to be IO::Socket objects. 198 199 *user* (--user=uid) 200 After doing a bind(), change the real and effective UID to the 201 given. This is usefull, if you want your server to bind to a 202 privileged port (<1024), but don't want the server to execute as 203 root. See also the --group and the --chroot options. 204 205 UID's can be passed as group names or numeric values. 206 207 *version* (--version) 208 Supresses startup of the server; instead the version string will be 209 printed and the program exits immediately. 210 211 Note that most of these attributes (facility, mode, localaddr, 212 localport, pidfile, version) are meaningfull only at startup. If you set 213 them later, they will be simply ignored. As almost all attributes have 214 appropriate defaults, you will typically use the localport attribute 215 only. 216 217 Command Line Parsing 218 my $optionsAvailable = Net::Daemon->Options(); 219 220 print Net::Daemon->Version(), "\n"; 221 222 Net::Daemon->Usage(); 223 224 The Options method returns a hash ref of possible command line options. 225 The keys are option names, the values are again hash refs with the 226 following keys: 227 228 template 229 An option template that can be passed to Getopt::Long::GetOptions. 230 231 description 232 A description of this option, as used in Usage 233 234 The Usage method prints a list of all possible options and returns. It 235 uses the Version method for printing program name and version. 236 237 Config File 238 If the config file option is set in the command line options or in the 239 in the "new" args, then the method 240 241 $server->ReadConfigFile($file, $options, $args) 242 243 is invoked. By default the config file is expected to contain Perl 244 source that returns a hash ref of options. These options override the 245 "new" args and will in turn be overwritten by the command line options, 246 as present in the $options hash ref. 247 248 A typical config file might look as follows, we use the DBI::ProxyServer 249 as an example: 250 251 # Load external modules; this is not required unless you use 252 # the chroot() option. 253 #require DBD::mysql; 254 #require DBD::CSV; 255 256 { 257 # 'chroot' => '/var/dbiproxy', 258 'facility' => 'daemon', 259 'pidfile' => '/var/dbiproxy/dbiproxy.pid', 260 'user' => 'nobody', 261 'group' => 'nobody', 262 'localport' => '1003', 263 'mode' => 'fork' 264 265 # Access control 266 'clients' => [ 267 # Accept the local 268 { 269 'mask' => '^192\.168\.1\.\d+$', 270 'accept' => 1 271 }, 272 # Accept myhost.company.com 273 { 274 'mask' => '^myhost\.company\.com$', 275 'accept' => 1 276 } 277 # Deny everything else 278 { 279 'mask' => '.*', 280 'accept' => 0 281 } 282 ] 283 } 284 285 Access control 286 The Net::Daemon package supports a host based access control scheme. By 287 default access is open for anyone. However, if you create an attribute 288 $self->{'clients'}, typically in the config file, then access control is 289 disabled by default. For any connection the client list is processed: 290 The clients attribute is an array ref to a list of hash refs. Any of the 291 hash refs may contain arbitrary attributes, including the following: 292 293 mask A Perl regular expression that has to match the clients IP 294 number or its host name. The list is processed from the left to 295 the right, whenever a 'mask' attribute matches, then the related 296 hash ref is choosen as client and processing the client list 297 stops. 298 299 accept This may be set to true or false (default when omitting the 300 attribute), the former means accepting the client. 301 302 Event logging 303 $server->Log($level, $format, @args); 304 $server->Debug($format, @args); 305 $server->Error($format, @args); 306 $server->Fatal($format, @args); 307 308 The Log method is an interface to "Sys::Syslog (3)" or "Win32::EventLog 309 (3)". It's arguments are *$level*, a syslog level like debug, notice or 310 err, a format string in the style of printf and the format strings 311 arguments. 312 313 The Debug and Error methods are shorthands for calling Log with a level 314 of debug and err, respectively. The Fatal method is like Error, except 315 it additionally throws the given message as exception. 316 317 See Net::Daemon::Log(3) for details. 318 319 Flow of control 320 $server->Bind(); 321 # The following inside Bind(): 322 if ($connection->Accept()) { 323 $connection->Run(); 324 } else { 325 $connection->Log('err', 'Connection refused'); 326 } 327 328 The Bind method is called by the application when the server should 329 start. Typically this can be done right after creating the server object 330 $server. Bind usually never returns, except in case of errors. 331 332 When a client connects, the server uses Clone to derive a connection 333 object $connection from the server object. A new thread or process is 334 created that uses the connection object to call your classes Accept 335 method. This method is intended for host authorization and should return 336 either FALSE (refuse the client) or TRUE (accept the client). 337 338 If the client is accepted, the Run method is called which does the true 339 work. The connection is closed when Run returns and the corresponding 340 thread or process exits. 341 342 Error Handling 343 All methods are supposed to throw Perl exceptions in case of errors. 344 345MULTITHREADING CONSIDERATIONS 346 All methods are working with lexically scoped data and handle data only, 347 the exception being the OpenLog method which is invoked before threading 348 starts. Thus you are safe as long as you don't share handles between 349 threads. I strongly recommend that your application behaves similar. 350 (This doesn't apply to mode 'ithreads'.) 351 352EXAMPLE 353 As an example we'll write a simple calculator server. After connecting 354 to this server you may type expressions, one per line. The server 355 evaluates the expressions and prints the result. (Note this is an 356 example, in real life we'd never implement such a security hole. :-) 357 358 For the purpose of example we add a command line option *--base* that 359 takes 'hex', 'oct' or 'dec' as values: The servers output will use the 360 given base. 361 362 # -*- perl -*- 363 # 364 # Calculator server 365 # 366 require 5.004; 367 use strict; 368 369 require Net::Daemon; 370 371 372 package Calculator; 373 374 use vars qw($VERSION @ISA); 375 $VERSION = '0.01'; 376 @ISA = qw(Net::Daemon); # to inherit from Net::Daemon 377 378 sub Version ($) { 'Calculator Example Server, 0.01'; } 379 380 # Add a command line option "--base" 381 sub Options ($) { 382 my($self) = @_; 383 my($options) = $self->SUPER::Options(); 384 $options->{'base'} = { 'template' => 'base=s', 385 'description' => '--base ' 386 . 'dec (default), hex or oct' 387 }; 388 $options; 389 } 390 391 # Treat command line option in the constructor 392 sub new ($$;$) { 393 my($class, $attr, $args) = @_; 394 my($self) = $class->SUPER::new($attr, $args); 395 if ($self->{'parent'}) { 396 # Called via Clone() 397 $self->{'base'} = $self->{'parent'}->{'base'}; 398 } else { 399 # Initial call 400 if ($self->{'options'} && $self->{'options'}->{'base'}) { 401 $self->{'base'} = $self->{'options'}->{'base'} 402 } 403 } 404 if (!$self->{'base'}) { 405 $self->{'base'} = 'dec'; 406 } 407 $self; 408 } 409 410 sub Run ($) { 411 my($self) = @_; 412 my($line, $sock); 413 $sock = $self->{'socket'}; 414 while (1) { 415 if (!defined($line = $sock->getline())) { 416 if ($sock->error()) { 417 $self->Error("Client connection error %s", 418 $sock->error()); 419 } 420 $sock->close(); 421 return; 422 } 423 $line =~ s/\s+$//; # Remove CRLF 424 my($result) = eval $line; 425 my($rc); 426 if ($self->{'base'} eq 'hex') { 427 $rc = printf $sock ("%x\n", $result); 428 } elsif ($self->{'base'} eq 'oct') { 429 $rc = printf $sock ("%o\n", $result); 430 } else { 431 $rc = printf $sock ("%d\n", $result); 432 } 433 if (!$rc) { 434 $self->Error("Client connection error %s", 435 $sock->error()); 436 $sock->close(); 437 return; 438 } 439 } 440 } 441 442 package main; 443 444 my $server = Calculator->new({'pidfile' => 'none', 445 'localport' => 2000}, \@ARGV); 446 $server->Bind(); 447 448KNOWN PROBLEMS 449 Most, or even any, known problems are related to the Sys::Syslog module 450 which is by default used for logging events under Unix. I'll quote some 451 examples: 452 453 Usage: Sys::Syslog::_PATH_LOG at ... 454 This problem is treated in perl bug 20000712.003. A workaround is 455 changing line 277 of Syslog.pm to 456 457 my $syslog = &_PATH_LOG() || croak "_PATH_LOG not found in syslog.ph"; 458 459AUTHOR AND COPYRIGHT 460 Net::Daemon is Copyright (C) 1998, Jochen Wiedmann 461 Am Eisteich 9 462 72555 Metzingen 463 Germany 464 465 Phone: +49 7123 14887 466 Email: joe@ispsoft.de 467 468 All rights reserved. 469 470 You may distribute this package under the terms of either the GNU 471 General Public License or the Artistic License, as specified in the 472 Perl README file. 473 474SEE ALSO 475 RPC::pServer(3), Netserver::Generic(3), Net::Daemon::Log(3), 476 Net::Daemon::Test(3) 477 478