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 '$_'\015\012"; # basic echo
19                   last if /quit/i;
20               }
21           }
22
23           MyPackage->run(port => 160, ipv => '*');
24
25
26           # one liner to get going quickly
27           perl -e 'use base qw(Net::Server); main->run(port => 20208)'
28
29           NOTE: beginning in Net::Server 2.005, the default value for
30                 ipv is IPv* meaning that if no host is passed, or
31                 a hostname is past, any available IPv4 and IPv6 sockets will be
32                 bound.  You can force IPv4 only by adding an ipv => 4
33                 configuration in any of the half dozen ways we let you
34                 specify it.
35

FEATURES

37           * Full IPv6 support
38           * Working SSL sockets and https (both with and without IO::Socket::SSL)
39           * Single Server Mode
40           * Inetd Server Mode
41           * Preforking Simple Mode (PreForkSimple)
42           * Preforking Managed Mode (PreFork)
43           * Forking Mode
44           * Multiplexing Mode using a single process
45           * Multi port accepts on Single, Preforking, and Forking modes
46           * Basic HTTP Daemon (supports IPv6, SSL, full apache style logs)
47           * Basic PSGI Daemon
48           * Simultaneous accept/recv on tcp/udp/unix, ssl/tcp, and IPv4/IPv6 sockets
49           * Safe signal handling in Fork/PreFork avoids perl signal trouble
50           * User customizable hooks
51           * Chroot ability after bind
52           * Change of user and group after bind
53           * Basic allow/deny access control
54           * Pluggable logging (Sys::Syslog, Log::Log4perl, log_file, STDERR, or your own)
55           * HUP able server (clean restarts via sig HUP)
56           * Graceful shutdowns (via sig QUIT)
57           * Hot deploy in Fork and PreFork modes (via sig TTIN and TTOU)
58           * Dequeue ability in all Fork and PreFork modes.
59           * Taint clean
60           * Written in Perl
61           * Protection against buffer overflow
62           * Clean process flow
63           * Extensibility
64

DESCRIPTION

66       "Net::Server" is an extensible, generic Perl server engine.
67
68       "Net::Server" attempts to be a generic server as in "Net::Daemon" and
69       "NetServer::Generic".  It includes with it the ability to run as an
70       inetd process ("Net::Server::INET"), a single connection server
71       ("Net::Server" or "Net::Server::Single"), a forking server
72       ("Net::Server::Fork"), a preforking server which maintains a constant
73       number of preforked children ("Net::Server::PreForkSimple"), or as a
74       managed preforking server which maintains the number of children based
75       on server load ("Net::Server::PreFork").  In all but the inetd type,
76       the server provides the ability to connect to one or to multiple server
77       ports.
78
79       The additional server types are made possible via "personalities" or
80       sub classes of the "Net::Server".  By moving the multiple types of
81       servers out of the main "Net::Server" class, the "Net::Server" concept
82       is easily extended to other types (in the near future, we would like to
83       add a "Thread" personality).
84
85       "Net::Server" borrows several concepts from the Apache Webserver.
86       "Net::Server" uses "hooks" to allow custom servers such as SMTP, HTTP,
87       POP3, etc. to be layered over the base "Net::Server" class.  In
88       addition the "Net::Server::PreFork" class borrows concepts of
89       min_start_servers, max_servers, and min_waiting servers.
90       "Net::Server::PreFork" also uses the concept of an flock serialized
91       accept when accepting on multiple ports (PreFork can choose between
92       flock, IPC::Semaphore, and pipe to control serialization).
93

PERSONALITIES

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

SOCKET ACCESS

180       Once started, the Net::Server will take care of binding to port and
181       waiting for connections.  Once a connection is received, the
182       Net::Server will accept on the socket and will store the result (the
183       client connection) in $self->{server}->{client}.  This property is a
184       Socket blessed into the IO::Socket classes.  UDP servers are slightly
185       different in that they will perform a recv instead of an accept.
186
187       To make programming easier, during the post_accept phase, STDIN and
188       STDOUT are opened to the client connection.  This allows for programs
189       to be written using <STDIN> and print "out\n" to print to the client
190       connection.  UDP will require using a ->send call.
191

SAMPLE CODE

193       The following is a very simple server.  The main functionality occurs
194       in the process_request method call as shown below.  Notice the use of
195       timeouts to prevent Denial of Service while reading.  (Other examples
196       of using "Net::Server" can, or will, be included with this
197       distribution).
198
199           #!/usr/bin/perl -w -T
200
201           package MyPackage;
202
203           use strict;
204           use base qw(Net::Server::PreFork); # any personality will do
205
206           MyPackage->run;
207
208           # over-ride the default echo handler
209
210           sub process_request {
211               my $self = shift;
212               eval {
213
214                   local $SIG{'ALRM'} = sub { die "Timed Out!\n" };
215                   my $timeout = 30; # give the user 30 seconds to type some lines
216
217                   my $previous_alarm = alarm($timeout);
218                   while (<STDIN>) {
219                       s/\r?\n$//;
220                       print "You said '$_'\r\n";
221                       alarm($timeout);
222                   }
223                   alarm($previous_alarm);
224
225               };
226
227               if ($@ =~ /timed out/i) {
228                   print STDOUT "Timed Out.\r\n";
229                   return;
230               }
231
232           }
233
234           1;
235
236       Playing this file from the command line will invoke a Net::Server using
237       the PreFork personality.  When building a server layer over the
238       Net::Server, it is important to use features such as timeouts to
239       prevent Denial Of Service attacks.
240
241       Net::Server comes with a built in echo server by default.  You can test
242       it out by simply running the following from the commandline:
243
244           net-server
245
246       If you wanted to try another flavor you could try
247
248           net-server PreFork
249
250       If you wanted to try out a basic HTTP server you could use
251
252           net-server HTTP
253
254       Or if you wanted to test out a CGI you are writing you could use
255
256           net-server HTTP --app ../../mycgi.cgi
257

ARGUMENTS

259       There are at least five possible ways to pass arguments to Net::Server.
260       They are passing to the new method, passing on command line, passing
261       parameters to run, using a conf file, returning values in the
262       default_values method, or configuring the values in
263       post_configure_hook.
264
265       The "options" method is used to determine which arguments the server
266       will search for and can be used to extend the parsed parameters.  Any
267       arguments found from the command line, parameters passed to run, and
268       arguments found in the conf_file will be matched against the keys of
269       the options template.  Any commandline parameters that do not match
270       will be left in place and can be further processed by the server in the
271       various hooks (by looking at @ARGV).  Arguments passed to new will
272       automatically win over any other options (this can be used if you would
273       like to disallow a user passing in other arguments).
274
275       Arguments consist of key value pairs.  On the commandline these pairs
276       follow the POSIX fashion of "--key value" or "--key=value", and also
277       "key=value".  In the conf file the parameter passing can best be shown
278       by the following regular expression:
279       ($key,$val)=~/^(\w+)\s+(\S+?)\s+$/.  Passing arguments to the run
280       method is done as follows: "<Net::Server->run(key1 =" 'val1')>>.
281       Passing arguments via a prebuilt object can best be shown in the
282       following code:
283
284           #!/usr/bin/perl -w -T
285
286           package MyPackage;
287           use strict;
288           use base qw(Net::Server);
289
290           my $server = MyPackage->new({
291               key1 => 'val1',
292           });
293
294           $server->run;
295
296       All five methods for passing arguments may be used at the same time.
297       Once an argument has been set, it is not over written if another method
298       passes the same argument.  "Net::Server" will look for arguments in the
299       following order:
300
301           1) Arguments passed to the C<new> method.
302           2) Arguments passed on command line.
303           3) Arguments passed to the C<run> method.
304           4) Arguments passed via a conf file.
305           5) Arguments set in the C<default_values> method.
306
307       Additionally the following hooks are available:
308
309           1) Arguments set in the configure_hook (occurs after new
310              but before any of the other areas are checked).
311           2) Arguments set and validated in the post_configure_hook
312              (occurs after all of the other areas are checked).
313
314       Each of these levels will override parameters of the same name
315       specified in subsequent levels.  For example, specifying --setsid=0 on
316       the command line will override a value of "setsid 1" in the conf file.
317
318       Note that the configure_hook method doesn't return values to set, but
319       is there to allow for setting up configured values before the configure
320       method is called.
321
322       Key/value pairs used by the server are removed by the configuration
323       process so that server layers on top of "Net::Server" can pass and read
324       their own parameters.
325

ADDING CUSTOM ARGUMENTS

327       It is possible to add in your own custom parameters to those parsed by
328       Net::Server.  The following code shows how this is done:
329
330           sub options {
331               my $self     = shift;
332               my $prop     = $self->{'server'};
333               my $template = shift;
334
335               # setup options in the parent classes
336               $self->SUPER::options($template);
337
338               # add a single value option
339               $prop->{'my_option'} ||= undef;
340               $template->{'my_option'} = \ $prop->{'my_option'};
341
342               # add a multi value option
343               $prop->{'an_arrayref_item'} ||= [];
344               $template->{'an_arrayref_item'} = $prop->{'an_arrayref_item'};
345           }
346
347       Overriding the "options" method allows for adding your own custom
348       fields.  A template hashref is passed in, that should then be modified
349       to contain an of your custom fields.  Fields which are intended to
350       receive a single scalar value should have a reference to the
351       destination scalar given.  Fields which are intended to receive
352       multiple values should reference the corresponding destination
353       arrayref.
354
355       You are responsible for validating your custom options once they have
356       been parsed.  The post_configure_hook is a good place to do your
357       validation.
358
359       Some emails have asked why we use this "template" method.  The idea is
360       that you are creating the data structure to store the values in, and
361       you are also creating a way to get the values into the data structure.
362       The template is the way to get the values to the servers data
363       structure.  One of the possibilities (that probably isn't used that
364       much) is that by letting you specify the mapping, you could build a
365       nested data structure - even though the passed in arguments are flat.
366       It also allows you to setup aliases to your names.
367
368       For example, a basic structure might look like this:
369
370          $prop = $self->{'server'}
371
372          $prop->{'my_custom_option'} ||= undef;
373          $prop->{'my_custom_array'}  ||= [];
374
375          $template = {
376              my_custom_option => \ $prop->{'my_custom_option'},
377              mco              => \ $prop->{'my_custom_option'}, # alias
378              my_custom_array  => $prop->{'my_custom_array'},
379              mca              => $prop->{'my_custom_array'}, # an alias
380          };
381
382          $template->{'mco2'} = $template->{'mco'}; # another way to alias
383
384       But you could also have more complex data:
385
386          $prop = $self->{'server'};
387
388          $prop->{'one_layer'} = {
389              two_layer => [
390                  undef,
391                  undef,
392              ],
393          };
394
395          $template = {
396              param1 => \ $prop->{'one_layer'}->{'two_layer'}->[0],
397              param2 => \ $prop->{'one_layer'}->{'two_layer'}->[1],
398          };
399
400       This is of course a contrived example - but it does show that you can
401       get the data from the flat passed in arguments to whatever type of
402       structure you need - with only a little bit of effort.
403

DEFAULT ARGUMENTS FOR Net::Server

405       The following arguments are available in the default "Net::Server" or
406       "Net::Server::Single" modules.  (Other personalities may use additional
407       parameters and may optionally not use parameters from the base class.)
408
409           Key               Value                    Default
410           conf_file         "filename"               undef
411
412           log_level         0-4                      2
413           log_file          (filename|Sys::Syslog
414                              |Log::Log4perl)         undef
415           log_function                               undef
416
417           port              \d+                      20203
418           host              "host"                   "*"
419           ipv               (4|6|*)                  *
420           proto             (tcp|udp|unix)           "tcp"
421           listen            \d+                      SOMAXCONN
422           ipv6_package      (IO::Socket::INET6       IO::Socket::IP
423                              |IO::Socket::IP)
424
425           ## syslog parameters (if log_file eq Sys::Syslog)
426           syslog_logsock    (native|unix|inet|udp
427                              |tcp|stream|console)    unix (on Sys::Syslog < 0.15)
428           syslog_ident      "identity"               "net_server"
429           syslog_logopt     (cons|ndelay|nowait|pid) pid
430           syslog_facility   \w+                      daemon
431
432           reverse_lookups   (1|double|double-debug)  undef
433           double_reverse_lookups  (1|debug|autofail) undef
434           allow             /regex/                  none
435           deny              /regex/                  none
436           cidr_allow        CIDR                     none
437           cidr_deny         CIDR                     none
438
439           ## daemonization parameters
440           pid_file          "filename"               undef
441           chroot            "directory"              undef
442           user              (uid|username)           "nobody"
443           group             (gid|group)              "nobody"
444           background        1                        undef
445           setsid            1                        undef
446
447           no_close_by_child (1|undef)                undef
448
449           ## See Net::Server::Proto::(TCP|UDP|UNIX|SSL|SSLeay|etc)
450           ## for more sample parameters.
451
452       conf_file
453           Filename from which to read additional key value pair arguments for
454           starting the server.  Default is undef.
455
456           There are two ways that you can specify a default location for a
457           conf_file.  The first is to pass the default value to the run
458           method as in:
459
460               MyServer->run({
461                  conf_file => '/etc/my_server.conf',
462               });
463
464           If the end user passes in --conf_file=/etc/their_server.conf then
465           the value will be overridden.
466
467           The second way to do this was added in the 0.96 version.  It uses
468           the default_values method as in:
469
470               sub default_values {
471                   return {
472                       conf_file => '/etc/my_server.conf',
473                   }
474               }
475
476           This method has the advantage of also being able to be overridden
477           in the run method.
478
479           If you do not want the user to be able to specify a conf_file at
480           all, you can pass conf_file to the new method when creating your
481           object:
482
483               MyServer->new({
484                  conf_file => '/etc/my_server.conf',
485               })->run;
486
487           If passed this way, the value passed to new will "win" over any of
488           the other passed in values.
489
490       log_level
491           Ranges from 0 to 4 in level.  Specifies what level of error will be
492           logged.  "O" means logging is off.  "4" means very verbose.  These
493           levels should be able to correlate to syslog levels.  Default is 2.
494           These levels correlate to syslog levels as defined by the following
495           key/value pairs: 0=>'err', 1=>'warning', 2=>'notice', 3=>'info',
496           4=>'debug'.
497
498       log_file
499           Name of log file or log subsystem to be written to.  If no name is
500           given and the write_to_log_hook is not overridden, log goes to
501           STDERR.  Default is undef.
502
503           The log_file may also be the name of a Net::Server pluggable
504           logging class.  Net::Server is packaged with Sys::Syslog and
505           Log::Log4perl.  If the log_file looks like a module name, it will
506           have "Net::Server::Log::" added to the front and it will then be
507           required.  The package should provide an "initialize" class method
508           that returns a single function which will be used for logging.
509           This returned function will be passed log_level, and message.
510
511           If the magic name "Sys::Syslog" is used, all logging will take
512           place via the Net::Server::Log::Sys::Syslog module.  If syslog is
513           used the parameters "syslog_logsock", "syslog_ident", and
514           "syslog_logopt",and "syslog_facility" may also be defined.  See
515           Net::Server::Log::Sys::Syslog.
516
517           If the magic name "Log::Log4perl" is used, all logging will be
518           directed to the Log4perl system.  If used, the "log4perl_conf",
519           "log4perl_poll", "log4perl_logger" may also be defined. See
520           Net::Server::Log::Log::Log4per.
521
522           If a "log_file" is given or if "setsid" is set, STDIN and STDOUT
523           will automatically be opened to /dev/null and STDERR will be opened
524           to STDOUT.  This will prevent any output from ending up at the
525           terminal.
526
527       log_function
528           Can take a coderef or method name to call when a log event occurs.
529           Will be passed the level of the log message and the log message.
530
531           Note that functions depending upon stdout will not function during
532           process_request in situations where the tie_stdout is set (such as
533           during Net::Server::HTTP).
534
535       pid_file
536           Filename to store pid of parent process.  Generally applies only to
537           forking servers.  Default is none (undef).
538
539       port
540           See Net::Server::Proto for further examples of configuration.
541
542           Local port/socket on which to bind.  If it is a low port, the
543           process must start as root.  If multiple ports are given, all will
544           be bound at server startup.  May be of the form "host:port/proto",
545           "host:port/proto/ipv", "host:port", "port/proto", or "port", where
546           host represents a hostname residing on the local box, where port
547           represents either the number of the port (eg. "80") or the service
548           designation (eg. "http"), where ipv represents the IP protocol
549           version (IPv4 or IPv6 or IPv*) and where proto represents the
550           protocol to be used. See Net::Server::Proto.  The following are
551           some valid port strings:
552
553               20203                            # port only
554               localhost:20203                  # host and port
555               localhost:http                   # localhost bound to port 80
556               localhost:20203/tcp              # host, port, protocol
557               localhost:20203/tcp/IPv*         # host, port, protocol and family
558               localhost, 20203, tcp, IPv*      # same
559               localhost | 20203 | tcp | IPv*   # same
560               localhost:20203/IPv*             # bind any configured interfaces for IPv4 or 6 (default)
561               localhost:20203/IPv4/IPv6        # bind localhost on IPv4 and 6 (fails if it cannot do both)
562
563               *:20203                          # bind all local interfaces
564
565           Additionally, when passed in the code (non-commandline, and non-
566           config), the port may be passed as a hashref or array hashrefs of
567           information:
568
569               port => {
570                   host  => 'localhost',
571                   port  => '20203',
572                   ipv   => 6,     # IPv6 only
573                   proto => 'udp', # UDP protocol
574               }
575
576               port => [{
577                   host  => '*',
578                   port  => '20203',
579                   ipv   => 4,     # IPv4 only
580                   proto => 'tcp', # (default)
581               }, {
582                   host  => 'localhost',
583                   port  => '20204',
584                   ipv   => '*',      # default - all IPv4 and IPv6 interfaces tied to localhost
585                   proto => 'ssleay', # or ssl - Using SSL
586               }],
587
588           An explicit host given in a port specification overrides a default
589           binding address (a "host" setting, see below).  The host part may
590           be enclosed in square brackets, but when it is a numerical IPv6
591           address it should be enclosed in square brackets to avoid ambiguity
592           in parsing a port number, e.g.: "[::1]:80".  However you could also
593           use pipes, white space, or commas to separate these.  Note that
594           host and port number must come first.
595
596           If the protocol is not specified, proto will default to the "proto"
597           specified in the arguments.  If "proto" is not specified there it
598           will default to "tcp".  If host is not specified, host will default
599           to "host" specified in the arguments.  If "host" is not specified
600           there it will default to "*".  Default port is 20203.
601           Configuration passed to new or run may be either a scalar
602           containing a single port number or an arrayref of ports.  If "ipv"
603           is not specified it will default to "*" (Any resolved addresses
604           under IPv4 or IPv6).
605
606           If you are working with unix sockets, you may also specify
607           "socket_file|unix" or "socket_file|type|unix" where type is
608           SOCK_DGRAM or SOCK_STREAM.
609
610           On systems that support it, a port value of 0 may be used to ask
611           the OS to auto-assign a port.  The value of the auto-assigned port
612           will be stored in the NS_port property of the
613           Net::Server::Proto::TCP object and is also available in the
614           sockport method.  When the server is processing a request, the
615           $self->{server}->{sockport} property contains the port that was
616           connected through.
617
618       host
619           Local host or addr upon which to bind port.  If a value of '*' is
620           given, the server will bind that port on all available addresses on
621           the box.  The "host" argument provides a default local host address
622           if the "port" argument omits a host specification.  See
623           Net::Server::Proto. See IO::Socket.  Configuration passed to new or
624           run may be either a scalar containing a single host or an arrayref
625           of hosts - if the hosts array is shorter than the ports array, the
626           last host entry will be used to augment the hosts array to the size
627           of the ports array.
628
629           If an IPv4 address is passed, an IPv4 socket will be created.  If
630           an IPv6 address is passed, an IPv6 socket will be created.  If a
631           hostname is given, Net::Server will look at the value of ipv
632           (default IPv4) to determine which type of socket to create.
633           Optionally the ipv specification can be passed as part of the
634           hostname.
635
636               host => "127.0.0.1",  # an IPv4 address
637
638               host => "::1",        # an IPv6 address
639
640               host => 'localhost',  # addresses matched by localhost (default any IPv4 and/or IPv6)
641
642               host => 'localhost/IPv*',  # same
643
644               ipv  => 6,
645               host => 'localhost',  # addresses matched by localhost (IPv6)
646
647               ipv  => 4,
648               host => 'localhost',  # addresses matched by localhost (IPv4)
649
650               ipv  => 'IPv4 IPv6',
651               host => 'localhost',  # addresses matched by localhost (requires IPv6 and IPv4)
652
653               host => '*',          # any local interfaces (any IPv6 or IPv4)
654
655               host => '*/IPv*',     # same (any IPv6 or IPv4)
656
657               ipv  => 4,
658               host => '*',          # any local IPv4 interfaces
659
660       proto
661           See Net::Server::Proto.  Protocol to use when binding ports.  See
662           IO::Socket.  As of release 2.0, Net::Server supports tcp, udp, and
663           unix, unixdgram, ssl, and ssleay.  Other types will need to be
664           added later (or custom modules extending the Net::Server::Proto
665           class may be used).  Configuration passed to new or run may be
666           either a scalar containing a single proto or an arrayref of protos
667           - if the protos array is shorter than the ports array, the last
668           proto entry will be used to augment the protos array to the size of
669           the ports array.
670
671           Additionally the proto may also contain the ipv specification.
672
673       ipv (IPv4 and IPv6)
674           See Net::Server::Proto.
675
676           IPv6 is now available under Net::Server.  It will be used
677           automatically if an IPv6 address is passed, or if the ipv is set
678           explicitly to IPv6, or if ipv is left as the default value of IPv*.
679           This is a significant change from version 2.004 and earlier where
680           the default value was IPv4.  However, the previous behavior led to
681           confusion on IPv6 only hosts, and on hosts that only had IPv6
682           entries for a local hostname.  Trying to pass an IPv4 address when
683           ipv is set to 6 (only 6 - not * or 4) will result in an error.
684
685               localhost:20203 # will use IPv6 if there is a corresponding entry for localhost
686                               # it will also use IPv4 if there is a corresponding v4 entry for localhost
687
688               localhost:20203:IPv*  # same (default)
689
690               localhost:20203:IPv6  # will use IPv6
691
692               [::1]:20203           # will use IPv6 (IPv6 style address)
693
694               localhost:20203:IPv4  # will use IPv4
695
696               127.0.0.1:20203       # will use IPv4 (IPv4 style address
697
698               localhost:20203:IPv4:IPv6 # will bind to both v4 and v6 - fails otherwise
699
700               # or as a hashref as
701               port => {
702                   host => "localhost",
703                   ipv  => 6, # only binds IPv6
704               }
705
706               port => {
707                   host => "localhost",
708                   ipv  => 4, # only binds IPv4
709               }
710
711               port => {
712                   host => "::1",
713                   ipv  => "IPv6", # same as passing "6"
714               }
715
716               port => {
717                   host => "localhost/IPv*",       # any IPv4 or IPv6
718               }
719
720               port => {
721                   host => "localhost IPv4 IPv6",  # must create both
722               }
723
724           In many proposed Net::Server solutions, IPv* was enabled by
725           default.  For versions 2.000 through 2.004, the previous default of
726           IPv4 was used.  We have attempted to make it easy to set IPv4,
727           IPv6, or IPv*.  If you do not want or need IPv6, simply set ipv to
728           4, pass IPv4 along in the port specification, set $ENV{'IPV'}=4;
729           before running the server, set $ENV{'NO_IPV6'}, or uninstall
730           IO::Socket::IP and/or IO::Socket::INET6.
731
732           On my local box the following command results in the following
733           output:
734
735               perl -e 'use base qw(Net::Server); main->run(host => "localhost")'
736
737               Resolved [localhost]:20203 to [::1]:20203, IPv6
738               Resolved [localhost]:20203 to [127.0.0.1]:20203, IPv4
739               Binding to TCP port 20203 on host ::1 with IPv6
740               Binding to TCP port 20203 on host 127.0.0.1 with IPv4
741
742           My local box has IPv6 enabled and there are entries for localhost
743           on both IPv6 ::1 and IPv4 127.0.0.1.  I could also choose to
744           explicitly bind ports rather than depending upon ipv => "*" to
745           resolve them for me as in the following:
746
747               perl -e 'use base qw(Net::Server); main->run(port => [20203,20203], host => "localhost", ipv => [4,6])'
748
749               Binding to TCP port 20203 on host localhost with IPv4
750               Binding to TCP port 20203 on host localhost with IPv6
751
752           There is a special case of using host => "*" as well as ipv => "*".
753           The Net::Server::Proto::_bindv6only method is used to check the
754           system setting for "sysctl -n net.ipv6.bindv6only" (or
755           net.inet6.ip6.v6only).  If this setting is false, then an IPv6
756           socket will listen for the corresponding IPv4 address.  For example
757           the address [::] (IPv6 equivalent of INADDR_ANY) will also listen
758           for 0.0.0.0.  The address ::FFFF:127.0.0.1 (IPv6) would also listen
759           to 127.0.0.1 (IPv4).  In this case, only one socket will be created
760           because it will handle both cases (an error is returned if an
761           attempt is made to listen to both addresses when bindv6only is
762           false).
763
764           However, if net.ipv6.bindv6only (or equivalent) is true, then a
765           hostname (such as *) resolving to both a IPv4 entry as well as an
766           IPv6 will result in both an IPv4 socket as well as an IPv6 socket.
767
768           On my linux box which defaults to net.ipv6.bindv6only=0, the
769           following is output.
770
771               perl -e 'use base qw(Net::Server); main->run(host => "*")'
772
773               Resolved [*]:8080 to [::]:8080, IPv6
774               Not including resolved host [0.0.0.0] IPv4 because it will be handled by [::] IPv6
775               Binding to TCP port 8080 on host :: with IPv6
776
777           If I issue a "sudo /sbin/sysctl -w net.ipv6.bindv6only=1", the
778           following is output.
779
780               perl -e 'use base qw(Net::Server); main->run(host => "*")'
781
782               Resolved [*]:8080 to [0.0.0.0]:8080, IPv4
783               Resolved [*]:8080 to [::]:8080, IPv6
784               Binding to TCP port 8080 on host 0.0.0.0 with IPv4
785               Binding to TCP port 8080 on host :: with IPv6
786
787           BSD differs from linux and generally defaults to
788           net.inet6.ip6.v6only=0.  If it cannot be determined on your OS, it
789           will default to false and the log message will change from "it will
790           be handled" to "it should be handled" (if you have a non-resource
791           intensive way to check on your platform, feel free to email me).
792           Be sure to check the logs as you test your server to make sure you
793           have bound the ports you desire.  You can always pass in individual
794           explicit IPv4 and IPv6 port specifications if you need.  For
795           example, if your system has both IPv4 and IPv6 interfaces but you'd
796           only like to bind to IPv6 entries, then you should use a hostname
797           of [::] instead of [*].
798
799           If bindv6only (or equivalent) is false, and you receive an IPv4
800           connection on a bound IPv6 port, the textual representation of the
801           peer's IPv4 address will typically be in a form of an IPv4-mapped
802           IPv6 addresses, e.g. "::FFFF:127.0.0.1" .
803
804           The ipv parameter was chosen because it does not conflict with any
805           other existing usage, it is very similar to ipv4 or ipv6, it allows
806           for user code to not need to know about Socket::AF_INET or
807           Socket6::AF_INET6 or Socket::AF_UNSPEC, and it is short.
808
809       listen
810           See IO::Socket.  Not used with udp protocol (or UNIX SOCK_DGRAM).
811
812       ipv6_package
813           Net::Server::Proto will try to determine the appropriate socket
814           class to use if a v6 socket is needed.  It will default to trying
815           IO::Socket::IP first, and then IO::Socket::INET6.  Specifying this
816           package allows for a specific package to be used (note that
817           IO::Socket::SSL used by Proto::SSL does its own ipv6 socket package
818           determination).
819
820       reverse_lookups
821           Specify whether to lookup the hostname of the connected IP.
822           Information is cached in server object under "peerhost" property.
823           Default is to not use reverse_lookups (undef).
824
825           Can be set to the values "double", "double-detail", "double-
826           autofail", or "double-debug" to set double_reverse_lookups.
827
828       double_reverse_lookups
829           If set, also sets reverse_lookups.
830
831           Same as setting reverse_lookups to "double".  Looks up the IPs that
832           the hostname resolves to to make sure the connection ip is one of
833           those ips.
834
835           Sets peerhost_rev as a hashref of ip addresses the name resolved to
836           during get_client_info.
837
838           If double_reverse_lookups is set, the double_reverse_lookup method
839           is called during the allow_deny method.  The double_reverse_lookup
840           method is passed:
841
842               addr  - the IPv4 or IPv6 address
843               host  - the hostname the addr resolved to
844               addrs - the hashref of ip addresses the host resolved to
845               orig  - the original unfiltered addr
846
847           Makes allow_deny return false if there is no hostname, no reverse
848           ips, or if one of the ip addrs does not match the connection ip
849           addr.  Sends a log level 3 message.
850
851           Can set double_reverse_lookups to one of the following to adjust
852           logging:
853
854               detail   - add addrs to the failure messages
855               autofail - fail on every connection and log
856               debug    - log address information (but not fail) for successful connections
857
858           The following one liners can help with debugging:
859
860               net-server HTTP --reverse_lookups=double-debug --log_level=3
861               # curl localhost:8080 in other window
862
863               2022/11/30-22:16:45 CONNECT TCP Peer: "[::ffff:127.0.0.1]:44766" (localhost)  Local: "[::ffff:127.0.0.1]:8080"
864               2022/11/30-22:16:45 Double reverse debug:  addr: 127.0.0.1,  host: localhost,  addrs: (127.0.0.1),  orig_addr: ::ffff:127.0.0.1
865
866           The double_reverse_lookup is called before running any allow/deny
867           rules.
868
869       allow/deny
870           May be specified multiple times.  Contains regex to compare to
871           incoming peeraddr or peerhost (if reverse_lookups has been
872           enabled).  If allow or deny options are given, the incoming client
873           must match an allow and not match a deny or the client connection
874           will be closed.  Defaults to empty array refs.
875
876       cidr_allow/cidr_deny
877           May be specified multiple times.  Contains a CIDR block to compare
878           to incoming peeraddr.  If cidr_allow or cidr_deny options are
879           given, the incoming client must match a cidr_allow and not match a
880           cidr_deny or the client connection will be closed.  Defaults to
881           empty array refs.
882
883       chroot
884           Directory to chroot to after bind process has taken place and the
885           server is still running as root.  Defaults to undef.
886
887       user
888           Userid or username to become after the bind process has occurred.
889           Defaults to "nobody."  If you would like the server to run as root,
890           you will have to specify "user" equal to "root".
891
892       group
893           Groupid or groupname to become after the bind process has occurred.
894           Defaults to "nobody."  If you would like the server to run as root,
895           you will have to specify "group" equal to "root".
896
897       background
898           Specifies whether or not the server should fork after the bind
899           method to release itself from the command line.  Defaults to undef.
900           Process will also background if "setsid" is set.
901
902       setsid
903           Specifies whether or not the server should fork after the bind
904           method to release itself from the command line and then run the
905           POSIX::setsid() command to truly daemonize.  Defaults to undef.  If
906           a "log_file" is given or if "setsid" is set, STDIN and STDOUT will
907           automatically be opened to /dev/null and STDERR will be opened to
908           STDOUT.  This will prevent any output from ending up at the
909           terminal.
910
911       no_close_by_child
912           Boolean.  Specifies whether or not a forked child process has
913           permission or not to shutdown the entire server process.  If set to
914           1, the child may NOT signal the parent to shutdown all children.
915           Default is undef (not set).
916
917       no_client_stdout
918           Boolean.  Default undef (not set).  Specifies that STDIN and STDOUT
919           should not be opened on the client handle once a connection has
920           been accepted.  By default the Net::Server will open STDIN and
921           STDOUT on the client socket making it easier for many types of
922           scripts to read directly from and write directly to the socket
923           using normal print and read methods.  Disabling this is useful on
924           clients that may be opening their own connections to STDIN and
925           STDOUT.
926
927           This option has no affect on STDIN and STDOUT which has a magic
928           client property that is tied to the already open STDIN and STDOUT.
929
930       leave_children_open_on_hup
931           Boolean.  Default undef (not set).  If set, the parent will not
932           attempt to close child processes if the parent receives a SIG HUP.
933           The parent will rebind the open port and begin tracking a fresh set
934           of children.
935
936           Children of a Fork server will exit after their current request.
937           Children of a Prefork type server will finish the current request
938           and then exit.
939
940           Note - the newly restarted parent will start up a fresh set of
941           servers on fork servers.  The new parent will attempt to keep track
942           of the children from the former parent but custom communication
943           channels (open pipes from the child to the old parent) will no
944           longer be available to the old child processes.  New child
945           processes will still connect properly to the new parent.
946
947       sig_passthrough
948           Default none.  Allow for passing requested signals through to
949           children.  Takes a single signal name, a comma separated list of
950           names, or an arrayref of signal names.  It first sends the signals
951           to the children before calling any currently registered signal by
952           that name.
953
954       tie_client_stdout
955           Default undef.  If set will use Net::Server::TiedHandle tied
956           interface for STDIN and STDOUT.  This interface allows SSL and
957           SSLEAY to work.  It also allows for intercepting read and write via
958           the tied_stdin_callback and tied_stdout_callback.
959
960       tied_stdin_callback
961           Default undef.  Called during a read of STDIN data if
962           tie_client_stdout has been set, or if the client handle's
963           tie_stdout method returns true.  It is passed the client
964           connection, the name of the method that would be called, and the
965           arguments that are being passed.  The callback is then responsible
966           for calling that method on the handle or for performing some other
967           input operation.
968
969       tied_stdout_callback
970           Default undef.  Called during a write of data to STDOUT if
971           tie_client_stdout has been set, or if the client handle's
972           tie_stdout method returns true.  It is passed the client
973           connection, the name of the method that would be called, and the
974           arguments that are being passed.  The callback is then responsible
975           for calling that method on the handle or for performing some other
976           output operation.
977

PROPERTIES

979       All of the "ARGUMENTS" listed above become properties of the server
980       object under the same name.  These properties, as well as other
981       internal properties, are available during hooks and other method calls.
982
983       The structure of a Net::Server object is shown below:
984
985           $self = bless({
986               server => {
987                   key1 => 'val1',
988                   # more key/vals
989               },
990           }, 'Net::Server');
991
992       This structure was chosen so that all server related properties are
993       grouped under a single key of the object hashref.  This is so that
994       other objects could layer on top of the Net::Server object class and
995       still have a fairly clean namespace in the hashref.
996
997       You may get and set properties in two ways.  The suggested way is to
998       access properties directly via
999
1000           my $val = $self->{server}->{key1};
1001
1002       Accessing the properties directly will speed the server process -
1003       though some would deem this as bad style.  A second way has been
1004       provided for object oriented types who believe in methods.  The second
1005       way consists of the following methods:
1006
1007           my $val = $self->get_property( 'key1' );
1008           my $self->set_property( key1 => 'val1' );
1009
1010       Properties are allowed to be changed at any time with caution (please
1011       do not undef the sock property or you will close the client
1012       connection).
1013

CONFIGURATION FILE

1015       "Net::Server" allows for the use of a configuration file to read in
1016       server parameters.  The format of this conf file is simple key value
1017       pairs.  Comments and blank lines are ignored.
1018
1019           #-------------- file test.conf --------------
1020
1021           ### user and group to become
1022           user        somebody
1023           group       everybody
1024
1025           # logging ?
1026           log_file    /var/log/server.log
1027           log_level   3
1028           pid_file    /tmp/server.pid
1029
1030           # optional syslog directive
1031           # used in place of log_file above
1032           #log_file       Sys::Syslog
1033           #syslog_logsock unix
1034           #syslog_ident   myserver
1035           #syslog_logopt  pid|cons
1036
1037           # access control
1038           allow       .+\.(net|com)
1039           allow       domain\.com
1040           deny        a.+
1041           cidr_allow  127.0.0.0/8
1042           cidr_allow  192.0.2.0/24
1043           cidr_deny   192.0.2.4/30
1044
1045           # background the process?
1046           background  1
1047
1048           # ports to bind (this should bind
1049           # 127.0.0.1:20205 on IPv6 and
1050           # localhost:20204 on IPv4)
1051           # See Net::Server::Proto
1052           host        127.0.0.1
1053           ipv         IPv6
1054           port        localhost:20204/IPv4
1055           port        20205
1056
1057           # reverse lookups ?
1058           # reverse_lookups on
1059
1060         #-------------- file test.conf --------------
1061

PROCESS FLOW

1063       The process flow is written in an open, easy to override, easy to hook,
1064       fashion.  The basic flow is shown below.  This is the flow of the
1065       "$self->run" method.
1066
1067           $self->configure_hook;
1068
1069           $self->configure(@_);
1070
1071           $self->post_configure;
1072
1073           $self->post_configure_hook;
1074
1075           $self->pre_bind;
1076
1077           $self->bind;
1078
1079           $self->post_bind_hook;
1080
1081           $self->post_bind;
1082
1083           $self->pre_loop_hook;
1084
1085           $self->loop;
1086
1087           ### routines inside a standard $self->loop
1088           # $self->accept;
1089           # $self->run_client_connection;
1090           # $self->done;
1091
1092           $self->pre_server_close_hook;
1093
1094           $self->server_close;
1095
1096       The server then exits.
1097
1098       During the client processing phase ("$self->run_client_connection"),
1099       the following represents the program flow:
1100
1101           $self->post_accept;
1102
1103           $self->get_client_info;
1104
1105           $self->post_accept_hook;
1106
1107           if ($self->allow_deny
1108               && $self->allow_deny_hook) {
1109
1110               $self->process_request;
1111
1112           } else {
1113
1114               $self->request_denied_hook;
1115
1116           }
1117
1118           $self->post_process_request_hook;
1119
1120           $self->post_process_request;
1121
1122           $self->post_client_connection_hook;
1123
1124       The allow_deny method calls $self->double_reverse_lookup if
1125       double_reverse_lookups are enabled.
1126
1127       The process then loops and waits for the next connection.  For a more
1128       in depth discussion, please read the code.
1129
1130       During the server shutdown phase ("$self->server_close"), the following
1131       represents the program flow:
1132
1133           $self->close_children;  # if any
1134
1135           $self->post_child_cleanup_hook;
1136
1137           if (Restarting server) {
1138               $self->restart_close_hook();
1139               $self->hup_server;
1140           }
1141
1142           $self->shutdown_sockets;
1143
1144           $self->server_exit;
1145

MAIN SERVER METHODS

1147       "$self->run"
1148           This method incorporates the main process flow.  This flow is
1149           listed above.
1150
1151           The method run may be called in any of the following ways.
1152
1153                MyPackage->run(port => 20201);
1154
1155                MyPackage->new({port => 20201})->run;
1156
1157                my $obj = bless {server=>{port => 20201}}, 'MyPackage';
1158                $obj->run;
1159
1160           The ->run method should typically be the last method called in a
1161           server start script (the server will exit at the end of the ->run
1162           method).
1163
1164       "$self->configure"
1165           This method attempts to read configurations from the commandline,
1166           from the run method call, or from a specified conf_file (the
1167           conf_file may be specified by passed in parameters, or in the
1168           default_values).  All of the configured parameters are then stored
1169           in the {"server"} property of the Server object.
1170
1171       "$self->post_configure"
1172           The post_configure hook begins the startup of the server.  During
1173           this method running server instances are checked for, pid_files are
1174           created, log_files are created, Sys::Syslog is initialized (as
1175           needed), process backgrounding occurs and the server closes STDIN
1176           and STDOUT (as needed).
1177
1178       "$self->pre_bind"
1179           This method is used to initialize all of the socket objects used by
1180           the server.
1181
1182       "$self->bind"
1183           This method actually binds to the initialized sockets (or rebinds
1184           if the server has been HUPed).
1185
1186       "$self->post_bind"
1187           During this method privileges are dropped.  The INT, TERM, and QUIT
1188           signals are set to run server_close.  Sig PIPE is set to IGNORE.
1189           Sig CHLD is set to sig_chld.  And sig HUP is set to call sig_hup.
1190
1191           Under the Fork, PreFork, and PreFork simple personalities, these
1192           signals are registered using Net::Server::SIG to allow for safe
1193           signal handling.
1194
1195       "$self->loop"
1196           During this phase, the server accepts incoming connections.  The
1197           behavior of how the accepting occurs and if a child process handles
1198           the connection is controlled by what type of Net::Server
1199           personality the server is using.
1200
1201           Net::Server and Net::Server single accept only one connection at a
1202           time.
1203
1204           Net::Server::INET runs one connection and then exits (for use by
1205           inetd or xinetd daemons).
1206
1207           Net::Server::MultiPlex allows for one process to simultaneously
1208           handle multiple connections (but requires rewriting the
1209           process_request code to operate in a more "packet-like" manner).
1210
1211           Net::Server::Fork forks off a new child process for each incoming
1212           connection.
1213
1214           Net::Server::PreForkSimple starts up a fixed number of processes
1215           that all accept on incoming connections.
1216
1217           Net::Server::PreFork starts up a base number of child processes
1218           which all accept on incoming connections.  The server throttles the
1219           number of processes running depending upon the number of requests
1220           coming in (similar to concept to how Apache controls its child
1221           processes in a PreFork server).
1222
1223           Read the documentation for each of the types for more information.
1224
1225       "$self->server_close"
1226           This method is called once the server has been signaled to end, or
1227           signaled for the server to restart (via HUP), or the loop method
1228           has been exited.
1229
1230           This method takes care of cleaning up any remaining child
1231           processes, setting appropriate flags on sockets (for HUPing),
1232           closing up logging, and then closing open sockets.
1233
1234           Can optionally be passed an exit value that will be passed to the
1235           server_exit call.
1236
1237       "$self->server_exit"
1238           This method is called at the end of server_close.  It calls exit,
1239           but may be overridden to do other items.  At this point all
1240           services should be shut down.
1241
1242           Can optionally be passed an exit value that will be passed to the
1243           exit call.
1244

MAIN CLIENT CONNECTION METHODS

1246       "$self->run_client_connection"
1247           This method is run after the server has accepted and received a
1248           client connection.  The full process flow is listed above under
1249           PROCESS FLOWS.  This method takes care of handling each client
1250           connection.
1251
1252       "$self->post_accept"
1253           This method opens STDIN and STDOUT to the client socket.  This
1254           allows any of the methods during the run_client_connection phase to
1255           print directly to and read directly from the client socket.
1256
1257       "$self->get_client_info"
1258           This method looks up information about the client connection such
1259           as ip address, socket type, and hostname (as needed).
1260
1261           Sets the following in $self->{'server'} (note that these names do
1262           not necessarily correspond to the names of the IO::Socket::
1263           libraries):
1264
1265               sockaddr     - Human IP address that was connected to
1266               sockport     - Local port that was connected to
1267               peeraddr     - Human IP address of the remote source (either IPv6 or IPv4)
1268               peerport     - Source port of the connection
1269               peerhost     - IP Address resolved to hostname (if possible)
1270               peerhost_rev - Hashref of ips of the reverse lookup of the peerhost - only set if double_reverse_lookups
1271
1272       "$self->allow_deny"
1273           This method uses the rules defined in the allow and deny
1274           configuration parameters to determine if the ip address should be
1275           accepted.
1276
1277       "$self->double_reverse_lookup"
1278           Called if the double_reverse_lookups value is set or
1279           reverse_lookups is set to "double".  Uses peerhost_rev hashref ips
1280           to verify that the connection ip is valid for the hostname.  See
1281           the double_reverse_lookups configuration.
1282
1283       "$self->process_request"
1284           This method is intended to handle all of the client communication.
1285           At this point STDIN and STDOUT are opened to the client, the ip
1286           address has been verified.  The server can then interact with the
1287           client connection according to whatever API or protocol the server
1288           is implementing.  Note that the stub implementation uses STDIN and
1289           STDOUT and will not work if the no_client_stdout flag is set.
1290
1291           This is the main method to override.
1292
1293           The default method implements a simple echo server that will repeat
1294           whatever is sent.  It will quit the child if "quit" is sent, and
1295           will exit the server if "exit" is sent.
1296
1297           As of version 2.000, the client handle is passed as an argument.
1298
1299       "$self->post_process_request"
1300           This method is used to clean up the client connection and to handle
1301           any parent/child accounting for the forking servers.
1302

HOOKS

1304       "Net::Server" provides a number of "hooks" allowing for servers layered
1305       on top of "Net::Server" to respond at different levels of execution
1306       without having to "SUPER" class the main built-in methods.  The
1307       placement of the hooks can be seen in the PROCESS FLOW section.
1308
1309       Almost all of the default hook methods do nothing.  To use a hook you
1310       simply need to override the method in your subclass.  For example to
1311       add your own post_configure_hook you could do something like the
1312       following:
1313
1314           package MyServer;
1315
1316           sub post_configure_hook {
1317               my $self = shift;
1318               my $prop = $self->{'server'};
1319
1320               # do some validation here
1321           }
1322
1323       The following describes the hooks available in the plain Net::Server
1324       class (other flavors such as Fork or PreFork have additional hooks).
1325
1326       "$self->configure_hook()"
1327           This hook takes place immediately after the "->run()" method is
1328           called.  This hook allows for setting up the object before any
1329           built in configuration takes place.  This allows for custom
1330           configurability.
1331
1332       "$self->post_configure_hook()"
1333           This hook occurs just after the reading of configuration parameters
1334           and initiation of logging and pid_file creation.  It also occurs
1335           before the "->pre_bind()" and "->bind()" methods are called.  This
1336           hook allows for verifying configuration parameters.
1337
1338       "$self->post_bind_hook()"
1339           This hook occurs just after the bind process and just before any
1340           chrooting, change of user, or change of group occurs.  At this
1341           point the process will still be running as the user who started the
1342           server.
1343
1344       "$self->pre_loop_hook()"
1345           This hook occurs after chroot, change of user, and change of group
1346           has occurred.  It allows for preparation before looping begins.
1347
1348       "$self->can_read_hook()"
1349           This hook occurs after a socket becomes readable on an
1350           accept_multi_port request (accept_multi_port is used if there are
1351           multiple bound ports to accept on, or if the "multi_port"
1352           configuration parameter is set to true).  This hook is intended to
1353           allow for processing of arbitrary handles added to the IO::Select
1354           used for the accept_multi_port.  These handles could be added
1355           during the post_bind_hook.  No internal support is added for
1356           processing these handles or adding them to the IO::Socket.  Care
1357           must be used in how much occurs during the can_read_hook as a long
1358           response time will result in the server being susceptible to DOS
1359           attacks.  A return value of true indicates that the Server should
1360           not pass the readable handle on to the post_accept and
1361           process_request phases.
1362
1363           It is generally suggested that other avenues be pursued for sending
1364           messages via sockets not created by the Net::Server.
1365
1366       "$self->post_accept_hook()"
1367           This hook occurs after a client has connected to the server.  At
1368           this point STDIN and STDOUT are mapped to the client socket.  This
1369           hook occurs before the processing of the request.
1370
1371       "$self->allow_deny_hook()"
1372           This hook allows for the checking of ip and host information beyond
1373           the "$self->allow_deny()" routine.  If this hook returns 1, the
1374           client request will be processed, otherwise, the request will be
1375           denied processing.
1376
1377           As of version 2.000, the client connection is passed as an
1378           argument.
1379
1380       "$self->request_denied_hook()"
1381           This hook occurs if either the "$self->allow_deny()" or
1382           "$self->allow_deny_hook()" have taken place.
1383
1384       "$self->post_process_request_hook()"
1385           This hook occurs after the processing of the request, but before
1386           the client connection has been closed.
1387
1388       "$self->post_client_connection_hook"
1389           This is one final hook that occurs at the very end of the
1390           run_client_connection method.  At this point all other methods and
1391           hooks that will run during the run_client_connection have finished
1392           and the client connection has already been closed.
1393
1394           item "$self->other_child_died_hook($pid)"
1395
1396           Net::Server takes control of signal handling and child process
1397           cleanup; this makes it difficult to tell when a child process
1398           terminates if that child process was not started by Net::Server
1399           itself.  If Net::Server notices another child process dying that it
1400           did not start, it will fire this hook with the PID of the
1401           terminated process.
1402
1403       "$self->pre_server_close_hook()"
1404           This hook occurs before the server begins shutting down.
1405
1406       "$self->write_to_log_hook"
1407           This hook handles writing to log files.  The default hook is to
1408           write to STDERR, or to the filename contained in the parameter
1409           "log_file".  The arguments passed are a log level of 0 to 4 (4
1410           being very verbose), and a log line.  If log_file is equal to
1411           "Sys::Syslog", then logging will go to Sys::Syslog and will bypass
1412           the write_to_log_hook.
1413
1414       "$self->fatal_hook"
1415           This hook occurs when the server has encountered an unrecoverable
1416           error.  Arguments passed are the error message, the package, file,
1417           and line number.  The hook may close the server, but it is
1418           suggested that it simply return and use the built in shut down
1419           features.
1420
1421       "$self->post_child_cleanup_hook"
1422           This hook occurs in the parent server process after all children
1423           have been shut down and just before the server either restarts or
1424           exits.  It is intended for additional cleanup of information.  At
1425           this point pid_files and lockfiles still exist.
1426
1427       "$self->restart_open_hook"
1428           This hook occurs if a server has been HUPed (restarted via the HUP
1429           signal.  It occurs just before reopening to the filenos of the
1430           sockets that were already opened.
1431
1432       "$self->restart_close_hook"
1433           This hook occurs if a server has been HUPed (restarted via the HUP
1434           signal.  It occurs just before restarting the server via exec.
1435
1436       "$self->child_init_hook()"
1437           This hook is called during the forking servers.  It is also called
1438           during run_dequeue.  It runs just after the fork and after signals
1439           have been cleaned up.  If it is a dequeue process, the string
1440           'dequeue' will be passed as an argument.
1441
1442           If your child processes will be needing random numbers, this hook
1443           is a good location to initialize srand (forked processes maintain
1444           the same random seed unless changed).
1445
1446               sub child_init_hook {
1447                   # from perldoc -f srand
1448                   srand(time ^ $$ ^ unpack "%L*", `ps axww | gzip -f`);
1449               }
1450
1451       "$self->pre_fork_hook()"
1452           Similar to the child_init_hook, but occurs just before the fork.
1453
1454       "$self->register_child($pid, $type)"
1455           Called by parent process when a child has been forked.  Type will
1456           be one of dequeue, fork, prefork, or preforksimple depending on
1457           where the child was created.
1458
1459       "$self->child_finish_hook()"
1460           Similar to the child_init_hook, but ran when the forked process is
1461           about to finish up.
1462

OTHER METHODS

1464       "$self->default_values"
1465           Allow for returning configuration values that will be used if no
1466           other value could be found.
1467
1468           Should return a hashref.
1469
1470               sub default_values {
1471                   return {
1472                       port => 20201,
1473                   };
1474               }
1475
1476       "$self->handle_syslog_error"
1477           Called when log_file is set to 'Sys::Syslog' and an error occurs
1478           while writing to the syslog.  It is passed two arguments, the value
1479           of $@, and an arrayref containing the arguments that were passed to
1480           the log method when the error occurred.
1481
1482       "$self->log"
1483           Parameters are a log_level and a message.
1484
1485           If log_level is set to 'Sys::Syslog', the parameters may
1486           alternately be a log_level, a format string, and format string
1487           parameters.  (The second parameter is assumed to be a format string
1488           if additional arguments are passed along).  Passing arbitrary
1489           format strings to Sys::Syslog will allow the server to be
1490           vulnerable to exploit.  The server maintainer should make sure that
1491           any string treated as a format string is controlled.
1492
1493               # assuming log_file = 'Sys::Syslog'
1494
1495               $self->log(1, "My Message with %s in it");
1496               # sends "%s", "My Message with %s in it" to syslog
1497
1498               $self->log(1, "My Message with %s in it", "Foo");
1499               # sends "My Message with %s in it", "Foo" to syslog
1500
1501           If log_file is set to a file (other than Sys::Syslog), the message
1502           will be appended to the log file by calling the write_to_log_hook.
1503
1504           If the log_file is Sys::Syslog and an error occurs during write,
1505           the handle_syslog_error method will be called and passed the error
1506           exception.  The default option of handle_syslog_error is to die -
1507           but could easily be told to do nothing by using the following code
1508           in your subclassed server:
1509
1510               sub handle_syslog_error {}
1511
1512           It the log had been closed, you could attempt to reopen it in the
1513           error handler with the following code:
1514
1515               sub handle_syslog_error {
1516                   my $self = shift;
1517                   $self->open_syslog;
1518               }
1519
1520       "$self->new"
1521           As of Net::Server 0.91 there is finally a "new" method.  This
1522           method takes a class name and an argument hashref as parameters.
1523           The argument hashref becomes the "server" property of the object.
1524
1525               package MyPackage;
1526               use base qw(Net::Server);
1527
1528               my $obj = MyPackage->new({port => 20201});
1529
1530               # same as
1531
1532               my $obj = bless {server => {port => 20201}}, 'MyPackage';
1533
1534       "$self->open_syslog"
1535           Called during post_configure when the log_file option is set to
1536           'Sys::Syslog'.  By default it use the parsed configuration options
1537           listed in this document.  If more custom behavior is desired, the
1538           method could be overridden and Sys::Syslog::openlog should be
1539           called with the custom parameters.
1540
1541       "$self->shutdown_sockets"
1542           This method will close any remaining open sockets.  This is called
1543           at the end of the server_close method.
1544

RESTARTING

1546       Each of the server personalities (except for INET), support restarting
1547       via a HUP signal (see "kill -l").  When a HUP is received, the server
1548       will close children (if any), make sure that sockets are left open, and
1549       re-exec using the same commandline parameters that initially started
1550       the server.  (Note: for this reason it is important that @ARGV is not
1551       modified until "->run" is called).
1552
1553       The Net::Server will attempt to find out the commandline used for
1554       starting the program.  The attempt is made before any configuration
1555       files or other arguments are processed.  The outcome of this attempt is
1556       stored using the method "->commandline".  The stored commandline may
1557       also be retrieved using the same method name.  The stored contents will
1558       undoubtedly contain Tainted items that will cause the server to die
1559       during a restart when using the -T flag (Taint mode).  As it is
1560       impossible to arbitrarily decide what is taint safe and what is not,
1561       the individual program must clean up the tainted items before doing a
1562       restart.
1563
1564           sub configure_hook{
1565               my $self = shift;
1566
1567               ### see the contents
1568               my $ref  = $self->commandline;
1569               use Data::Dumper;
1570               print Dumper $ref;
1571
1572               ### arbitrary untainting - VERY dangerous
1573               my @untainted = map {/(.+)/;$1} @$ref;
1574
1575               $self->commandline(\@untainted)
1576           }
1577

SHUTDOWN

1579       Each of the Fork and PreFork personalities support graceful shutdowns
1580       via the QUIT signal.  When a QUIT is received, the parent will signal
1581       the children and then wait for them to exit.
1582
1583       All server personalities support the normal TERM and INT signal
1584       shutdowns.
1585

HOT DEPLOY

1587       Since version 2.000, the Fork and PreFork personalities have accepted
1588       the TTIN and TTOU signals.  When a TTIN is received, the max_servers is
1589       increased by 1.  If a TTOU signal is received the max_servers is
1590       decreased by 1.  This allows for adjusting the number of handling
1591       processes without having to restart the server.
1592
1593       If the log_level is set to at 3, then the new value is displayed in the
1594       logs.
1595

FILES

1597       The following files are installed as part of this distribution.
1598
1599           Net/Server.pm
1600           Net/Server/Fork.pm
1601           Net/Server/INET.pm
1602           Net/Server/MultiType.pm
1603           Net/Server/PreForkSimple.pm
1604           Net/Server/PreFork.pm
1605           Net/Server/Single.pm
1606           Net/Server/Daemonize.pm
1607           Net/Server/SIG.pm
1608           Net/Server/Proto.pm
1609           Net/Server/Proto/*.pm
1610

INSTALL

1612       Download and extract tarball before running these commands in its base
1613       directory:
1614
1615           perl Makefile.PL
1616           make
1617           make test
1618           make install
1619

AUTHOR

1621       Paul Seamons <paul at seamons.com>
1622

THANKS

1624       As we move to a github flow, please be sure to add yourself to the
1625       credits as patches are passed along (if you'd like to be mentioned).
1626
1627       Thanks to Rob Brown (bbb at cpan.org) for help with miscellaneous
1628       concepts such as tracking down the serialized select via flock ala
1629       Apache and the reference to IO::Select making multiport servers
1630       possible.  And for researching into allowing sockets to remain open
1631       upon exec (making HUP possible).
1632
1633       Thanks to Jonathan J. Miner <miner at doit.wisc.edu> for patching a
1634       blatant problem in the reverse lookups.
1635
1636       Thanks to Bennett Todd <bet at rahul.net> for pointing out a problem in
1637       Solaris 2.5.1 which does not allow multiple children to accept on the
1638       same port at the same time.  Also for showing some sample code from
1639       Viktor Duchovni which now represents the semaphore option of the
1640       serialize argument in the PreFork server.
1641
1642       Thanks to traveler and merlyn from http://perlmonks.org for pointing me
1643       in the right direction for determining the protocol used on a socket
1644       connection.
1645
1646       Thanks to Jeremy Howard <j+daemonize at howard.fm> for numerous
1647       suggestions and for work on Net::Server::Daemonize.
1648
1649       Thanks to Vadim <vadim at hardison.net> for patches to implement
1650       parent/child communication on PreFork.pm.
1651
1652       Thanks to Carl Lewis for suggesting "-" in user names.
1653
1654       Thanks to Slaven Rezic for suggesting Reuse => 1 in Proto::UDP.
1655
1656       Thanks to Tim Watt for adding udp_broadcast to Proto::UDP.
1657
1658       Thanks to Christopher A Bongaarts for pointing out problems with the
1659       Proto::SSL implementation that currently locks around the socket accept
1660       and the SSL negotiation. See Net::Server::Proto::SSL.
1661
1662       Thanks to Alessandro Zummo for pointing out various bugs including some
1663       in configuration, commandline args, and cidr_allow.
1664
1665       Thanks to various other people for bug fixes over the years.  These and
1666       future thank-you's are available in the Changes file as well as CVS
1667       comments.
1668
1669       Thanks to Ben Cohen and tye (on Permonks) for finding and diagnosing
1670       more correct behavior for dealing with re-opening STDIN and STDOUT on
1671       the client handles.
1672
1673       Thanks to Mark Martinec for trouble shooting other problems with STDIN
1674       and STDOUT (he proposed having a flag that is now the no_client_stdout
1675       flag).
1676
1677       Thanks to David (DSCHWEI) on cpan for asking for the nofatal option
1678       with syslog.
1679
1680       Thanks to Andreas Kippnick and Peter Beckman for suggesting leaving
1681       open child connections open during a HUP (this is now available via the
1682       leave_children_open_on_hup flag).
1683
1684       Thanks to LUPE on cpan for helping patch HUP with taint on.
1685
1686       Thanks to Michael Virnstein for fixing a bug in the check_for_dead
1687       section of PreFork server.
1688
1689       Thanks to Rob Mueller for patching PreForkSimple to only open lock_file
1690       once during parent call.  This patch should be portable on systems
1691       supporting flock.  Rob also suggested not closing STDIN/STDOUT but
1692       instead reopening them to /dev/null to prevent spurious warnings.  Also
1693       suggested short circuit in post_accept if in UDP.  Also for cleaning up
1694       some of the child management code of PreFork.
1695
1696       Thanks to Mark Martinec for suggesting additional log messages for
1697       failure during accept.
1698
1699       Thanks to Bill Nesbitt and Carlos Velasco for pointing out double
1700       decrement bug in PreFork.pm (rt #21271)
1701
1702       Thanks to John W. Krahn for pointing out glaring precedence with non-
1703       parened open and ||.
1704
1705       Thanks to Ricardo Signes for pointing out setuid bug for perl 5.6.1 (rt
1706       #21262).
1707
1708       Thanks to Carlos Velasco for updating the Syslog options (rt #21265).
1709       And for additional fixes later.
1710
1711       Thanks to Steven Lembark for pointing out that no_client_stdout wasn't
1712       working with the Multiplex server.
1713
1714       Thanks to Peter Beckman for suggesting allowing Sys::SysLog keywords be
1715       passed through the ->log method and for suggesting we allow more types
1716       of characters through in syslog_ident.  Also to Peter Beckman for
1717       pointing out that a poorly setup localhost will cause tests to hang.
1718
1719       Thanks to Curtis Wilbar for pointing out that the Fork server called
1720       post_accept_hook twice.  Changed to only let the child process call
1721       this, but added the pre_fork_hook method.
1722
1723       And just a general Thanks You to everybody who is using Net::Server or
1724       who has contributed fixes over the years.
1725
1726       Thanks to Paul Miller for some ->autoflush, FileHandle fixes.
1727
1728       Thanks to Patrik Wallstrom for suggesting handling syslog errors
1729       better.
1730
1731       Thanks again to Rob Mueller for more logic cleanup for child accounting
1732       in PreFork server.
1733
1734       Thanks to David Schweikert for suggesting handling setlogsock a little
1735       better on newer versions of Sys::Syslog (>= 0.15).
1736
1737       Thanks to Mihail Nasedkin for suggesting adding a hook that is now
1738       called post_client_connection_hook.
1739
1740       Thanks to Graham Barr for adding the ability to set the check_for_spawn
1741       and min_child_ttl settings of the PreFork server.
1742
1743       Thanks to Daniel Kahn Gillmor for adding the other_child_died_hook.
1744
1745       Thanks to Dominic Humphries for helping not kill pid files on HUP.
1746
1747       Thanks to Kristoffer Møllerhøj for fixing UDP on Multiplex.
1748
1749       Thanks to mishikal for patches for helping identify un-cleaned up
1750       children.
1751
1752       Thanks to rpkelly and tim@retout for pointing out error in header regex
1753       of HTTP.
1754
1755       Thanks to dmcbride for some basic HTTP parsing fixes, as well as for
1756       some broken tied handle fixes.
1757
1758       Thanks to Gareth for pointing out glaring bug issues with broken pipe
1759       and semaphore serialization.
1760
1761       Thanks to CATONE for sending the idea for arbitrary signal passing to
1762       children.  (See the sig_passthrough option)
1763
1764       Thanks to intrigeri@boum for pointing out and giving code ideas for
1765       NS_port not functioning after a HUP.
1766
1767       Thanks to Sergey Zasenko for adding sysread/syswrite support to SSLEAY
1768       as well as the base test.
1769
1770       Thanks to mbarbon@users. for adding tally dequeue to prefork server.
1771
1772       Thanks to stefanos@cpan for fixes to PreFork under Win32
1773
1774       Thanks to Mark Martinec for much of the initial work towards getting
1775       IPv6 going.
1776
1777       Thanks to the munin developers and Nicolai Langfeldt for hosting the
1778       development version of Net::Server for so long and for fixes to the
1779       allow_deny checking for IPv6 addresses.
1780
1781       Thanks to Tatsuhiko Miyagawa for feedback, and for suggesting adding
1782       graceful shutdowns and hot deploy (max_servers adjustment).
1783
1784       Thanks to TONVOON@cpan for submitting a patch adding Log4perl
1785       functionality.
1786
1787       Thanks to Miko O'Sullivan for fixes to HTTP to correct tainting issues
1788       and passing initial log fixes, and for patches to fix CLOSE on tied
1789       stdout and various other HTTP issues.
1790
1791       Thanks to Emanuele <targeta> for a small patch releasing semaphores.
1792
1793       Thanks to Rob <hookbot> for daemonization fixes with zero pid file.
1794

SEE ALSO

1796       Please see also Net::Server::Fork, Net::Server::INET,
1797       Net::Server::PreForkSimple, Net::Server::PreFork,
1798       Net::Server::MultiType, Net::Server::Single Net::Server::HTTP
1799

TODO

1801       Improve test suite to fully cover code (using Devel::Cover).  Anybody
1802       that wanted to send me patches to the t/*.t tests that improved
1803       coverage would earn a big thank you.
1804

CODE REPOSITORY

1806       https://github.com/rhandom/perl-net-server
1807

AUTHOR

1809           Paul Seamons <paul at seamons.com>
1810           http://seamons.com/
1811
1812           Rob Brown <bbb at cpan.org>
1813

LICENSE

1815       This package may be distributed under the terms of either the
1816
1817         GNU General Public License
1818           or the
1819         Perl Artistic License
1820
1821       All rights reserved.
1822
1823
1824
1825perl v5.36.0                      2023-03-17                    Net::Server(3)
Impressum