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

NAME

6       Net::Server - Extensible, general Perl server engine
7

SYNOPSIS

9           #!/usr/bin/perl -w -T
10           package MyPackage;
11
12           use base qw(Net::Server);
13
14           sub process_request {
15               my $self = shift;
16               while (<STDIN>) {
17                   s/\r?\n$//;
18                   print "You said '$_'\r\n"; # basic echo
19                   last if /quit/i;
20               }
21           }
22
23           MyPackage->run(port => 160);
24

FEATURES

26        * Single Server Mode
27        * Inetd Server Mode
28        * Preforking Simple Mode (PreForkSimple)
29        * Preforking Managed Mode (PreFork)
30        * Forking Mode
31        * Multiplexing Mode using a single process
32        * Multi port accepts on Single, Preforking, and Forking modes
33        * Simultaneous accept/recv on tcp, udp, and unix sockets
34        * Safe signal handling in Fork/PreFork avoids perl signal trouble
35        * User customizable hooks
36        * Chroot ability after bind
37        * Change of user and group after bind
38        * Basic allow/deny access control
39        * Customized logging (choose Syslog, log_file, or STDERR)
40        * HUP able server (clean restarts via sig HUP)
41        * Dequeue ability in all Fork and PreFork modes.
42        * Taint clean
43        * Written in Perl
44        * Protection against buffer overflow
45        * Clean process flow
46        * Extensibility
47

DESCRIPTION

49       "Net::Server" is an extensible, generic Perl server engine.
50       "Net::Server" combines the good properties from "Net::Daemon" (0.34),
51       "NetServer::Generic" (1.03), and "Net::FTPServer" (1.0), and also from
52       various concepts in the Apache Webserver.
53
54       "Net::Server" attempts to be a generic server as in "Net::Daemon" and
55       "NetServer::Generic".  It includes with it the ability to run as an
56       inetd process ("Net::Server::INET"), a single connection server
57       ("Net::Server" or "Net::Server::Single"), a forking server
58       ("Net::Server::Fork"), a preforking server which maintains a constant
59       number of preforked children ("Net::Server::PreForkSimple"), or as a
60       managed preforking server which maintains the number of children based
61       on server load ("Net::Server::PreFork").  In all but the inetd type,
62       the server provides the ability to connect to one or to multiple server
63       ports.
64
65       "Net::Server" uses ideologies of "Net::FTPServer" in order to provide
66       extensibility.  The additional server types are made possible via
67       "personalities" or sub classes of the "Net::Server".  By moving the
68       multiple types of servers out of the main "Net::Server" class, the
69       "Net::Server" concept is easily extended to other types (in the near
70       future, we would like to add a "Thread" personality).
71
72       "Net::Server" borrows several concepts from the Apache Webserver.
73       "Net::Server" uses "hooks" to allow custom servers such as SMTP, HTTP,
74       POP3, etc. to be layered over the base "Net::Server" class.  In
75       addition the "Net::Server::PreFork" class borrows concepts of
76       min_start_servers, max_servers, and min_waiting servers.
77       "Net::Server::PreFork" also uses the concept of an flock serialized
78       accept when accepting on multiple ports (PreFork can choose between
79       flock, IPC::Semaphore, and pipe to control serialization).
80

PERSONALITIES

82       "Net::Server" is built around a common class (Net::Server) and is
83       extended using sub classes, or "personalities".  Each personality
84       inherits, overrides, or enhances the base methods of the base class.
85
86       Included with the Net::Server package are several basic personalities,
87       each of which has their own use.
88
89       Fork
90           Found in the module Net/Server/Fork.pm (see Net::Server::Fork).
91           This server binds to one or more ports and then waits for a
92           connection.  When a client request is received, the parent forks a
93           child, which then handles the client and exits.  This is good for
94           moderately hit services.
95
96       INET
97           Found in the module Net/Server/INET.pm (see Net::Server::INET).
98           This server is designed to be used with inetd.  The "pre_bind",
99           "bind", "accept", and "post_accept" are all overridden as these
100           services are taken care of by the INET daemon.
101
102       MultiType
103           Found in the module Net/Server/MultiType.pm (see
104           Net::Server::MultiType).  This server has no server functionality
105           of its own.  It is designed for servers which need a simple way to
106           easily switch between different personalities.  Multiple
107           "server_type" parameters may be given and Net::Server::MultiType
108           will cycle through until it finds a class that it can use.
109
110       Multiplex
111           Found in the module Net/Server/Multiplex.pm (see
112           Net::Server::Multiplex).  This server binds to one or more ports.
113           It uses IO::Multiplex to multiplex between waiting for new
114           connections and waiting for input on currently established
115           connections.  This personality is designed to run as one process
116           without forking.  The "process_request" method is never used but
117           the "mux_input" callback is used instead (see also IO::Multiplex).
118           See examples/samplechat.pl for an example using most of the
119           features of Net::Server::Multiplex.
120
121       PreForkSimple
122           Found in the module Net/Server/PreFork.pm (see
123           Net::Server::PreFork).  This server binds to one or more ports and
124           then forks "max_servers" child process.  The server will make sure
125           that at any given time there are always "max_servers" available to
126           receive a client request.  Each of these children will process up
127           to "max_requests" client connections.  This type is good for a
128           heavily hit site that can dedicate max_server processes no matter
129           what the load.  It should scale well for most applications.  Multi
130           port accept is accomplished using either flock, IPC::Semaphore, or
131           pipe to serialize the children.  Serialization may also be switched
132           on for single port in order to get around an OS that does not allow
133           multiple children to accept at the same time.  For a further
134           discussion of serialization see Net::Server::PreFork.
135
136       PreFork
137           Found in the module Net/Server/PreFork.pm (see
138           Net::Server::PreFork).  This server binds to one or more ports and
139           then forks "min_servers" child process.  The server will make sure
140           that at any given time there are at least "min_spare_servers" but
141           not more than "max_spare_servers" available to receive a client
142           request, up to "max_servers".  Each of these children will process
143           up to "max_requests" client connections.  This type is good for a
144           heavily hit site, and should scale well for most applications.
145           Multi port accept is accomplished using either flock,
146           IPC::Semaphore, or pipe to serialize the children.  Serialization
147           may also be switched on for single port in order to get around an
148           OS that does not allow multiple children to accept at the same
149           time.  For a further discussion of serialization see
150           Net::Server::PreFork.
151
152       Single
153           All methods fall back to Net::Server.  This personality is provided
154           only as parallelism for Net::Server::MultiType.
155
156       "Net::Server" was partially written to make it easy to add new
157       personalities.  Using separate modules built upon an open architecture
158       allows for easy addition of new features, a separate development
159       process, and reduced code bloat in the core module.
160

SOCKET ACCESS

162       Once started, the Net::Server will take care of binding to port and
163       waiting for connections.  Once a connection is received, the
164       Net::Server will accept on the socket and will store the result (the
165       client connection) in $self->{server}->{client}.  This property is a
166       Socket blessed into the the IO::Socket classes.  UDP servers are
167       slightly different in that they will perform a recv instead of an
168       accept.
169
170       To make programming easier, during the post_accept phase, STDIN and
171       STDOUT are opened to the client connection.  This allows for programs
172       to be written using <STDIN> and print "out\n" to print to the client
173       connection.  UDP will require using a ->send call.
174

SAMPLE CODE

176       The following is a very simple server.  The main functionality occurs
177       in the process_request method call as shown below.  Notice the use of
178       timeouts to prevent Denial of Service while reading.  (Other examples
179       of using "Net::Server" can, or will, be included with this
180       distribution).
181
182           #!/usr/bin/perl -w -T
183
184           package MyPackage;
185
186           use strict;
187           use base qw(Net::Server::PreFork); # any personality will do
188
189           MyPackage->run;
190
191           ### over-ridden subs below
192
193           sub process_request {
194               my $self = shift;
195               eval {
196
197                   local $SIG{'ALRM'} = sub { die "Timed Out!\n" };
198                   my $timeout = 30; # give the user 30 seconds to type some lines
199
200                   my $previous_alarm = alarm($timeout);
201                   while (<STDIN>) {
202                       s/\r?\n$//;
203                       print "You said '$_'\r\n";
204                       alarm($timeout);
205                   }
206                   alarm($previous_alarm);
207
208               };
209
210               if ($@ =~ /timed out/i) {
211                   print STDOUT "Timed Out.\r\n";
212                   return;
213               }
214
215           }
216
217           1;
218
219       Playing this file from the command line will invoke a Net::Server using
220       the PreFork personality.  When building a server layer over the
221       Net::Server, it is important to use features such as timeouts to
222       prevent Denial Of Service attacks.
223

ARGUMENTS

225       There are five possible ways to pass arguments to Net::Server.  They
226       are passing to the new method, passing on command line, passing
227       parameters to run, using a conf file, returning values in the
228       default_values method, or configuring the values in
229       post_configure_hook.
230
231       The "options" method is used to determine which arguments the server
232       will search for and can be used to extend the parsed parameters.  Any
233       arguments found from the command line, parameters passed to run, and
234       arguments found in the conf_file will be matched against the keys of
235       the options template.  Any commandline parameters that do not match
236       will be left in place and can be further processed by the server in the
237       various hooks (by looking at @ARGV).  Arguments passed to new will
238       automatically win over any other options (this can be used if you would
239       like to disallow a user passing in other arguments).
240
241       Arguments consist of key value pairs.  On the commandline these pairs
242       follow the POSIX fashion of "--key value" or "--key=value", and also
243       "key=value".  In the conf file the parameter passing can best be shown
244       by the following regular expression:
245       ($key,$val)=~/^(\w+)\s+(\S+?)\s+$/.  Passing arguments to the run
246       method is done as follows: "Net::Server-"run(key1 => 'val1')>.  Passing
247       arguments via a prebuilt object can best be shown in the following
248       code:
249
250           #!/usr/bin/perl -w -T
251
252           package MyPackage;
253           use strict;
254           use base qw(Net::Server);
255
256           my $server = MyPackage->new({
257               key1 => 'val1',
258           });
259
260           $server->run;
261
262       All five methods for passing arguments may be used at the same time.
263       Once an argument has been set, it is not over written if another method
264       passes the same argument.  "Net::Server" will look for arguments in the
265       following order:
266
267         1) Arguments passed to the C<new> method.
268         2) Arguments passed on command line.
269         3) Arguments passed to the C<run> method.
270         4) Arguments passed via a conf file.
271         5) Arguments set in the C<default_values> method.
272
273       Additionally the following hooks are available:
274
275         1) Arguments set in the configure_hook (occurs after new
276            but before any of the other areas are checked).
277         2) Arguments set and validated in the post_configure_hook
278            (occurs after all of the other areas are checked).
279
280       Each of these levels will override parameters of the same name
281       specified in subsequent levels.  For example, specifying --setsid=0 on
282       the command line will override a value of "setsid 1" in the conf file.
283
284       Note that the configure_hook method doesn't return values to set, but
285       is there to allow for setting up configured values before the configure
286       method is called.
287
288       Key/value pairs used by the server are removed by the configuration
289       process so that server layers on top of "Net::Server" can pass and read
290       their own parameters.
291

ADDING CUSTOM ARGUMENTS

293       It is possible to add in your own custom parameters to those parsed by
294       Net::Server.  The following code shows how this is done:
295
296           sub options {
297               my $self     = shift;
298               my $prop     = $self->{'server'};
299               my $template = shift;
300
301               ### setup options in the parent classes
302               $self->SUPER::options($template);
303
304               ### add a single value option
305               $prop->{'my_option'} ||= undef;
306               $template->{'my_option'} = \ $prop->{'my_option'};
307
308               ### add a multi value option
309               $prop->{'an_arrayref_item'} ||= [];
310               $template->{'an_arrayref_item'} = $prop->{'an_arrayref_item'};
311           }
312
313       Overriding the "options" method allows for adding your own custom
314       fields.  A template hashref is passed in, that should then be modified
315       to contain an of your custom fields.  Fields which are intended to
316       receive a single scalar value should have a reference to the
317       destination scalar given.  Fields which are intended to receive
318       multiple values should reference the corresponding destination
319       arrayref.
320
321       You are responsible for validating your custom options once they have
322       been parsed.  The post_configure_hook is a good place to do your
323       validation.
324
325       Some emails have asked why we use this "template" method.  The idea is
326       that you are creating the the data structure to store the values in,
327       and you are also creating a way to get the values into the data
328       structure.  The template is the way to get the values to the servers
329       data structure.  One of the possibilities (that probably isn't used
330       that much) is that by letting you specify the mapping, you could build
331       a nested data structure - even though the passed in arguments are flat.
332       It also allows you to setup aliases to your names.
333
334       For example, a basic structure might look like this:
335
336          $prop = $self->{'server'}
337
338          $prop->{'my_custom_option'} ||= undef;
339          $prop->{'my_custom_array'}  ||= [];
340
341          $template = {
342             my_custom_option => \ $prop->{'my_custom_option'},
343             mco              => \ $prop->{'my_custom_option'}, # alias
344             my_custom_array  => $prop->{'my_custom_array'},
345             mca              => $prop->{'my_custom_array'}, # an alias
346          };
347
348          $template->{'mco2'} = $template->{'mco'}; # another way to alias
349
350       But you could also have more complex data:
351
352          $prop = $self->{'server'};
353
354          $prop->{'one_layer'} = {
355              two_layer => [
356                  undef,
357                  undef,
358              ],
359          };
360
361          $template = {
362               param1 => \ $prop->{'one_layer'}->{'two_layer'}->[0],
363               param2 => \ $prop->{'one_layer'}->{'two_layer'}->[1],
364          };
365
366       This is of course a contrived example - but it does show that you can
367       get the data from the flat passed in arguments to whatever type of
368       structure you need - with only a little bit of effort.
369

DEFAULT ARGUMENTS FOR Net::Server

371       The following arguments are available in the default "Net::Server" or
372       "Net::Server::Single" modules.  (Other personalities may use additional
373       parameters and may optionally not use parameters from the base class.)
374
375         Key               Value                    Default
376         conf_file         "filename"               undef
377
378         log_level         0-4                      2
379         log_file          (filename|Sys::Syslog)   undef
380
381         ## syslog parameters
382         syslog_logsock    (native|unix|inet|udp
383                            |tcp|stream|console)    unix (on Sys::Syslog < 0.15)
384         syslog_ident      "identity"               "net_server"
385         syslog_logopt     (cons|ndelay|nowait|pid) pid
386         syslog_facility   \w+                      daemon
387
388         port              \d+                      20203
389         host              "host"                   "*"
390         proto             (tcp|udp|unix)           "tcp"
391         listen            \d+                      SOMAXCONN
392
393         reverse_lookups   1                        undef
394         allow             /regex/                  none
395         deny              /regex/                  none
396         cidr_allow        CIDR                     none
397         cidr_deny         CIDR                     none
398
399         ## daemonization parameters
400         pid_file          "filename"               undef
401         chroot            "directory"              undef
402         user              (uid|username)           "nobody"
403         group             (gid|group)              "nobody"
404         background        1                        undef
405         setsid            1                        undef
406
407         no_close_by_child (1|undef)                undef
408
409         ## See Net::Server::Proto::(TCP|UDP|UNIX|etc)
410         ## for more sample parameters.
411
412       conf_file
413           Filename from which to read additional key value pair arguments for
414           starting the server.  Default is undef.
415
416           There are two ways that you can specify a default location for a
417           conf_file.  The first is to pass the default value to the run
418           method as in:
419
420               MyServer->run({
421                  conf_file => '/etc/my_server.conf',
422               });
423
424           If the end user passes in --conf_file=/etc/their_server.conf then
425           the value will be overridden.
426
427           The second way to do this was added in the 0.96 version.  It uses
428           the default_values method as in:
429
430               sub default_values {
431                   return {
432                       conf_file => '/etc/my_server.conf',
433                   }
434               }
435
436           This method has the advantage of also being able to be overridden
437           in the run method.
438
439           If you do not want the user to be able to specify a conf_file at
440           all, you can pass conf_file to the new method when creating your
441           object:
442
443               MyServer->new({
444                  conf_file => '/etc/my_server.conf',
445               })->run;
446
447           If passed this way, the value passed to new will "win" over any of
448           the other passed in values.
449
450       log_level
451           Ranges from 0 to 4 in level.  Specifies what level of error will be
452           logged.  "O" means logging is off.  "4" means very verbose.  These
453           levels should be able to correlate to syslog levels.  Default is 2.
454           These levels correlate to syslog levels as defined by the following
455           key/value pairs: 0=>'err', 1=>'warning', 2=>'notice', 3=>'info',
456           4=>'debug'.
457
458       log_file
459           Name of log file to be written to.  If no name is given and hook is
460           not overridden, log goes to STDERR.  Default is undef.  If the
461           magic name "Sys::Syslog" is used, all logging will take place via
462           the Sys::Syslog module.  If syslog is used the parameters
463           "syslog_logsock", "syslog_ident", and "syslog_logopt",and
464           "syslog_facility" may also be defined.  If a "log_file" is given or
465           if "setsid" is set, STDIN and STDOUT will automatically be opened
466           to /dev/null and STDERR will be opened to STDOUT.  This will
467           prevent any output from ending up at the terminal.
468
469       pid_file
470           Filename to store pid of parent process.  Generally applies only to
471           forking servers.  Default is none (undef).
472
473       syslog_logsock
474           Only available if "log_file" is equal to "Sys::Syslog".  May be
475           either unix, inet, native, console, stream, udp, or tcp, or an
476           arrayref of the types to try.  Default is "unix" if the version of
477           Sys::Syslog < 0.15 - otherwise the default is to not call
478           setlogsock.
479
480           See Sys::Syslog.
481
482       syslog_ident
483           Only available if "log_file" is equal to "Sys::Syslog".  Id to
484           prepend on syslog entries.  Default is "net_server".  See
485           Sys::Syslog.
486
487       syslog_logopt
488           Only available if "log_file" is equal to "Sys::Syslog".  May be
489           either zero or more of "pid","cons","ndelay","nowait".  Default is
490           "pid".  See Sys::Syslog.
491
492       syslog_facility
493           Only available if "log_file" is equal to "Sys::Syslog".  See
494           Sys::Syslog and syslog.  Default is "daemon".
495
496       port
497           See Net::Server::Proto.  Local port/socket on which to bind.  If
498           low port, process must start as root.  If multiple ports are given,
499           all will be bound at server startup.  May be of the form
500           "host:port/proto", "host:port", "port/proto", or "port", where host
501           represents a hostname residing on the local box, where port
502           represents either the number of the port (eg. "80") or the service
503           designation (eg.  "http"), and where proto represents the protocol
504           to be used.  See Net::Server::Proto.  If you are working with unix
505           sockets, you may also specify "socket_file|unix" or
506           "socket_file|type|unix" where type is SOCK_DGRAM or SOCK_STREAM.
507           If the protocol is not specified, proto will default to the "proto"
508           specified in the arguments.  If "proto" is not specified there it
509           will default to "tcp".  If host is not specified, host will default
510           to "host" specified in the arguments.  If "host" is not specified
511           there it will default to "*".  Default port is 20203.
512           Configuration passed to new or run may be either a scalar
513           containing a single port number or an arrayref of ports.
514
515       host
516           Local host or addr upon which to bind port.  If a value of '*' is
517           given, the server will bind that port on all available addresses on
518           the box.  See Net::Server::Proto. See IO::Socket.  Configuration
519           passed to new or run may be either a scalar containing a single
520           host or an arrayref of hosts - if the hosts array is shorter than
521           the ports array, the last host entry will be used to augment the
522           hosts arrary to the size of the ports array.
523
524       proto
525           See Net::Server::Proto.  Protocol to use when binding ports.  See
526           IO::Socket.  As of release 0.70, Net::Server supports tcp, udp, and
527           unix.  Other types will need to be added later (or custom modules
528           extending the Net::Server::Proto class may be used).  Configuration
529           passed to new or run may be either a scalar containing a single
530           proto or an arrayref of protos - if the protos array is shorter
531           than the ports array, the last proto entry will be used to augment
532           the protos arrary to the size of the ports array.
533
534       listen
535             See L<IO::Socket>.  Not used with udp protocol (or UNIX SOCK_DGRAM).
536
537       reverse_lookups
538           Specify whether to lookup the hostname of the connected IP.
539           Information is cached in server object under "peerhost" property.
540           Default is to not use reverse_lookups (undef).
541
542       allow/deny
543           May be specified multiple times.  Contains regex to compare to
544           incoming peeraddr or peerhost (if reverse_lookups has been
545           enabled).  If allow or deny options are given, the incoming client
546           must match an allow and not match a deny or the client connection
547           will be closed.  Defaults to empty array refs.
548
549       cidr_allow/cidr_deny
550           May be specified multiple times.  Contains a CIDR block to compare
551           to incoming peeraddr.  If cidr_allow or cidr_deny options are
552           given, the incoming client must match a cidr_allow and not match a
553           cidr_deny or the client connection will be closed.  Defaults to
554           empty array refs.
555
556       chroot
557           Directory to chroot to after bind process has taken place and the
558           server is still running as root.  Defaults to undef.
559
560       user
561           Userid or username to become after the bind process has occured.
562           Defaults to "nobody."  If you would like the server to run as root,
563           you will have to specify "user" equal to "root".
564
565       group
566           Groupid or groupname to become after the bind process has occured.
567           Defaults to "nobody."  If you would like the server to run as root,
568           you will have to specify "group" equal to "root".
569
570       background
571           Specifies whether or not the server should fork after the bind
572           method to release itself from the command line.  Defaults to undef.
573           Process will also background if "setsid" is set.
574
575       setsid
576           Specifies whether or not the server should fork after the bind
577           method to release itself from the command line and then run the
578           "POSIX::setsid()" command to truly daemonize.  Defaults to undef.
579           If a "log_file" is given or if "setsid" is set, STDIN and STDOUT
580           will automatically be opened to /dev/null and STDERR will be opened
581           to STDOUT.  This will prevent any output from ending up at the
582           terminal.
583
584       no_close_by_child
585           Boolean.  Specifies whether or not a forked child process has
586           permission or not to shutdown the entire server process.  If set to
587           1, the child may NOT signal the parent to shutdown all children.
588           Default is undef (not set).
589
590       no_client_stdout
591           Boolean.  Default undef (not set).  Specifies that STDIN and STDOUT
592           should not be opened on the client handle once a connection has
593           been accepted.  By default the Net::Server will open STDIN and
594           STDOUT on the client socket making it easier for many types of
595           scripts to read directly from and write directly to the socket
596           using normal print and read methods.  Disabling this is useful on
597           clients that may be opening their own connections to STDIN and
598           STDOUT.
599
600           This option has no affect on STDIN and STDOUT which has a magic
601           client property that is tied to the already open STDIN and STDOUT.
602
603       leave_children_open_on_hup
604           Boolean.  Default undef (not set).  If set, the parent will not
605           attempt to close child processes if the parent receives a SIG HUP.
606           The parent will rebind the the open port and begin tracking a fresh
607           set of children.
608
609           Children of a Fork server will exit after their current request.
610           Children of a Prefork type server will finish the current request
611           and then exit.
612
613           Note - the newly restarted parent will start up a fresh set of
614           servers on fork servers.  The new parent will attempt to keep track
615           of the children from the former parent but custom communication
616           channels (open pipes from the child to the old parent) will no
617           longer be available to the old child processes.  New child
618           processes will still connect properly to the new parent.
619

PROPERTIES

621       All of the "ARGUMENTS" listed above become properties of the server
622       object under the same name.  These properties, as well as other
623       internal properties, are available during hooks and other method calls.
624
625       The structure of a Net::Server object is shown below:
626
627         $self = bless( {
628                          'server' => {
629                                        'key1' => 'val1',
630                                        # more key/vals
631                                      }
632                        }, 'Net::Server' );
633
634       This structure was chosen so that all server related properties are
635       grouped under a single key of the object hashref.  This is so that
636       other objects could layer on top of the Net::Server object class and
637       still have a fairly clean namespace in the hashref.
638
639       You may get and set properties in two ways.  The suggested way is to
640       access properties directly via
641
642         my $val = $self->{server}->{key1};
643
644       Accessing the properties directly will speed the server process -
645       though some would deem this as bad style.  A second way has been
646       provided for object oriented types who believe in methods.  The second
647       way consists of the following methods:
648
649         my $val = $self->get_property( 'key1' );
650         my $self->set_property( key1 => 'val1' );
651
652       Properties are allowed to be changed at any time with caution (please
653       do not undef the sock property or you will close the client
654       connection).
655

CONFIGURATION FILE

657       "Net::Server" allows for the use of a configuration file to read in
658       server parameters.  The format of this conf file is simple key value
659       pairs.  Comments and blank lines are ignored.
660
661         #-------------- file test.conf --------------
662
663         ### user and group to become
664         user        somebody
665         group       everybody
666
667         ### logging ?
668         log_file    /var/log/server.log
669         log_level   3
670         pid_file    /tmp/server.pid
671
672         ### optional syslog directive
673         ### used in place of log_file above
674         #log_file       Sys::Syslog
675         #syslog_logsock unix
676         #syslog_ident   myserver
677         #syslog_logopt  pid|cons
678
679         ### access control
680         allow       .+\.(net|com)
681         allow       domain\.com
682         deny        a.+
683         cidr_allow  127.0.0.0/8
684         cidr_allow  192.0.2.0/24
685         cidr_deny   192.0.2.4/30
686
687         ### background the process?
688         background  1
689
690         ### ports to bind (this should bind
691         ### 127.0.0.1:20205 and localhost:20204)
692         ### See Net::Server::Proto
693         host        127.0.0.1
694         port        localhost:20204
695         port        20205
696
697         ### reverse lookups ?
698         # reverse_lookups on
699
700         #-------------- file test.conf --------------
701

PROCESS FLOW

703       The process flow is written in an open, easy to override, easy to hook,
704       fashion.  The basic flow is shown below.  This is the flow of the
705       "$self->run" method.
706
707         $self->configure_hook;
708
709         $self->configure(@_);
710
711         $self->post_configure;
712
713         $self->post_configure_hook;
714
715         $self->pre_bind;
716
717         $self->bind;
718
719         $self->post_bind_hook;
720
721         $self->post_bind;
722
723         $self->pre_loop_hook;
724
725         $self->loop;
726
727         ### routines inside a standard $self->loop
728         # $self->accept;
729         # $self->run_client_connection;
730         # $self->done;
731
732         $self->pre_server_close_hook;
733
734         $self->server_close;
735
736       The server then exits.
737
738       During the client processing phase ("$self->run_client_connection"),
739       the following represents the program flow:
740
741         $self->post_accept;
742
743         $self->get_client_info;
744
745         $self->post_accept_hook;
746
747         if( $self->allow_deny
748
749             && $self->allow_deny_hook ){
750
751           $self->process_request;
752
753         }else{
754
755           $self->request_denied_hook;
756
757         }
758
759         $self->post_process_request_hook;
760
761         $self->post_process_request;
762
763         $self->post_client_connection_hook;
764
765       The process then loops and waits for the next connection.  For a more
766       in depth discussion, please read the code.
767
768       During the server shutdown phase ("$self->server_close"), the following
769       represents the program flow:
770
771         $self->close_children;  # if any
772
773         $self->post_child_cleanup_hook;
774
775         if( Restarting server ){
776            $self->restart_close_hook();
777            $self->hup_server;
778         }
779
780         $self->shutdown_sockets;
781
782         $self->server_exit;
783

MAIN SERVER METHODS

785       "$self->run"
786           This method incorporates the main process flow.  This flow is
787           listed above.
788
789           The method run may be called in any of the following ways.
790
791              MyPackage->run(port => 20201);
792
793              MyPackage->new({port => 20201})->run;
794
795              my $obj = bless {server=>{port => 20201}}, 'MyPackage';
796              $obj->run;
797
798           The ->run method should typically be the last method called in a
799           server start script (the server will exit at the end of the ->run
800           method).
801
802       "$self->configure"
803           This method attempts to read configurations from the commandline,
804           from the run method call, or from a specified conf_file (the
805           conf_file may be specified by passed in parameters, or in the
806           default_values).  All of the configured parameters are then stored
807           in the {"server"} property of the Server object.
808
809       "$self->post_configure"
810           The post_configure hook begins the startup of the server.  During
811           this method running server instances are checked for, pid_files are
812           created, log_files are created, Sys::Syslog is initialized (as
813           needed), process backgrounding occurs and the server closes STDIN
814           and STDOUT (as needed).
815
816       "$self->pre_bind"
817           This method is used to initialize all of the socket objects used by
818           the server.
819
820       "$self->bind"
821           This method actually binds to the inialized sockets (or rebinds if
822           the server has been HUPed).
823
824       "$self->post_bind"
825           During this method priveleges are dropped.  The INT, TERM, and QUIT
826           signals are set to run server_close.  Sig PIPE is set to IGNORE.
827           Sig CHLD is set to sig_chld.  And sig HUP is set to call sig_hup.
828
829           Under the Fork, PreFork, and PreFork simple personalities, these
830           signals are registered using Net::Server::SIG to allow for safe
831           signal handling.
832
833       "$self->loop"
834           During this phase, the server accepts incoming connections.  The
835           behavior of how the accepting occurs and if a child process handles
836           the connection is controlled by what type of Net::Server
837           personality the server is using.
838
839           Net::Server and Net::Server single accept only one connection at a
840           time.
841
842           Net::Server::INET runs one connection and then exits (for use by
843           inetd or xinetd daemons).
844
845           Net::Server::MultiPlex allows for one process to simultaneously
846           handle multiple connections (but requires rewriting the
847           process_request code to operate in a more "packet-like" manner).
848
849           Net::Server::Fork forks off a new child process for each incoming
850           connection.
851
852           Net::Server::PreForkSimple starts up a fixed number of processes
853           that all accept on incoming connections.
854
855           Net::Server::PreFork starts up a base number of child processes
856           which all accept on incoming connections.  The server throttles the
857           number of processes running depending upon the number of requests
858           coming in (similar to concept to how Apache controls its child
859           processes in a PreFork server).
860
861           Read the documentation for each of the types for more information.
862
863       "$self->server_close"
864           This method is called once the server has been signaled to end, or
865           signaled for the server to restart (via HUP),  or the loop method
866           has been exited.
867
868           This method takes care of cleaning up any remaining child
869           processes, setting appropriate flags on sockets (for HUPing),
870           closing up logging, and then closing open sockets.
871
872       "$self->server_exit"
873           This method is called at the end of server_close.  It calls exit,
874           but may be overridden to do other items.  At this point all
875           services should be shut down.
876

MAIN CLIENT CONNECTION METHODS

878       "$self->run_client_connection"
879           This method is run after the server has accepted and received a
880           client connection.  The full process flow is listed above under
881           PROCESS FLOWS.  This method takes care of handling each client
882           connection.
883
884       "$self->post_accept"
885           This method opens STDIN and STDOUT to the client socket.  This
886           allows any of the methods during the run_client_connection phase to
887           print directly to and read directly from the client socket.
888
889       "$self->get_client_info"
890           This method looks up information about the client connection such
891           as ip address, socket type, and hostname (as needed).
892
893       "$self->allow_deny"
894           This method uses the rules defined in the allow and deny
895           configuration parameters to determine if the ip address should be
896           accepted.
897
898       "$self->process_request"
899           This method is intended to handle all of the client communication.
900           At this point STDIN and STDOUT are opened to the client, the ip
901           address has been verified.  The server can then interact with the
902           client connection according to whatever API or protocol the server
903           is implementing.  Note that the stub implementation uses STDIN and
904           STDOUT and will not work if the no_client_stdout flag is set.
905
906           This is the main method to override.
907
908           The default method implements a simple echo server that will repeat
909           whatever is sent.  It will quit the child if "quit" is sent, and
910           will exit the server if "exit" is sent.
911
912       "$self->post_process_request"
913           This method is used to clean up the client connection and to handle
914           any parent/child accounting for the forking servers.
915

HOOKS

917       "Net::Server" provides a number of "hooks" allowing for servers layered
918       on top of "Net::Server" to respond at different levels of execution
919       without having to "SUPER" class the main built-in methods.  The
920       placement of the hooks can be seen in the PROCESS FLOW section.
921
922       Almost all of the default hook methods do nothing.  To use a hook you
923       simply need to override the method in your subclass.  For example to
924       add your own post_configure_hook you could do something like the
925       following:
926
927           package MyServer;
928
929           sub post_configure_hook {
930               my $self = shift;
931               my $prop = $self->{'server'};
932
933               # do some validation here
934           }
935
936       The following describes the hooks available in the plain Net::Server
937       class (other flavors such as Fork or PreFork have additional hooks).
938
939       "$self->configure_hook()"
940           This hook takes place immediately after the "->run()" method is
941           called.  This hook allows for setting up the object before any
942           built in configuration takes place.  This allows for custom
943           configurability.
944
945       "$self->post_configure_hook()"
946           This hook occurs just after the reading of configuration parameters
947           and initiation of logging and pid_file creation.  It also occurs
948           before the "->pre_bind()" and "->bind()" methods are called.  This
949           hook allows for verifying configuration parameters.
950
951       "$self->post_bind_hook()"
952           This hook occurs just after the bind process and just before any
953           chrooting, change of user, or change of group occurs.  At this
954           point the process will still be running as the user who started the
955           server.
956
957       "$self->pre_loop_hook()"
958           This hook occurs after chroot, change of user, and change of group
959           has occured.  It allows for preparation before looping begins.
960
961       "$self->can_read_hook()"
962           This hook occurs after a socket becomes readible on an
963           accept_multi_port request (accept_multi_port is used if there are
964           multiple bound ports to accept on, or if the "multi_port"
965           configuration parameter is set to true).  This hook is intended to
966           allow for processing of arbitrary handles added to the IO::Select
967           used for the accept_multi_port.  These handles could be added
968           during the post_bind_hook.  No internal support is added for
969           processing these handles or adding them to the IO::Socket.  Care
970           must be used in how much occurs during the can_read_hook as a long
971           response time will result in the server being susceptible to DOS
972           attacks.  A return value of true indicates that the Server should
973           not pass the readible handle on to the post_accept and
974           process_request phases.
975
976           It is generally suggested that other avenues be pursued for sending
977           messages via sockets not created by the Net::Server.
978
979       "$self->post_accept_hook()"
980           This hook occurs after a client has connected to the server.  At
981           this point STDIN and STDOUT are mapped to the client socket.  This
982           hook occurs before the processing of the request.
983
984       "$self->allow_deny_hook()"
985           This hook allows for the checking of ip and host information beyond
986           the "$self->allow_deny()" routine.  If this hook returns 1, the
987           client request will be processed, otherwise, the request will be
988           denied processing.
989
990       "$self->request_denied_hook()"
991           This hook occurs if either the "$self->allow_deny()" or
992           "$self->allow_deny_hook()" have taken place.
993
994       "$self->post_process_request_hook()"
995           This hook occurs after the processing of the request, but before
996           the client connection has been closed.
997
998       "$self->post_client_connection_hook"
999           This is one final hook that occurs at the very end of the
1000           run_client_connection method.  At this point all other methods and
1001           hooks that will run during the run_client_connection have finished
1002           and the client connection has already been closed.
1003
1004       "$self->pre_server_close_hook()"
1005           This hook occurs before the server begins shutting down.
1006
1007       "$self->write_to_log_hook"
1008           This hook handles writing to log files.  The default hook is to
1009           write to STDERR, or to the filename contained in the parameter
1010           "log_file".  The arguments passed are a log level of 0 to 4 (4
1011           being very verbose), and a log line.  If log_file is equal to
1012           "Sys::Syslog", then logging will go to Sys::Syslog and will bypass
1013           the write_to_log_hook.
1014
1015       "$self->fatal_hook"
1016           This hook occurs when the server has encountered an unrecoverable
1017           error.  Arguments passed are the error message, the package, file,
1018           and line number.  The hook may close the server, but it is
1019           suggested that it simply return and use the built in shut down
1020           features.
1021
1022       "$self->post_child_cleanup_hook"
1023           This hook occurs in the parent server process after all children
1024           have been shut down and just before the server either restarts or
1025           exits.  It is intended for additional cleanup of information.  At
1026           this point pid_files and lockfiles still exist.
1027
1028       "$self->restart_open_hook"
1029           This hook occurs if a server has been HUPed (restarted via the HUP
1030           signal.  It occurs just before reopening to the filenos of the
1031           sockets that were already opened.
1032
1033       "$self->restart_close_hook"
1034           This hook occurs if a server has been HUPed (restarted via the HUP
1035           signal.  It occurs just before restarting the server via exec.
1036

OTHER METHODS

1038       "$self->default_values"
1039           Allow for returning configuration values that will be used if no
1040           other value could be found.
1041
1042           Should return a hashref.
1043
1044               sub default_values {
1045                 return {
1046                   port => 20201,
1047                 };
1048               }
1049
1050       "$self->handle_syslog_error"
1051           Called when log_file is set to 'Sys::Syslog' and an error occurs
1052           while writing to the syslog.  It is passed two arguments, the value
1053           of $@, and an arrayref containing the arguments that were passed to
1054           the log method when the error occured.
1055
1056       "$self->log"
1057           Parameters are a log_level and a message.
1058
1059           If log_level is set to 'Sys::Syslog', the parameters may
1060           alternately be a log_level, a format string, and format string
1061           parameters.  (The second parameter is assumed to be a format string
1062           if additional arguments are passed along).  Passing arbitrary
1063           format strings to Sys::Syslog will allow the server to be
1064           vulnerable to exploit.  The server maintainer should make sure that
1065           any string treated as a format string is controlled.
1066
1067               # assuming log_file = 'Sys::Syslog'
1068
1069               $self->log(1, "My Message with %s in it");
1070               # sends "%s", "My Message with %s in it" to syslog
1071
1072               $self->log(1, "My Message with %s in it", "Foo");
1073               # sends "My Message with %s in it", "Foo" to syslog
1074
1075           If log_file is set to a file (other than Sys::Syslog), the message
1076           will be appended to the log file by calling the write_to_log_hook.
1077
1078           If the log_file is Sys::Syslog and an error occurs during write,
1079           the handle_syslog_error method will be called and passed the error
1080           exception.  The default option of handle_syslog_error is to die -
1081           but could easily be told to do nothing by using the following code
1082           in your subclassed server:
1083
1084               sub handle_syslog_error {}
1085
1086           It the log had been closed, you could attempt to reopen it in the
1087           error handler with the following code:
1088
1089               sub handle_syslog_error {
1090                 my $self = shift;
1091                 $self->open_syslog;
1092               }
1093
1094       "$self->new"
1095           As of Net::Server 0.91 there is finally a new method.  This method
1096           takes a class name and an argument hashref as parameters.  The
1097           argument hashref becomes the "server" property of the object.
1098
1099              package MyPackage;
1100              use base qw(Net::Server);
1101
1102              my $obj = MyPackage->new({port => 20201});
1103
1104              # same as
1105
1106              my $obj = bless {server => {port => 20201}}, 'MyPackage';
1107
1108       "$self->open_syslog"
1109           Called during post_configure when the log_file option is set to
1110           'Sys::Syslog'.  By default it use the parsed configuration options
1111           listed in this document.  If more custom behavior is desired, the
1112           method could be overridden and Sys::Syslog::openlog should be
1113           called with the custom parameters.
1114
1115       "$self->shutdown_sockets"
1116           This method will close any remaining open sockets.  This is called
1117           at the end of the server_close method.
1118

RESTARTING

1120       Each of the server personalities (except for INET), support restarting
1121       via a HUP signal (see "kill -l").  When a HUP is received, the server
1122       will close children (if any), make sure that sockets are left open, and
1123       re-exec using the same commandline parameters that initially started
1124       the server.  (Note: for this reason it is important that @ARGV is not
1125       modified until "->run" is called).
1126
1127       The Net::Server will attempt to find out the commandline used for
1128       starting the program.  The attempt is made before any configuration
1129       files or other arguments are processed.  The outcome of this attempt is
1130       stored using the method "->commandline".  The stored commandline may
1131       also be retrieved using the same method name.  The stored contents will
1132       undoubtedly contain Tainted items that will cause the server to die
1133       during a restart when using the -T flag (Taint mode).  As it is
1134       impossible to arbitrarily decide what is taint safe and what is not,
1135       the individual program must clean up the tainted items before doing a
1136       restart.
1137
1138         sub configure_hook{
1139           my $self = shift;
1140
1141           ### see the contents
1142           my $ref  = $self->commandline;
1143           use Data::Dumper;
1144           print Dumper $ref;
1145
1146           ### arbitrary untainting - VERY dangerous
1147           my @untainted = map {/(.+)/;$1} @$ref;
1148
1149           $self->commandline(\@untainted)
1150         }
1151

FILES

1153       The following files are installed as part of this distribution.
1154
1155           Net/Server.pm
1156           Net/Server/Fork.pm
1157           Net/Server/INET.pm
1158           Net/Server/MultiType.pm
1159           Net/Server/PreForkSimple.pm
1160           Net/Server/PreFork.pm
1161           Net/Server/Single.pm
1162           Net/Server/Daemonize.pm
1163           Net/Server/SIG.pm
1164           Net/Server/Proto.pm
1165           Net/Server/Proto/*.pm
1166

INSTALL

1168       Download and extract tarball before running these commands in its base
1169       directory:
1170
1171           perl Makefile.PL
1172           make
1173           make test
1174           make install
1175

AUTHOR

1177       Paul Seamons <paul at seamons.com>
1178

THANKS

1180       Thanks to Rob Brown (bbb at cpan.org) for help with miscellaneous
1181       concepts such as tracking down the serialized select via flock ala
1182       Apache and the reference to IO::Select making multiport servers
1183       possible.  And for researching into allowing sockets to remain open
1184       upon exec (making HUP possible).
1185
1186       Thanks to Jonathan J. Miner <miner at doit.wisc.edu> for patching a
1187       blatant problem in the reverse lookups.
1188
1189       Thanks to Bennett Todd <bet at rahul.net> for pointing out a problem in
1190       Solaris 2.5.1 which does not allow multiple children to accept on the
1191       same port at the same time.  Also for showing some sample code from
1192       Viktor Duchovni which now represents the semaphore option of the
1193       serialize argument in the PreFork server.
1194
1195       Thanks to traveler and merlyn from http://perlmonks.org for pointing me
1196       in the right direction for determining the protocol used on a socket
1197       connection.
1198
1199       Thanks to Jeremy Howard <j+daemonize at howard.fm> for numerous
1200       suggestions and for work on Net::Server::Daemonize.
1201
1202       Thanks to Vadim <vadim at hardison.net> for patches to implement
1203       parent/child communication on PreFork.pm.
1204
1205       Thanks to Carl Lewis for suggesting "-" in user names.
1206
1207       Thanks to Slaven Rezic for suggesing Reuse => 1 in Proto::UDP.
1208
1209       Thanks to Tim Watt for adding udp_broadcast to Proto::UDP.
1210
1211       Thanks to Christopher A Bongaarts for pointing out problems with the
1212       Proto::SSL implementation that currently locks around the socket accept
1213       and the SSL negotiation. See Net::Server::Proto::SSL.
1214
1215       Thanks to Alessandro Zummo for pointing out various bugs including some
1216       in configuration, commandline args, and cidr_allow.
1217
1218       Thanks to various other people for bug fixes over the years.  These and
1219       future thank-you's are available in the Changes file as well as CVS
1220       comments.
1221
1222       Thanks to Ben Cohen and tye (on Permonks) for finding and diagnosing
1223       more correct behavior for dealing with re-opening STDIN and STDOUT on
1224       the client handles.
1225
1226       Thanks to Mark Martinec for trouble shooting other problems with STDIN
1227       and STDOUT (he proposed having a flag that is now the no_client_stdout
1228       flag).
1229
1230       Thanks to David (DSCHWEI) on cpan for asking for the nofatal option
1231       with syslog.
1232
1233       Thanks to Andreas Kippnick and Peter Beckman for suggesting leaving
1234       open child connections open during a HUP (this is now available via the
1235       leave_children_open_on_hup flag).
1236
1237       Thanks to LUPE on cpan for helping patch HUP with taint on.
1238
1239       Thanks to Michael Virnstein for fixing a bug in the check_for_dead
1240       section of PreFork server.
1241
1242       Thanks to Rob Mueller for patching PreForkSimple to only open lock_file
1243       once during parent call.  This patch should be portable on systems
1244       supporting flock.  Rob also suggested not closing STDIN/STDOUT but
1245       instead reopening them to /dev/null to prevent spurious warnings.  Also
1246       suggested short circuit in post_accept if in UDP.  Also for cleaning up
1247       some of the child managment code of PreFork.
1248
1249       Thanks to Mark Martinec for suggesting additional log messages for
1250       failure during accept.
1251
1252       Thanks to Bill Nesbitt and Carlos Velasco for pointing out double
1253       decrement bug in PreFork.pm (rt #21271)
1254
1255       Thanks to John W. Krahn for pointing out glaring precended with non-
1256       parened open and ||.
1257
1258       Thanks to Ricardo Signes for pointing out setuid bug for perl 5.6.1 (rt
1259       #21262).
1260
1261       Thanks to Carlos Velasco for updating the Syslog options (rt #21265).
1262       And for additional fixes later.
1263
1264       Thanks to Steven Lembark for pointing out that no_client_stdout wasn't
1265       working with the Multiplex server.
1266
1267       Thanks to Peter Beckman for suggesting allowing Sys::SysLog keyworks be
1268       passed through the ->log method and for suggesting we allow more types
1269       of characters through in syslog_ident.  Also to Peter Beckman for
1270       pointing out that a poorly setup localhost will cause tests to hang.
1271
1272       Thanks to Curtis Wilbar for pointing out that the Fork server called
1273       post_accept_hook twice.  Changed to only let the child process call
1274       this, but added the pre_fork_hook method.
1275
1276       And just a general Thanks You to everybody who is using Net::Server or
1277       who has contributed fixes over the years.
1278
1279       Thanks to Paul Miller for some ->autoflush, FileHandle fixes.
1280
1281       Thanks to Patrik Wallstrom for suggesting handling syslog errors
1282       better.
1283
1284       Thanks again to Rob Mueller for more logic cleanup for child accounting
1285       in PreFork server.
1286
1287       Thanks to David Schweikert for suggesting handling setlogsock a little
1288       better on newer versions of Sys::Syslog (>= 0.15).
1289
1290       Thanks to Mihail Nasedkin for suggesting adding a hook that is now
1291       called post_client_connection_hook.
1292

SEE ALSO

1294       Please see also Net::Server::Fork, Net::Server::INET,
1295       Net::Server::PreForkSimple, Net::Server::PreFork,
1296       Net::Server::MultiType, Net::Server::Single
1297

TODO

1299         Improve test suite to fully cover code (using Devel::Cover).  Anybody
1300         that wanted to send me patches to the t/*.t tests that improved coverage
1301         would earn a big thank you :) (Sorry there isn't a whole lot more than that to give).
1302

AUTHOR

1304         Paul Seamons <paul at seamons.com>
1305         http://seamons.com/
1306
1307         Rob Brown <bbb at cpan.org>
1308

LICENSE

1310       This package may be distributed under the terms of either the
1311
1312         GNU General Public License
1313           or the
1314         Perl Artistic License
1315
1316       All rights reserved.
1317
1318
1319
1320perl v5.12.0                      2007-07-25                    Net::Server(3)
Impressum