1Net::Server(3) User Contributed Perl Documentation Net::Server(3)
2
3
4
6 Net::Server - Extensible, general Perl server engine
7
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
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
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
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
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 the IO::Socket classes. UDP servers are
185 slightly different in that they will perform a recv instead of an
186 accept.
187
188 To make programming easier, during the post_accept phase, STDIN and
189 STDOUT are opened to the client connection. This allows for programs
190 to be written using <STDIN> and print "out\n" to print to the client
191 connection. UDP will require using a ->send call.
192
194 The following is a very simple server. The main functionality occurs
195 in the process_request method call as shown below. Notice the use of
196 timeouts to prevent Denial of Service while reading. (Other examples
197 of using "Net::Server" can, or will, be included with this
198 distribution).
199
200 #!/usr/bin/perl -w -T
201
202 package MyPackage;
203
204 use strict;
205 use base qw(Net::Server::PreFork); # any personality will do
206
207 MyPackage->run;
208
209 # over-ride the default echo handler
210
211 sub process_request {
212 my $self = shift;
213 eval {
214
215 local $SIG{'ALRM'} = sub { die "Timed Out!\n" };
216 my $timeout = 30; # give the user 30 seconds to type some lines
217
218 my $previous_alarm = alarm($timeout);
219 while (<STDIN>) {
220 s/\r?\n$//;
221 print "You said '$_'\r\n";
222 alarm($timeout);
223 }
224 alarm($previous_alarm);
225
226 };
227
228 if ($@ =~ /timed out/i) {
229 print STDOUT "Timed Out.\r\n";
230 return;
231 }
232
233 }
234
235 1;
236
237 Playing this file from the command line will invoke a Net::Server using
238 the PreFork personality. When building a server layer over the
239 Net::Server, it is important to use features such as timeouts to
240 prevent Denial Of Service attacks.
241
242 Net::Server comes with a built in echo server by default. You can test
243 it out by simply running the following from the commandline:
244
245 net-server
246
247 If you wanted to try another flavor you could try
248
249 net-server PreFork
250
251 If you wanted to try out a basic HTTP server you could use
252
253 net-server HTTP
254
255 Or if you wanted to test out a CGI you are writing you could use
256
257 net-server HTTP --app ../../mycgi.cgi
258
260 There are at least five possible ways to pass arguments to Net::Server.
261 They are passing to the new method, passing on command line, passing
262 parameters to run, using a conf file, returning values in the
263 default_values method, or configuring the values in
264 post_configure_hook.
265
266 The "options" method is used to determine which arguments the server
267 will search for and can be used to extend the parsed parameters. Any
268 arguments found from the command line, parameters passed to run, and
269 arguments found in the conf_file will be matched against the keys of
270 the options template. Any commandline parameters that do not match
271 will be left in place and can be further processed by the server in the
272 various hooks (by looking at @ARGV). Arguments passed to new will
273 automatically win over any other options (this can be used if you would
274 like to disallow a user passing in other arguments).
275
276 Arguments consist of key value pairs. On the commandline these pairs
277 follow the POSIX fashion of "--key value" or "--key=value", and also
278 "key=value". In the conf file the parameter passing can best be shown
279 by the following regular expression:
280 ($key,$val)=~/^(\w+)\s+(\S+?)\s+$/. Passing arguments to the run
281 method is done as follows: "<Net::Server->run(key1 =" 'val1')>>.
282 Passing arguments via a prebuilt object can best be shown in the
283 following code:
284
285 #!/usr/bin/perl -w -T
286
287 package MyPackage;
288 use strict;
289 use base qw(Net::Server);
290
291 my $server = MyPackage->new({
292 key1 => 'val1',
293 });
294
295 $server->run;
296
297 All five methods for passing arguments may be used at the same time.
298 Once an argument has been set, it is not over written if another method
299 passes the same argument. "Net::Server" will look for arguments in the
300 following order:
301
302 1) Arguments passed to the C<new> method.
303 2) Arguments passed on command line.
304 3) Arguments passed to the C<run> method.
305 4) Arguments passed via a conf file.
306 5) Arguments set in the C<default_values> method.
307
308 Additionally the following hooks are available:
309
310 1) Arguments set in the configure_hook (occurs after new
311 but before any of the other areas are checked).
312 2) Arguments set and validated in the post_configure_hook
313 (occurs after all of the other areas are checked).
314
315 Each of these levels will override parameters of the same name
316 specified in subsequent levels. For example, specifying --setsid=0 on
317 the command line will override a value of "setsid 1" in the conf file.
318
319 Note that the configure_hook method doesn't return values to set, but
320 is there to allow for setting up configured values before the configure
321 method is called.
322
323 Key/value pairs used by the server are removed by the configuration
324 process so that server layers on top of "Net::Server" can pass and read
325 their own parameters.
326
328 It is possible to add in your own custom parameters to those parsed by
329 Net::Server. The following code shows how this is done:
330
331 sub options {
332 my $self = shift;
333 my $prop = $self->{'server'};
334 my $template = shift;
335
336 # setup options in the parent classes
337 $self->SUPER::options($template);
338
339 # add a single value option
340 $prop->{'my_option'} ||= undef;
341 $template->{'my_option'} = \ $prop->{'my_option'};
342
343 # add a multi value option
344 $prop->{'an_arrayref_item'} ||= [];
345 $template->{'an_arrayref_item'} = $prop->{'an_arrayref_item'};
346 }
347
348 Overriding the "options" method allows for adding your own custom
349 fields. A template hashref is passed in, that should then be modified
350 to contain an of your custom fields. Fields which are intended to
351 receive a single scalar value should have a reference to the
352 destination scalar given. Fields which are intended to receive
353 multiple values should reference the corresponding destination
354 arrayref.
355
356 You are responsible for validating your custom options once they have
357 been parsed. The post_configure_hook is a good place to do your
358 validation.
359
360 Some emails have asked why we use this "template" method. The idea is
361 that you are creating the the data structure to store the values in,
362 and you are also creating a way to get the values into the data
363 structure. The template is the way to get the values to the servers
364 data structure. One of the possibilities (that probably isn't used
365 that much) is that by letting you specify the mapping, you could build
366 a nested data structure - even though the passed in arguments are flat.
367 It also allows you to setup aliases to your names.
368
369 For example, a basic structure might look like this:
370
371 $prop = $self->{'server'}
372
373 $prop->{'my_custom_option'} ||= undef;
374 $prop->{'my_custom_array'} ||= [];
375
376 $template = {
377 my_custom_option => \ $prop->{'my_custom_option'},
378 mco => \ $prop->{'my_custom_option'}, # alias
379 my_custom_array => $prop->{'my_custom_array'},
380 mca => $prop->{'my_custom_array'}, # an alias
381 };
382
383 $template->{'mco2'} = $template->{'mco'}; # another way to alias
384
385 But you could also have more complex data:
386
387 $prop = $self->{'server'};
388
389 $prop->{'one_layer'} = {
390 two_layer => [
391 undef,
392 undef,
393 ],
394 };
395
396 $template = {
397 param1 => \ $prop->{'one_layer'}->{'two_layer'}->[0],
398 param2 => \ $prop->{'one_layer'}->{'two_layer'}->[1],
399 };
400
401 This is of course a contrived example - but it does show that you can
402 get the data from the flat passed in arguments to whatever type of
403 structure you need - with only a little bit of effort.
404
406 The following arguments are available in the default "Net::Server" or
407 "Net::Server::Single" modules. (Other personalities may use additional
408 parameters and may optionally not use parameters from the base class.)
409
410 Key Value Default
411 conf_file "filename" undef
412
413 log_level 0-4 2
414 log_file (filename|Sys::Syslog
415 |Log::Log4perl) undef
416
417 port \d+ 20203
418 host "host" "*"
419 ipv (4|6|*) *
420 proto (tcp|udp|unix) "tcp"
421 listen \d+ SOMAXCONN
422
423 ## syslog parameters (if log_file eq Sys::Syslog)
424 syslog_logsock (native|unix|inet|udp
425 |tcp|stream|console) unix (on Sys::Syslog < 0.15)
426 syslog_ident "identity" "net_server"
427 syslog_logopt (cons|ndelay|nowait|pid) pid
428 syslog_facility \w+ daemon
429
430 reverse_lookups 1 undef
431 allow /regex/ none
432 deny /regex/ none
433 cidr_allow CIDR none
434 cidr_deny CIDR none
435
436 ## daemonization parameters
437 pid_file "filename" undef
438 chroot "directory" undef
439 user (uid|username) "nobody"
440 group (gid|group) "nobody"
441 background 1 undef
442 setsid 1 undef
443
444 no_close_by_child (1|undef) undef
445
446 ## See Net::Server::Proto::(TCP|UDP|UNIX|SSL|SSLeay|etc)
447 ## for more sample parameters.
448
449 conf_file
450 Filename from which to read additional key value pair arguments for
451 starting the server. Default is undef.
452
453 There are two ways that you can specify a default location for a
454 conf_file. The first is to pass the default value to the run
455 method as in:
456
457 MyServer->run({
458 conf_file => '/etc/my_server.conf',
459 });
460
461 If the end user passes in --conf_file=/etc/their_server.conf then
462 the value will be overridden.
463
464 The second way to do this was added in the 0.96 version. It uses
465 the default_values method as in:
466
467 sub default_values {
468 return {
469 conf_file => '/etc/my_server.conf',
470 }
471 }
472
473 This method has the advantage of also being able to be overridden
474 in the run method.
475
476 If you do not want the user to be able to specify a conf_file at
477 all, you can pass conf_file to the new method when creating your
478 object:
479
480 MyServer->new({
481 conf_file => '/etc/my_server.conf',
482 })->run;
483
484 If passed this way, the value passed to new will "win" over any of
485 the other passed in values.
486
487 log_level
488 Ranges from 0 to 4 in level. Specifies what level of error will be
489 logged. "O" means logging is off. "4" means very verbose. These
490 levels should be able to correlate to syslog levels. Default is 2.
491 These levels correlate to syslog levels as defined by the following
492 key/value pairs: 0=>'err', 1=>'warning', 2=>'notice', 3=>'info',
493 4=>'debug'.
494
495 log_file
496 Name of log file or log subsystem to be written to. If no name is
497 given and the write_to_log_hook is not overridden, log goes to
498 STDERR. Default is undef.
499
500 The log_file may also be the name of a Net::Server pluggable
501 logging class. Net::Server is packaged with Sys::Syslog and
502 Log::Log4perl. If the log_file looks like a module name, it will
503 have "Net::Server::Log::" added to the front and it will then be
504 required. The package should provide an "initialize" class method
505 that returns a single function which will be used for logging.
506 This returned function will be passed log_level, and message.
507
508 If the magic name "Sys::Syslog" is used, all logging will take
509 place via the Net::Server::Log::Sys::Syslog module. If syslog is
510 used the parameters "syslog_logsock", "syslog_ident", and
511 "syslog_logopt",and "syslog_facility" may also be defined. See
512 Net::Server::Log::Sys::Syslog.
513
514 If the magic name "Log::Log4perl" is used, all logging will be
515 directed to the Log4perl system. If used, the "log4perl_conf",
516 "log4perl_poll", "log4perl_logger" may also be defined. See
517 Net::Server::Log::Log::Log4per.
518
519 If a "log_file" is given or if "setsid" is set, STDIN and STDOUT
520 will automatically be opened to /dev/null and STDERR will be opened
521 to STDOUT. This will prevent any output from ending up at the
522 terminal.
523
524 pid_file
525 Filename to store pid of parent process. Generally applies only to
526 forking servers. Default is none (undef).
527
528 port
529 See Net::Server::Proto for further examples of configuration.
530
531 Local port/socket on which to bind. If it is a low port, the
532 process must start as root. If multiple ports are given, all will
533 be bound at server startup. May be of the form "host:port/proto",
534 "host:port/proto/ipv", "host:port", "port/proto", or "port", where
535 host represents a hostname residing on the local box, where port
536 represents either the number of the port (eg. "80") or the service
537 designation (eg. "http"), where ipv represents the IP protocol
538 version (IPv4 or IPv6 or IPv*) and where proto represents the
539 protocol to be used. See Net::Server::Proto. The following are
540 some valid port strings:
541
542 20203 # port only
543 localhost:20203 # host and port
544 localhost:http # localhost bound to port 80
545 localhost:20203/tcp # host, port, protocol
546 localhost:20203/tcp/IPv* # host, port, protocol and family
547 localhost, 20203, tcp, IPv* # same
548 localhost | 20203 | tcp | IPv* # same
549 localhost:20203/IPv* # bind any configured interfaces for IPv4 or 6 (default)
550 localhost:20203/IPv4/IPv6 # bind localhost on IPv4 and 6 (fails if it cannot do both)
551
552 *:20203 # bind all local interfaces
553
554 Additionally, when passed in the code (non-commandline, and non-
555 config), the port may be passed as a hashref or array hashrefs of
556 information:
557
558 port => {
559 host => 'localhost',
560 port => '20203',
561 ipv => 6, # IPv6 only
562 proto => 'udp', # UDP protocol
563 }
564
565 port => [{
566 host => '*',
567 port => '20203',
568 ipv => 4, # IPv4 only
569 proto => 'tcp', # (default)
570 }, {
571 host => 'localhost',
572 port => '20204',
573 ipv => '*', # default - all IPv4 and IPv6 interfaces tied to localhost
574 proto => 'ssleay', # or ssl - Using SSL
575 }],
576
577 An explicit host given in a port specification overrides a default
578 binding address (a "host" setting, see below). The host part may
579 be enclosed in square brackets, but when it is a numerical IPv6
580 address it should be enclosed in square brackets to avoid ambiguity
581 in parsing a port number, e.g.: "[::1]:80". However you could also
582 use pipes, white space, or commas to separate these. Note that
583 host and port number must come first.
584
585 If the protocol is not specified, proto will default to the "proto"
586 specified in the arguments. If "proto" is not specified there it
587 will default to "tcp". If host is not specified, host will default
588 to "host" specified in the arguments. If "host" is not specified
589 there it will default to "*". Default port is 20203.
590 Configuration passed to new or run may be either a scalar
591 containing a single port number or an arrayref of ports. If "ipv"
592 is not specified it will default to "*" (Any resolved addresses
593 under IPv4 or IPv6).
594
595 If you are working with unix sockets, you may also specify
596 "socket_file|unix" or "socket_file|type|unix" where type is
597 SOCK_DGRAM or SOCK_STREAM.
598
599 On systems that support it, a port value of 0 may be used to ask
600 the OS to auto-assign a port. The value of the auto-assigned port
601 will be stored in the NS_port property of the
602 Net::Server::Proto::TCP object and is also available in the
603 sockport method. When the server is processing a request, the
604 $self->{server}->{sockport} property contains the port that was
605 connected through.
606
607 host
608 Local host or addr upon which to bind port. If a value of '*' is
609 given, the server will bind that port on all available addresses on
610 the box. The "host" argument provides a default local host address
611 if the "port" argument omits a host specification. See
612 Net::Server::Proto. See IO::Socket. Configuration passed to new or
613 run may be either a scalar containing a single host or an arrayref
614 of hosts - if the hosts array is shorter than the ports array, the
615 last host entry will be used to augment the hosts arrary to the
616 size of the ports array.
617
618 If an IPv4 address is passed, an IPv4 socket will be created. If
619 an IPv6 address is passed, an IPv6 socket will be created. If a
620 hostname is given, Net::Server will look at the value of ipv
621 (default IPv4) to determine which type of socket to create.
622 Optionally the ipv specification can be passed as part of the
623 hostname.
624
625 host => "127.0.0.1", # an IPv4 address
626
627 host => "::1", # an IPv6 address
628
629 host => 'localhost', # addresses matched by localhost (default any IPv4 and/or IPv6)
630
631 host => 'localhost/IPv*', # same
632
633 ipv => 6,
634 host => 'localhost', # addresses matched by localhost (IPv6)
635
636 ipv => 4,
637 host => 'localhost', # addresses matched by localhost (IPv4)
638
639 ipv => 'IPv4 IPv6',
640 host => 'localhost', # addresses matched by localhost (requires IPv6 and IPv4)
641
642 host => '*', # any local interfaces (any IPv6 or IPv4)
643
644 host => '*/IPv*', # same (any IPv6 or IPv4)
645
646 ipv => 4,
647 host => '*', # any local IPv4 interfaces interfaces
648
649 proto
650 See Net::Server::Proto. Protocol to use when binding ports. See
651 IO::Socket. As of release 2.0, Net::Server supports tcp, udp, and
652 unix, unixdgram, ssl, and ssleay. Other types will need to be
653 added later (or custom modules extending the Net::Server::Proto
654 class may be used). Configuration passed to new or run may be
655 either a scalar containing a single proto or an arrayref of protos
656 - if the protos array is shorter than the ports array, the last
657 proto entry will be used to augment the protos arrary to the size
658 of the ports array.
659
660 Additionally the proto may also contain the ipv specification.
661
662 ipv (IPv4 and IPv6)
663 See Net::Server::Proto.
664
665 IPv6 is now available under Net::Server. It will be used
666 automatically if an IPv6 address is passed, or if the ipv is set
667 explicitly to IPv6, or if ipv is left as the default value of IPv*.
668 This is a significant change from version 2.004 and earlier where
669 the default value was IPv4. However, the previous behavior led to
670 confusion on IPv6 only hosts, and on hosts that only had IPv6
671 entries for a local hostname. Trying to pass an IPv4 address when
672 ipv is set to 6 (only 6 - not * or 4) will result in an error.
673
674 localhost:20203 # will use IPv6 if there is a corresponding entry for localhost
675 # it will also use IPv4 if there is a corresponding v4 entry for localhost
676
677 localhost:20203:IPv* # same (default)
678
679 localhost:20203:IPv6 # will use IPv6
680
681 [::1]:20203 # will use IPv6 (IPv6 style address)
682
683 localhost:20203:IPv4 # will use IPv4
684
685 127.0.0.1:20203 # will use IPv4 (IPv4 style address
686
687 localhost:20203:IPv4:IPv6 # will bind to both v4 and v6 - fails otherwise
688
689 # or as a hashref as
690 port => {
691 host => "localhost",
692 ipv => 6, # only binds IPv6
693 }
694
695 port => {
696 host => "localhost",
697 ipv => 4, # only binds IPv4
698 }
699
700 port => {
701 host => "::1",
702 ipv => "IPv6", # same as passing "6"
703 }
704
705 port => {
706 host => "localhost/IPv*", # any IPv4 or IPv6
707 }
708
709 port => {
710 host => "localhost IPv4 IPv6", # must create both
711 }
712
713 In many proposed Net::Server solutions, IPv* was enabled by
714 default. For versions 2.000 through 2.004, the previous default of
715 IPv4 was used. We have attempted to make it easy to set IPv4,
716 IPv6, or IPv*. If you do not want or need IPv6, simply set ipv to
717 4, pass IPv4 along in the port specification, set $ENV{'IPV'}=4;
718 before running the server, or uninstall IO::Socket::INET6.
719
720 On my local box the following command results in the following
721 output:
722
723 perl -e 'use base qw(Net::Server); main->run(host => "localhost")'
724
725 Resolved [localhost]:20203 to [::1]:20203, IPv6
726 Resolved [localhost]:20203 to [127.0.0.1]:20203, IPv4
727 Binding to TCP port 20203 on host ::1 with IPv6
728 Binding to TCP port 20203 on host 127.0.0.1 with IPv4
729
730 My local box has IPv6 enabled and there are entries for localhost
731 on both IPv6 ::1 and IPv4 127.0.0.1. I could also choose to
732 explicitly bind ports rather than depending upon ipv => "*" to
733 resolve them for me as in the following:
734
735 perl -e 'use base qw(Net::Server); main->run(port => [20203,20203], host => "localhost", ipv => [4,6])'
736
737 Binding to TCP port 20203 on host localhost with IPv4
738 Binding to TCP port 20203 on host localhost with IPv6
739
740 There is a special case of using host => "*" as well as ipv => "*".
741 The Net::Server::Proto::_bindv6only method is used to check the
742 system setting for "sysctl -n net.ipv6.bindv6only" (or
743 net.inet6.ip6.v6only). If this setting is false, then an IPv6
744 socket will listen for the corresponding IPv4 address. For example
745 the address [::] (IPv6 equivalent of INADDR_ANY) will also listen
746 for 0.0.0.0. The address ::FFFF:127.0.0.1 (IPv6) would also listen
747 to 127.0.0.1 (IPv4). In this case, only one socket will be created
748 because it will handle both cases (an error is returned if an
749 attempt is made to listen to both addresses when bindv6only is
750 false).
751
752 However, if net.ipv6.bindv6only (or equivalent) is true, then a
753 hostname (such as *) resolving to both a IPv4 entry as well as an
754 IPv6 will result in both an IPv4 socket as well as an IPv6 socket.
755
756 On my linux box which defaults to net.ipv6.bindv6only=0, the
757 following is output.
758
759 perl -e 'use base qw(Net::Server); main->run(host => "*")'
760
761 Resolved [*]:8080 to [::]:8080, IPv6
762 Not including resolved host [0.0.0.0] IPv4 because it will be handled by [::] IPv6
763 Binding to TCP port 8080 on host :: with IPv6
764
765 If I issue a "sudo /sbin/sysctl -w net.ipv6.bindv6only=1", the
766 following is output.
767
768 perl -e 'use base qw(Net::Server); main->run(host => "*")'
769
770 Resolved [*]:8080 to [0.0.0.0]:8080, IPv4
771 Resolved [*]:8080 to [::]:8080, IPv6
772 Binding to TCP port 8080 on host 0.0.0.0 with IPv4
773 Binding to TCP port 8080 on host :: with IPv6
774
775 BSD differs from linux and generally defaults to
776 net.inet6.ip6.v6only=0. If it cannot be determined on your OS, it
777 will default to false and the log message will change from "it will
778 be handled" to "it should be handled" (if you have a non-resource
779 intensive way to check on your platform, feel free to email me).
780 Be sure to check the logs as you test your server to make sure you
781 have bound the ports you desire. You can always pass in individual
782 explicit IPv4 and IPv6 port specifications if you need. For
783 example, if your system has both IPv4 and IPv6 interfaces but you'd
784 only like to bind to IPv6 entries, then you should use a hostname
785 of [::] instead of [*].
786
787 If bindv6only (or equivalent) is false, and you receive an IPv4
788 connection on a bound IPv6 port, the textual representation of the
789 peer's IPv4 address will typically be in a form of an IPv4-mapped
790 IPv6 addresses, e.g. "::FFFF:127.0.0.1" .
791
792 The ipv parameter was chosen because it does not conflict with any
793 other existing usage, it is very similar to ipv4 or ipv6, it allows
794 for user code to not need to know about Socket::AF_INET or
795 Socket6::AF_INET6 or Socket::AF_UNSPEC, and it is short.
796
797 listen
798 See IO::Socket. Not used with udp protocol (or UNIX SOCK_DGRAM).
799
800 reverse_lookups
801 Specify whether to lookup the hostname of the connected IP.
802 Information is cached in server object under "peerhost" property.
803 Default is to not use reverse_lookups (undef).
804
805 allow/deny
806 May be specified multiple times. Contains regex to compare to
807 incoming peeraddr or peerhost (if reverse_lookups has been
808 enabled). If allow or deny options are given, the incoming client
809 must match an allow and not match a deny or the client connection
810 will be closed. Defaults to empty array refs.
811
812 cidr_allow/cidr_deny
813 May be specified multiple times. Contains a CIDR block to compare
814 to incoming peeraddr. If cidr_allow or cidr_deny options are
815 given, the incoming client must match a cidr_allow and not match a
816 cidr_deny or the client connection will be closed. Defaults to
817 empty array refs.
818
819 chroot
820 Directory to chroot to after bind process has taken place and the
821 server is still running as root. Defaults to undef.
822
823 user
824 Userid or username to become after the bind process has occured.
825 Defaults to "nobody." If you would like the server to run as root,
826 you will have to specify "user" equal to "root".
827
828 group
829 Groupid or groupname to become after the bind process has occured.
830 Defaults to "nobody." If you would like the server to run as root,
831 you will have to specify "group" equal to "root".
832
833 background
834 Specifies whether or not the server should fork after the bind
835 method to release itself from the command line. Defaults to undef.
836 Process will also background if "setsid" is set.
837
838 setsid
839 Specifies whether or not the server should fork after the bind
840 method to release itself from the command line and then run the
841 "POSIX::setsid()" command to truly daemonize. Defaults to undef.
842 If a "log_file" is given or if "setsid" is set, STDIN and STDOUT
843 will automatically be opened to /dev/null and STDERR will be opened
844 to STDOUT. This will prevent any output from ending up at the
845 terminal.
846
847 no_close_by_child
848 Boolean. Specifies whether or not a forked child process has
849 permission or not to shutdown the entire server process. If set to
850 1, the child may NOT signal the parent to shutdown all children.
851 Default is undef (not set).
852
853 no_client_stdout
854 Boolean. Default undef (not set). Specifies that STDIN and STDOUT
855 should not be opened on the client handle once a connection has
856 been accepted. By default the Net::Server will open STDIN and
857 STDOUT on the client socket making it easier for many types of
858 scripts to read directly from and write directly to the socket
859 using normal print and read methods. Disabling this is useful on
860 clients that may be opening their own connections to STDIN and
861 STDOUT.
862
863 This option has no affect on STDIN and STDOUT which has a magic
864 client property that is tied to the already open STDIN and STDOUT.
865
866 leave_children_open_on_hup
867 Boolean. Default undef (not set). If set, the parent will not
868 attempt to close child processes if the parent receives a SIG HUP.
869 The parent will rebind the the open port and begin tracking a fresh
870 set of children.
871
872 Children of a Fork server will exit after their current request.
873 Children of a Prefork type server will finish the current request
874 and then exit.
875
876 Note - the newly restarted parent will start up a fresh set of
877 servers on fork servers. The new parent will attempt to keep track
878 of the children from the former parent but custom communication
879 channels (open pipes from the child to the old parent) will no
880 longer be available to the old child processes. New child
881 processes will still connect properly to the new parent.
882
883 sig_passthrough
884 Default none. Allow for passing requested signals through to
885 children. Takes a single signal name, a comma separated list of
886 names, or an arrayref of signal names. It first sends the signals
887 to the children before calling any currently registered signal by
888 that name.
889
890 tie_client_stdout
891 Default undef. If set will use Net::Server::TiedHandle tied
892 interface for STDIN and STDOUT. This interface allows SSL and
893 SSLEAY to work. It also allows for intercepting read and write via
894 the tied_stdin_callback and tied_stdout_callback.
895
896 tied_stdin_callback
897 Default undef. Called during a read of STDIN data if
898 tie_client_stdout has been set, or if the client handle's
899 tie_stdout method returns true. It is passed the client
900 connection, the name of the method that would be called, and the
901 arguments that are being passed. The callback is then responsible
902 for calling that method on the handle or for performing some other
903 input operation.
904
905 tied_stdout_callback
906 Default undef. Called during a write of data to STDOUT if
907 tie_client_stdout has been set, or if the client handle's
908 tie_stdout method returns true. It is passed the client
909 connection, the name of the method that would be called, and the
910 arguments that are being passed. The callback is then responsible
911 for calling that method on the handle or for performing some other
912 output operation.
913
915 All of the "ARGUMENTS" listed above become properties of the server
916 object under the same name. These properties, as well as other
917 internal properties, are available during hooks and other method calls.
918
919 The structure of a Net::Server object is shown below:
920
921 $self = bless({
922 server => {
923 key1 => 'val1',
924 # more key/vals
925 },
926 }, 'Net::Server');
927
928 This structure was chosen so that all server related properties are
929 grouped under a single key of the object hashref. This is so that
930 other objects could layer on top of the Net::Server object class and
931 still have a fairly clean namespace in the hashref.
932
933 You may get and set properties in two ways. The suggested way is to
934 access properties directly via
935
936 my $val = $self->{server}->{key1};
937
938 Accessing the properties directly will speed the server process -
939 though some would deem this as bad style. A second way has been
940 provided for object oriented types who believe in methods. The second
941 way consists of the following methods:
942
943 my $val = $self->get_property( 'key1' );
944 my $self->set_property( key1 => 'val1' );
945
946 Properties are allowed to be changed at any time with caution (please
947 do not undef the sock property or you will close the client
948 connection).
949
951 "Net::Server" allows for the use of a configuration file to read in
952 server parameters. The format of this conf file is simple key value
953 pairs. Comments and blank lines are ignored.
954
955 #-------------- file test.conf --------------
956
957 ### user and group to become
958 user somebody
959 group everybody
960
961 # logging ?
962 log_file /var/log/server.log
963 log_level 3
964 pid_file /tmp/server.pid
965
966 # optional syslog directive
967 # used in place of log_file above
968 #log_file Sys::Syslog
969 #syslog_logsock unix
970 #syslog_ident myserver
971 #syslog_logopt pid|cons
972
973 # access control
974 allow .+\.(net|com)
975 allow domain\.com
976 deny a.+
977 cidr_allow 127.0.0.0/8
978 cidr_allow 192.0.2.0/24
979 cidr_deny 192.0.2.4/30
980
981 # background the process?
982 background 1
983
984 # ports to bind (this should bind
985 # 127.0.0.1:20205 on IPv6 and
986 # localhost:20204 on IPv4)
987 # See Net::Server::Proto
988 host 127.0.0.1
989 ipv IPv6
990 port localhost:20204/IPv4
991 port 20205
992
993 # reverse lookups ?
994 # reverse_lookups on
995
996 #-------------- file test.conf --------------
997
999 The process flow is written in an open, easy to override, easy to hook,
1000 fashion. The basic flow is shown below. This is the flow of the
1001 "$self->run" method.
1002
1003 $self->configure_hook;
1004
1005 $self->configure(@_);
1006
1007 $self->post_configure;
1008
1009 $self->post_configure_hook;
1010
1011 $self->pre_bind;
1012
1013 $self->bind;
1014
1015 $self->post_bind_hook;
1016
1017 $self->post_bind;
1018
1019 $self->pre_loop_hook;
1020
1021 $self->loop;
1022
1023 ### routines inside a standard $self->loop
1024 # $self->accept;
1025 # $self->run_client_connection;
1026 # $self->done;
1027
1028 $self->pre_server_close_hook;
1029
1030 $self->server_close;
1031
1032 The server then exits.
1033
1034 During the client processing phase ("$self->run_client_connection"),
1035 the following represents the program flow:
1036
1037 $self->post_accept;
1038
1039 $self->get_client_info;
1040
1041 $self->post_accept_hook;
1042
1043 if ($self->allow_deny
1044 && $self->allow_deny_hook) {
1045
1046 $self->process_request;
1047
1048 } else {
1049
1050 $self->request_denied_hook;
1051
1052 }
1053
1054 $self->post_process_request_hook;
1055
1056 $self->post_process_request;
1057
1058 $self->post_client_connection_hook;
1059
1060 The process then loops and waits for the next connection. For a more
1061 in depth discussion, please read the code.
1062
1063 During the server shutdown phase ("$self->server_close"), the following
1064 represents the program flow:
1065
1066 $self->close_children; # if any
1067
1068 $self->post_child_cleanup_hook;
1069
1070 if (Restarting server) {
1071 $self->restart_close_hook();
1072 $self->hup_server;
1073 }
1074
1075 $self->shutdown_sockets;
1076
1077 $self->server_exit;
1078
1080 "$self->run"
1081 This method incorporates the main process flow. This flow is
1082 listed above.
1083
1084 The method run may be called in any of the following ways.
1085
1086 MyPackage->run(port => 20201);
1087
1088 MyPackage->new({port => 20201})->run;
1089
1090 my $obj = bless {server=>{port => 20201}}, 'MyPackage';
1091 $obj->run;
1092
1093 The ->run method should typically be the last method called in a
1094 server start script (the server will exit at the end of the ->run
1095 method).
1096
1097 "$self->configure"
1098 This method attempts to read configurations from the commandline,
1099 from the run method call, or from a specified conf_file (the
1100 conf_file may be specified by passed in parameters, or in the
1101 default_values). All of the configured parameters are then stored
1102 in the {"server"} property of the Server object.
1103
1104 "$self->post_configure"
1105 The post_configure hook begins the startup of the server. During
1106 this method running server instances are checked for, pid_files are
1107 created, log_files are created, Sys::Syslog is initialized (as
1108 needed), process backgrounding occurs and the server closes STDIN
1109 and STDOUT (as needed).
1110
1111 "$self->pre_bind"
1112 This method is used to initialize all of the socket objects used by
1113 the server.
1114
1115 "$self->bind"
1116 This method actually binds to the inialized sockets (or rebinds if
1117 the server has been HUPed).
1118
1119 "$self->post_bind"
1120 During this method priveleges are dropped. The INT, TERM, and QUIT
1121 signals are set to run server_close. Sig PIPE is set to IGNORE.
1122 Sig CHLD is set to sig_chld. And sig HUP is set to call sig_hup.
1123
1124 Under the Fork, PreFork, and PreFork simple personalities, these
1125 signals are registered using Net::Server::SIG to allow for safe
1126 signal handling.
1127
1128 "$self->loop"
1129 During this phase, the server accepts incoming connections. The
1130 behavior of how the accepting occurs and if a child process handles
1131 the connection is controlled by what type of Net::Server
1132 personality the server is using.
1133
1134 Net::Server and Net::Server single accept only one connection at a
1135 time.
1136
1137 Net::Server::INET runs one connection and then exits (for use by
1138 inetd or xinetd daemons).
1139
1140 Net::Server::MultiPlex allows for one process to simultaneously
1141 handle multiple connections (but requires rewriting the
1142 process_request code to operate in a more "packet-like" manner).
1143
1144 Net::Server::Fork forks off a new child process for each incoming
1145 connection.
1146
1147 Net::Server::PreForkSimple starts up a fixed number of processes
1148 that all accept on incoming connections.
1149
1150 Net::Server::PreFork starts up a base number of child processes
1151 which all accept on incoming connections. The server throttles the
1152 number of processes running depending upon the number of requests
1153 coming in (similar to concept to how Apache controls its child
1154 processes in a PreFork server).
1155
1156 Read the documentation for each of the types for more information.
1157
1158 "$self->server_close"
1159 This method is called once the server has been signaled to end, or
1160 signaled for the server to restart (via HUP), or the loop method
1161 has been exited.
1162
1163 This method takes care of cleaning up any remaining child
1164 processes, setting appropriate flags on sockets (for HUPing),
1165 closing up logging, and then closing open sockets.
1166
1167 Can optionally be passed an exit value that will be passed to the
1168 server_exit call.
1169
1170 "$self->server_exit"
1171 This method is called at the end of server_close. It calls exit,
1172 but may be overridden to do other items. At this point all
1173 services should be shut down.
1174
1175 Can optionally be passed an exit value that will be passed to the
1176 exit call.
1177
1179 "$self->run_client_connection"
1180 This method is run after the server has accepted and received a
1181 client connection. The full process flow is listed above under
1182 PROCESS FLOWS. This method takes care of handling each client
1183 connection.
1184
1185 "$self->post_accept"
1186 This method opens STDIN and STDOUT to the client socket. This
1187 allows any of the methods during the run_client_connection phase to
1188 print directly to and read directly from the client socket.
1189
1190 "$self->get_client_info"
1191 This method looks up information about the client connection such
1192 as ip address, socket type, and hostname (as needed).
1193
1194 "$self->allow_deny"
1195 This method uses the rules defined in the allow and deny
1196 configuration parameters to determine if the ip address should be
1197 accepted.
1198
1199 "$self->process_request"
1200 This method is intended to handle all of the client communication.
1201 At this point STDIN and STDOUT are opened to the client, the ip
1202 address has been verified. The server can then interact with the
1203 client connection according to whatever API or protocol the server
1204 is implementing. Note that the stub implementation uses STDIN and
1205 STDOUT and will not work if the no_client_stdout flag is set.
1206
1207 This is the main method to override.
1208
1209 The default method implements a simple echo server that will repeat
1210 whatever is sent. It will quit the child if "quit" is sent, and
1211 will exit the server if "exit" is sent.
1212
1213 As of version 2.000, the client handle is passed as an argument.
1214
1215 "$self->post_process_request"
1216 This method is used to clean up the client connection and to handle
1217 any parent/child accounting for the forking servers.
1218
1220 "Net::Server" provides a number of "hooks" allowing for servers layered
1221 on top of "Net::Server" to respond at different levels of execution
1222 without having to "SUPER" class the main built-in methods. The
1223 placement of the hooks can be seen in the PROCESS FLOW section.
1224
1225 Almost all of the default hook methods do nothing. To use a hook you
1226 simply need to override the method in your subclass. For example to
1227 add your own post_configure_hook you could do something like the
1228 following:
1229
1230 package MyServer;
1231
1232 sub post_configure_hook {
1233 my $self = shift;
1234 my $prop = $self->{'server'};
1235
1236 # do some validation here
1237 }
1238
1239 The following describes the hooks available in the plain Net::Server
1240 class (other flavors such as Fork or PreFork have additional hooks).
1241
1242 "$self->configure_hook()"
1243 This hook takes place immediately after the "->run()" method is
1244 called. This hook allows for setting up the object before any
1245 built in configuration takes place. This allows for custom
1246 configurability.
1247
1248 "$self->post_configure_hook()"
1249 This hook occurs just after the reading of configuration parameters
1250 and initiation of logging and pid_file creation. It also occurs
1251 before the "->pre_bind()" and "->bind()" methods are called. This
1252 hook allows for verifying configuration parameters.
1253
1254 "$self->post_bind_hook()"
1255 This hook occurs just after the bind process and just before any
1256 chrooting, change of user, or change of group occurs. At this
1257 point the process will still be running as the user who started the
1258 server.
1259
1260 "$self->pre_loop_hook()"
1261 This hook occurs after chroot, change of user, and change of group
1262 has occured. It allows for preparation before looping begins.
1263
1264 "$self->can_read_hook()"
1265 This hook occurs after a socket becomes readible on an
1266 accept_multi_port request (accept_multi_port is used if there are
1267 multiple bound ports to accept on, or if the "multi_port"
1268 configuration parameter is set to true). This hook is intended to
1269 allow for processing of arbitrary handles added to the IO::Select
1270 used for the accept_multi_port. These handles could be added
1271 during the post_bind_hook. No internal support is added for
1272 processing these handles or adding them to the IO::Socket. Care
1273 must be used in how much occurs during the can_read_hook as a long
1274 response time will result in the server being susceptible to DOS
1275 attacks. A return value of true indicates that the Server should
1276 not pass the readible handle on to the post_accept and
1277 process_request phases.
1278
1279 It is generally suggested that other avenues be pursued for sending
1280 messages via sockets not created by the Net::Server.
1281
1282 "$self->post_accept_hook()"
1283 This hook occurs after a client has connected to the server. At
1284 this point STDIN and STDOUT are mapped to the client socket. This
1285 hook occurs before the processing of the request.
1286
1287 "$self->allow_deny_hook()"
1288 This hook allows for the checking of ip and host information beyond
1289 the "$self->allow_deny()" routine. If this hook returns 1, the
1290 client request will be processed, otherwise, the request will be
1291 denied processing.
1292
1293 As of version 2.000, the client connection is passed as an
1294 argument.
1295
1296 "$self->request_denied_hook()"
1297 This hook occurs if either the "$self->allow_deny()" or
1298 "$self->allow_deny_hook()" have taken place.
1299
1300 "$self->post_process_request_hook()"
1301 This hook occurs after the processing of the request, but before
1302 the client connection has been closed.
1303
1304 "$self->post_client_connection_hook"
1305 This is one final hook that occurs at the very end of the
1306 run_client_connection method. At this point all other methods and
1307 hooks that will run during the run_client_connection have finished
1308 and the client connection has already been closed.
1309
1310 item "$self->other_child_died_hook($pid)"
1311
1312 Net::Server takes control of signal handling and child process
1313 cleanup; this makes it difficult to tell when a child process
1314 terminates if that child process was not started by Net::Server
1315 itself. If Net::Server notices another child process dying that it
1316 did not start, it will fire this hook with the PID of the
1317 terminated process.
1318
1319 "$self->pre_server_close_hook()"
1320 This hook occurs before the server begins shutting down.
1321
1322 "$self->write_to_log_hook"
1323 This hook handles writing to log files. The default hook is to
1324 write to STDERR, or to the filename contained in the parameter
1325 "log_file". The arguments passed are a log level of 0 to 4 (4
1326 being very verbose), and a log line. If log_file is equal to
1327 "Sys::Syslog", then logging will go to Sys::Syslog and will bypass
1328 the write_to_log_hook.
1329
1330 "$self->fatal_hook"
1331 This hook occurs when the server has encountered an unrecoverable
1332 error. Arguments passed are the error message, the package, file,
1333 and line number. The hook may close the server, but it is
1334 suggested that it simply return and use the built in shut down
1335 features.
1336
1337 "$self->post_child_cleanup_hook"
1338 This hook occurs in the parent server process after all children
1339 have been shut down and just before the server either restarts or
1340 exits. It is intended for additional cleanup of information. At
1341 this point pid_files and lockfiles still exist.
1342
1343 "$self->restart_open_hook"
1344 This hook occurs if a server has been HUPed (restarted via the HUP
1345 signal. It occurs just before reopening to the filenos of the
1346 sockets that were already opened.
1347
1348 "$self->restart_close_hook"
1349 This hook occurs if a server has been HUPed (restarted via the HUP
1350 signal. It occurs just before restarting the server via exec.
1351
1352 "$self->child_init_hook()"
1353 This hook is called during the forking servers. It is also called
1354 during run_dequeue. It runs just after the fork and after signals
1355 have been cleaned up. If it is a dequeue process, the string
1356 'dequeue' will be passed as an argument.
1357
1358 If your child processes will be needing random numbers, this hook
1359 is a good location to initialize srand (forked processes maintain
1360 the same random seed unless changed).
1361
1362 sub child_init_hook {
1363 # from perldoc -f srand
1364 srand(time ^ $$ ^ unpack "%L*", `ps axww | gzip -f`);
1365 }
1366
1367 "$self->pre_fork_hook()"
1368 Similar to the child_init_hook, but occurs just before the fork.
1369
1370 "$self->child_finish_hook()"
1371 Similar to the child_init_hook, but ran when the forked process is
1372 about to finish up.
1373
1375 "$self->default_values"
1376 Allow for returning configuration values that will be used if no
1377 other value could be found.
1378
1379 Should return a hashref.
1380
1381 sub default_values {
1382 return {
1383 port => 20201,
1384 };
1385 }
1386
1387 "$self->handle_syslog_error"
1388 Called when log_file is set to 'Sys::Syslog' and an error occurs
1389 while writing to the syslog. It is passed two arguments, the value
1390 of $@, and an arrayref containing the arguments that were passed to
1391 the log method when the error occured.
1392
1393 "$self->log"
1394 Parameters are a log_level and a message.
1395
1396 If log_level is set to 'Sys::Syslog', the parameters may
1397 alternately be a log_level, a format string, and format string
1398 parameters. (The second parameter is assumed to be a format string
1399 if additional arguments are passed along). Passing arbitrary
1400 format strings to Sys::Syslog will allow the server to be
1401 vulnerable to exploit. The server maintainer should make sure that
1402 any string treated as a format string is controlled.
1403
1404 # assuming log_file = 'Sys::Syslog'
1405
1406 $self->log(1, "My Message with %s in it");
1407 # sends "%s", "My Message with %s in it" to syslog
1408
1409 $self->log(1, "My Message with %s in it", "Foo");
1410 # sends "My Message with %s in it", "Foo" to syslog
1411
1412 If log_file is set to a file (other than Sys::Syslog), the message
1413 will be appended to the log file by calling the write_to_log_hook.
1414
1415 If the log_file is Sys::Syslog and an error occurs during write,
1416 the handle_syslog_error method will be called and passed the error
1417 exception. The default option of handle_syslog_error is to die -
1418 but could easily be told to do nothing by using the following code
1419 in your subclassed server:
1420
1421 sub handle_syslog_error {}
1422
1423 It the log had been closed, you could attempt to reopen it in the
1424 error handler with the following code:
1425
1426 sub handle_syslog_error {
1427 my $self = shift;
1428 $self->open_syslog;
1429 }
1430
1431 "$self->new"
1432 As of Net::Server 0.91 there is finally a "new" method. This
1433 method takes a class name and an argument hashref as parameters.
1434 The argument hashref becomes the "server" property of the object.
1435
1436 package MyPackage;
1437 use base qw(Net::Server);
1438
1439 my $obj = MyPackage->new({port => 20201});
1440
1441 # same as
1442
1443 my $obj = bless {server => {port => 20201}}, 'MyPackage';
1444
1445 "$self->open_syslog"
1446 Called during post_configure when the log_file option is set to
1447 'Sys::Syslog'. By default it use the parsed configuration options
1448 listed in this document. If more custom behavior is desired, the
1449 method could be overridden and Sys::Syslog::openlog should be
1450 called with the custom parameters.
1451
1452 "$self->shutdown_sockets"
1453 This method will close any remaining open sockets. This is called
1454 at the end of the server_close method.
1455
1457 Each of the server personalities (except for INET), support restarting
1458 via a HUP signal (see "kill -l"). When a HUP is received, the server
1459 will close children (if any), make sure that sockets are left open, and
1460 re-exec using the same commandline parameters that initially started
1461 the server. (Note: for this reason it is important that @ARGV is not
1462 modified until "->run" is called).
1463
1464 The Net::Server will attempt to find out the commandline used for
1465 starting the program. The attempt is made before any configuration
1466 files or other arguments are processed. The outcome of this attempt is
1467 stored using the method "->commandline". The stored commandline may
1468 also be retrieved using the same method name. The stored contents will
1469 undoubtedly contain Tainted items that will cause the server to die
1470 during a restart when using the -T flag (Taint mode). As it is
1471 impossible to arbitrarily decide what is taint safe and what is not,
1472 the individual program must clean up the tainted items before doing a
1473 restart.
1474
1475 sub configure_hook{
1476 my $self = shift;
1477
1478 ### see the contents
1479 my $ref = $self->commandline;
1480 use Data::Dumper;
1481 print Dumper $ref;
1482
1483 ### arbitrary untainting - VERY dangerous
1484 my @untainted = map {/(.+)/;$1} @$ref;
1485
1486 $self->commandline(\@untainted)
1487 }
1488
1490 Each of the Fork and PreFork personalities support graceful shutdowns
1491 via the QUIT signal. When a QUIT is received, the parent will signal
1492 the children and then wait for them to exit.
1493
1494 All server personalities support the normal TERM and INT signal
1495 shutdowns.
1496
1498 Since version 2.000, the Fork and PreFork personalities have accepted
1499 the TTIN and TTOU signals. When a TTIN is received, the max_servers is
1500 increased by 1. If a TTOU signal is received the max_servers is
1501 decreased by 1. This allows for adjusting the number of handling
1502 processes without having to restart the server.
1503
1504 If the log_level is set to at 3, then the new value is displayed in the
1505 logs.
1506
1508 The following files are installed as part of this distribution.
1509
1510 Net/Server.pm
1511 Net/Server/Fork.pm
1512 Net/Server/INET.pm
1513 Net/Server/MultiType.pm
1514 Net/Server/PreForkSimple.pm
1515 Net/Server/PreFork.pm
1516 Net/Server/Single.pm
1517 Net/Server/Daemonize.pm
1518 Net/Server/SIG.pm
1519 Net/Server/Proto.pm
1520 Net/Server/Proto/*.pm
1521
1523 Download and extract tarball before running these commands in its base
1524 directory:
1525
1526 perl Makefile.PL
1527 make
1528 make test
1529 make install
1530
1532 Paul Seamons <paul at seamons.com>
1533
1535 As we move to a github flow, please be sure to add yourself to the
1536 credits as patches are passed along (if you'd like to be mentioned).
1537
1538 Thanks to Rob Brown (bbb at cpan.org) for help with miscellaneous
1539 concepts such as tracking down the serialized select via flock ala
1540 Apache and the reference to IO::Select making multiport servers
1541 possible. And for researching into allowing sockets to remain open
1542 upon exec (making HUP possible).
1543
1544 Thanks to Jonathan J. Miner <miner at doit.wisc.edu> for patching a
1545 blatant problem in the reverse lookups.
1546
1547 Thanks to Bennett Todd <bet at rahul.net> for pointing out a problem in
1548 Solaris 2.5.1 which does not allow multiple children to accept on the
1549 same port at the same time. Also for showing some sample code from
1550 Viktor Duchovni which now represents the semaphore option of the
1551 serialize argument in the PreFork server.
1552
1553 Thanks to traveler and merlyn from http://perlmonks.org for pointing me
1554 in the right direction for determining the protocol used on a socket
1555 connection.
1556
1557 Thanks to Jeremy Howard <j+daemonize at howard.fm> for numerous
1558 suggestions and for work on Net::Server::Daemonize.
1559
1560 Thanks to Vadim <vadim at hardison.net> for patches to implement
1561 parent/child communication on PreFork.pm.
1562
1563 Thanks to Carl Lewis for suggesting "-" in user names.
1564
1565 Thanks to Slaven Rezic for suggesing Reuse => 1 in Proto::UDP.
1566
1567 Thanks to Tim Watt for adding udp_broadcast to Proto::UDP.
1568
1569 Thanks to Christopher A Bongaarts for pointing out problems with the
1570 Proto::SSL implementation that currently locks around the socket accept
1571 and the SSL negotiation. See Net::Server::Proto::SSL.
1572
1573 Thanks to Alessandro Zummo for pointing out various bugs including some
1574 in configuration, commandline args, and cidr_allow.
1575
1576 Thanks to various other people for bug fixes over the years. These and
1577 future thank-you's are available in the Changes file as well as CVS
1578 comments.
1579
1580 Thanks to Ben Cohen and tye (on Permonks) for finding and diagnosing
1581 more correct behavior for dealing with re-opening STDIN and STDOUT on
1582 the client handles.
1583
1584 Thanks to Mark Martinec for trouble shooting other problems with STDIN
1585 and STDOUT (he proposed having a flag that is now the no_client_stdout
1586 flag).
1587
1588 Thanks to David (DSCHWEI) on cpan for asking for the nofatal option
1589 with syslog.
1590
1591 Thanks to Andreas Kippnick and Peter Beckman for suggesting leaving
1592 open child connections open during a HUP (this is now available via the
1593 leave_children_open_on_hup flag).
1594
1595 Thanks to LUPE on cpan for helping patch HUP with taint on.
1596
1597 Thanks to Michael Virnstein for fixing a bug in the check_for_dead
1598 section of PreFork server.
1599
1600 Thanks to Rob Mueller for patching PreForkSimple to only open lock_file
1601 once during parent call. This patch should be portable on systems
1602 supporting flock. Rob also suggested not closing STDIN/STDOUT but
1603 instead reopening them to /dev/null to prevent spurious warnings. Also
1604 suggested short circuit in post_accept if in UDP. Also for cleaning up
1605 some of the child managment code of PreFork.
1606
1607 Thanks to Mark Martinec for suggesting additional log messages for
1608 failure during accept.
1609
1610 Thanks to Bill Nesbitt and Carlos Velasco for pointing out double
1611 decrement bug in PreFork.pm (rt #21271)
1612
1613 Thanks to John W. Krahn for pointing out glaring precended with non-
1614 parened open and ||.
1615
1616 Thanks to Ricardo Signes for pointing out setuid bug for perl 5.6.1 (rt
1617 #21262).
1618
1619 Thanks to Carlos Velasco for updating the Syslog options (rt #21265).
1620 And for additional fixes later.
1621
1622 Thanks to Steven Lembark for pointing out that no_client_stdout wasn't
1623 working with the Multiplex server.
1624
1625 Thanks to Peter Beckman for suggesting allowing Sys::SysLog keyworks be
1626 passed through the ->log method and for suggesting we allow more types
1627 of characters through in syslog_ident. Also to Peter Beckman for
1628 pointing out that a poorly setup localhost will cause tests to hang.
1629
1630 Thanks to Curtis Wilbar for pointing out that the Fork server called
1631 post_accept_hook twice. Changed to only let the child process call
1632 this, but added the pre_fork_hook method.
1633
1634 And just a general Thanks You to everybody who is using Net::Server or
1635 who has contributed fixes over the years.
1636
1637 Thanks to Paul Miller for some ->autoflush, FileHandle fixes.
1638
1639 Thanks to Patrik Wallstrom for suggesting handling syslog errors
1640 better.
1641
1642 Thanks again to Rob Mueller for more logic cleanup for child accounting
1643 in PreFork server.
1644
1645 Thanks to David Schweikert for suggesting handling setlogsock a little
1646 better on newer versions of Sys::Syslog (>= 0.15).
1647
1648 Thanks to Mihail Nasedkin for suggesting adding a hook that is now
1649 called post_client_connection_hook.
1650
1651 Thanks to Graham Barr for adding the ability to set the check_for_spawn
1652 and min_child_ttl settings of the PreFork server.
1653
1654 Thanks to Daniel Kahn Gillmor for adding the other_child_died_hook.
1655
1656 Thanks to Dominic Humphries for helping not kill pid files on HUP.
1657
1658 Thanks to Kristoffer Møllerhøj for fixing UDP on Multiplex.
1659
1660 Thanks to mishikal for patches for helping identify un-cleaned up
1661 children.
1662
1663 Thanks to rpkelly and tim@retout for pointing out error in header regex
1664 of HTTP.
1665
1666 Thanks to dmcbride for some basic HTTP parsing fixes, as well as for
1667 some broken tied handle fixes.
1668
1669 Thanks to Gareth for pointing out glaring bug issues with broken pipe
1670 and semaphore serialization.
1671
1672 Thanks to CATONE for sending the idea for arbitrary signal passing to
1673 children. (See the sig_passthrough option)
1674
1675 Thanks to intrigeri@boum for pointing out and giving code ideas for
1676 NS_port not functioning after a HUP.
1677
1678 Thanks to Sergey Zasenko for adding sysread/syswrite support to SSLEAY
1679 as well as the base test.
1680
1681 Thanks to mbarbon@users. for adding tally dequeue to prefork server.
1682
1683 Thanks to stefanos@cpan for fixes to PreFork under Win32
1684
1685 Thanks to Mark Martinec for much of the initial work towards getting
1686 IPv6 going.
1687
1688 Thanks to the munin developers and Nicolai Langfeldt for hosting the
1689 development verion of Net::Server for so long and for fixes to the
1690 allow_deny checking for IPv6 addresses.
1691
1692 Thanks to Tatsuhiko Miyagawa for feedback, and for suggesting adding
1693 graceful shutdowns and hot deploy (max_servers adjustment).
1694
1695 Thanks to TONVOON@cpan for submitting a patch adding Log4perl
1696 functionality.
1697
1698 Thanks to Miko O'Sullivan for fixes to HTTP to correct tainting issues
1699 and passing initial log fixes, and for patches to fix CLOSE on tied
1700 stdout and various other HTTP issues.
1701
1703 Please see also Net::Server::Fork, Net::Server::INET,
1704 Net::Server::PreForkSimple, Net::Server::PreFork,
1705 Net::Server::MultiType, Net::Server::Single Net::Server::HTTP
1706
1708 Improve test suite to fully cover code (using Devel::Cover). Anybody
1709 that wanted to send me patches to the t/*.t tests that improved
1710 coverage would earn a big thank you.
1711
1713 https://github.com/rhandom/perl-net-server
1714
1716 Paul Seamons <paul at seamons.com>
1717 http://seamons.com/
1718
1719 Rob Brown <bbb at cpan.org>
1720
1722 This package may be distributed under the terms of either the
1723
1724 GNU General Public License
1725 or the
1726 Perl Artistic License
1727
1728 All rights reserved.
1729
1731 Hey! The above document had some coding errors, which are explained
1732 below:
1733
1734 Around line 1754:
1735 Non-ASCII character seen before =encoding in 'Møllerhøj'. Assuming
1736 UTF-8
1737
1738
1739
1740perl v5.34.0 2022-01-21 Net::Server(3)