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 \"$_\"\r\n"; # basic echo
19 last if /quit/i;
20 }
21 }
22
23 MyPackage->run(port => 160);
24
26 * Single Server Mode
27 * Inetd Server Mode
28 * Preforking Simple Mode (PreForkSimple)
29 * Preforking Managed Mode (PreFork)
30 * Forking Mode
31 * Multiplexing Mode using a single process
32 * Multi port accepts on Single, Preforking, and Forking modes
33 * Simultaneous accept/recv on tcp, udp, and unix sockets
34 * Safe signal handling in Fork/PreFork avoids perl signal trouble
35 * User customizable hooks
36 * Chroot ability after bind
37 * Change of user and group after bind
38 * Basic allow/deny access control
39 * Customized logging (choose Syslog, log_file, or STDERR)
40 * HUP able server (clean restarts via sig HUP)
41 * Dequeue ability in all Fork and PreFork modes.
42 * Taint clean
43 * Written in Perl
44 * Protection against buffer overflow
45 * Clean process flow
46 * Extensibility
47
49 "Net::Server" is an extensible, generic Perl server engine.
50 "Net::Server" combines the good properties from "Net::Daemon" (0.34),
51 "NetServer::Generic" (1.03), and "Net::FTPServer" (1.0), and also from
52 various concepts in the Apache Webserver.
53
54 "Net::Server" attempts to be a generic server as in "Net::Daemon" and
55 "NetServer::Generic". It includes with it the ability to run as an
56 inetd process ("Net::Server::INET"), a single connection server
57 ("Net::Server" or "Net::Server::Single"), a forking server
58 ("Net::Server::Fork"), a preforking server which maintains a constant
59 number of preforked children ("Net::Server::PreForkSimple"), or as a
60 managed preforking server which maintains the number of children based
61 on server load ("Net::Server::PreFork"). In all but the inetd type,
62 the server provides the ability to connect to one or to multiple server
63 ports.
64
65 "Net::Server" uses ideologies of "Net::FTPServer" in order to provide
66 extensibility. The additional server types are made possible via "per‐
67 sonalities" or sub classes of the "Net::Server". By moving the multi‐
68 ple types of servers out of the main "Net::Server" class, the
69 "Net::Server" concept is easily extended to other types (in the near
70 future, we would like to add a "Thread" personality).
71
72 "Net::Server" borrows several concepts from the Apache Webserver.
73 "Net::Server" uses "hooks" to allow custom servers such as SMTP, HTTP,
74 POP3, etc. to be layered over the base "Net::Server" class. In addi‐
75 tion the "Net::Server::PreFork" class borrows concepts of
76 min_start_servers, max_servers, and min_waiting servers.
77 "Net::Server::PreFork" also uses the concept of an flock serialized
78 accept when accepting on multiple ports (PreFork can choose between
79 flock, IPC::Semaphore, and pipe to control serialization).
80
82 "Net::Server" is built around a common class (Net::Server) and is
83 extended using sub classes, or "personalities". Each personality
84 inherits, overrides, or enhances the base methods of the base class.
85
86 Included with the Net::Server package are several basic personalities,
87 each of which has their own use.
88
89 Fork
90 Found in the module Net/Server/Fork.pm (see Net::Server::Fork).
91 This server binds to one or more ports and then waits for a connec‐
92 tion. When a client request is received, the parent forks a child,
93 which then handles the client and exits. This is good for moder‐
94 ately hit services.
95
96 INET
97 Found in the module Net/Server/INET.pm (see Net::Server::INET).
98 This server is designed to be used with inetd. The "pre_bind",
99 "bind", "accept", and "post_accept" are all overridden as these
100 services are taken care of by the INET daemon.
101
102 MultiType
103 Found in the module Net/Server/MultiType.pm (see Net::Server::Mul‐
104 tiType). This server has no server functionality of its own. It
105 is designed for servers which need a simple way to easily switch
106 between different personalities. Multiple "server_type" parameters
107 may be given and Net::Server::MultiType will cycle through until it
108 finds a class that it can use.
109
110 Multiplex
111 Found in the module Net/Server/Multiplex.pm (see Net::Server::Mul‐
112 tiplex). This server binds to one or more ports. It uses IO::Mul‐
113 tiplex to multiplex between waiting for new connections and waiting
114 for input on currently established connections. This personality
115 is designed to run as one process without forking. The
116 "process_request" method is never used but the "mux_input" callback
117 is used instead (see also IO::Multiplex). See examples/sam‐
118 plechat.pl for an example using most of the features of
119 Net::Server::Multiplex.
120
121 PreForkSimple
122 Found in the module Net/Server/PreFork.pm (see Net::Server::Pre‐
123 Fork). This server binds to one or more ports and then forks
124 "max_servers" child process. The server will make sure that at any
125 given time there are always "max_servers" available to receive a
126 client request. Each of these children will process up to
127 "max_requests" client connections. This type is good for a heavily
128 hit site that can dedicate max_server processes no matter what the
129 load. It should scale well for most applications. Multi port
130 accept is accomplished using either flock, IPC::Semaphore, or pipe
131 to serialize the children. Serialization may also be switched on
132 for single port in order to get around an OS that does not allow
133 multiple children to accept at the same time. For a further dis‐
134 cussion of serialization see Net::Server::PreFork.
135
136 PreFork
137 Found in the module Net/Server/PreFork.pm (see Net::Server::Pre‐
138 Fork). This server binds to one or more ports and then forks
139 "min_servers" child process. The server will make sure that at any
140 given time there are at least "min_spare_servers" but not more than
141 "max_spare_servers" available to receive a client request, up to
142 "max_servers". Each of these children will process up to
143 "max_requests" client connections. This type is good for a heavily
144 hit site, and should scale well for most applications. Multi port
145 accept is accomplished using either flock, IPC::Semaphore, or pipe
146 to serialize the children. Serialization may also be switched on
147 for single port in order to get around an OS that does not allow
148 multiple children to accept at the same time. For a further dis‐
149 cussion of serialization see Net::Server::PreFork.
150
151 Single
152 All methods fall back to Net::Server. This personality is provided
153 only as parallelism for Net::Server::MultiType.
154
155 "Net::Server" was partially written to make it easy to add new person‐
156 alities. Using separate modules built upon an open architecture allows
157 for easy addition of new features, a separate development process, and
158 reduced code bloat in the core module.
159
161 Once started, the Net::Server will take care of binding to port and
162 waiting for connections. Once a connection is received, the
163 Net::Server will accept on the socket and will store the result (the
164 client connection) in $self->{server}->{client}. This property is a
165 Socket blessed into the the IO::Socket classes. UDP servers are
166 slightly different in that they will perform a recv instead of an
167 accept.
168
169 To make programming easier, during the post_accept phase, STDIN and
170 STDOUT are opened to the client connection. This allows for programs
171 to be written using <STDIN> and print "out\n" to print to the client
172 connection. UDP will require using a ->send call.
173
175 The following is a very simple server. The main functionality occurs
176 in the process_request method call as shown below. Notice the use of
177 timeouts to prevent Denial of Service while reading. (Other examples
178 of using "Net::Server" can, or will, be included with this distribu‐
179 tion).
180
181 #!/usr/bin/perl -w -T
182 #--------------- file test.pl ---------------
183
184 package MyPackage;
185
186 use strict;
187 use base qw(Net::Server::PreFork); # any personality will do
188
189 MyPackage->run;
190
191 ### over-ridden subs below
192
193 sub process_request {
194 my $self = shift;
195 eval {
196
197 local $SIG{ALRM} = sub { die "Timed Out!\n" };
198 my $timeout = 30; # give the user 30 seconds to type a line
199
200 my $previous_alarm = alarm($timeout);
201 while( <STDIN> ){
202 s/\r?\n$//;
203 print "You said \"$_\"\r\n";
204 alarm($timeout);
205 }
206 alarm($previous_alarm);
207
208 };
209
210 if( $@=~/timed out/i ){
211 print STDOUT "Timed Out.\r\n";
212 return;
213 }
214
215 }
216
217 1;
218
219 #--------------- file test.pl ---------------
220
221 Playing this file from the command line will invoke a Net::Server using
222 the PreFork personality. When building a server layer over the
223 Net::Server, it is important to use features such as timeouts to pre‐
224 vent Denial of Service attacks.
225
227 There are five possible ways to pass arguments to Net::Server. They
228 are passing on command line, using a conf file, passing parameters to
229 run, returning values in the default_values method, or using a pre-
230 built object to call the run method (such as that returned by the new
231 method).
232
233 The "options" method is used to determine which arguments the server
234 will search for. Any arguments found from the command line, parameters
235 passed to run, and arguments found in the conf_file will be matched
236 against the keys of the options template. Any commandline parameters
237 that do not match will be left in place and can be further processed by
238 the server in the various hooks (by looking at @ARGV).
239
240 Arguments consist of key value pairs. On the commandline these pairs
241 follow the POSIX fashion of "--key value" or "--key=value", and also
242 "key=value". In the conf file the parameter passing can best be shown
243 by the following regular expression:
244 ($key,$val)=~/^(\w+)\s+(\S+?)\s+$/. Passing arguments to the run
245 method is done as follows: "Net::Server-"run(key1 => 'val1')>. Passing
246 arguments via a prebuilt object can best be shown in the following
247 code:
248
249 #!/usr/bin/perl -w -T
250 #--------------- file test2.pl ---------------
251 package MyPackage;
252 use strict;
253 use base qw(Net::Server);
254
255 my $server = MyPackage->new({
256 key1 => 'val1',
257 });
258
259 $server->run;
260 #--------------- file test2.pl ---------------
261
262 All five methods for passing arguments may be used at the same time.
263 Once an argument has been set, it is not over written if another method
264 passes the same argument. "Net::Server" will look for arguments in the
265 following order:
266
267 1) Arguments contained in the prebuilt object.
268 2) Arguments passed on command line.
269 3) Arguments passed to the run method.
270 4) Arguments passed via a conf file.
271 5) Arguments set in default_values method.
272 6) Arguments set in the configure_hook.
273
274 Each of these levels will override parameters of the same name speci‐
275 fied in subsequent levels. For example, specifying --setsid=0 on the
276 command line will override a value of "setsid 1" in the conf file.
277
278 Note that the configure_hook method doesn't return values to set, but
279 is there to allow for setting up configured values before the configure
280 method is called.
281
282 Key/value pairs used by the server are removed by the configuration
283 process so that server layers on top of "Net::Server" can pass and read
284 their own parameters.
285
287 It is possible to add in your own custom parameters to those parsed by
288 Net::Server. The following code shows how this is done:
289
290 sub options {
291 my $self = shift;
292 my $prop = $self->{'server'};
293 my $template = shift;
294
295 ### setup options in the parent classes
296 $self->SUPER::options($template);
297
298 ### add a single value option
299 $prop->{'my_option'} = undef;
300 $template->{'my_option'} = \ $prop->{'my_option'};
301
302 ### add a multi value option
303 $prop->{'an_arrayref_item'} ⎪⎪= [];
304 $template->{'an_arrayref_item'} = $prop->{'an_arrayref_item'};
305 }
306
307 Overriding the "options" method allows for adding your own custom
308 fields. A template hashref is passed in, that should then be modified
309 to contain an of your custom fields. Fields which are intended to
310 receive a single scalar value should have a reference to the destina‐
311 tion scalar given. Fields which are intended to receive multiple val‐
312 ues should reference the corresponding destination arrayref.
313
314 You are responsible for validating your custom options once they have
315 been parsed. The post_configure_hook is a good place to do your vali‐
316 dation.
317
319 The following arguments are available in the default "Net::Server" or
320 "Net::Server::Single" modules. (Other personalities may use additional
321 parameters and may optionally not use parameters from the base class.)
322
323 Key Value Default
324 conf_file "filename" undef
325
326 log_level 0-4 2
327 log_file (filename⎪Sys::Syslog) undef
328
329 ## syslog parameters
330 syslog_logsock (unix⎪inet) unix
331 syslog_ident "identity" "net_server"
332 syslog_logopt (cons⎪ndelay⎪nowait⎪pid) pid
333 syslog_facility \w+ daemon
334
335 port \d+ 20203
336 host "host" "*"
337 proto (tcp⎪udp⎪unix) "tcp"
338 listen \d+ SOMAXCONN
339
340 reverse_lookups 1 undef
341 allow /regex/ none
342 deny /regex/ none
343 cidr_allow CIDR none
344 cidr_deny CIDR none
345
346 ## daemonization parameters
347 pid_file "filename" undef
348 chroot "directory" undef
349 user (uid⎪username) "nobody"
350 group (gid⎪group) "nobody"
351 background 1 undef
352 setsid 1 undef
353
354 no_close_by_child (1⎪undef) undef
355
356 ## See Net::Server::Proto::(TCP⎪UDP⎪UNIX⎪etc)
357 ## for more sample parameters.
358
359 conf_file
360 Filename from which to read additional key value pair arguments for
361 starting the server. Default is undef.
362
363 log_level
364 Ranges from 0 to 4 in level. Specifies what level of error will be
365 logged. "O" means logging is off. "4" means very verbose. These
366 levels should be able to correlate to syslog levels. Default is 2.
367 These levels correlate to syslog levels as defined by the following
368 key/value pairs: 0=>'err', 1=>'warning', 2=>'notice', 3=>'info',
369 4=>'debug'.
370
371 log_file
372 Name of log file to be written to. If no name is given and hook is
373 not overridden, log goes to STDERR. Default is undef. If the
374 magic name "Sys::Syslog" is used, all logging will take place via
375 the Sys::Syslog module. If syslog is used the parameters "sys‐
376 log_logsock", "syslog_ident", and "syslog_logopt",and "sys‐
377 log_facility" may also be defined. If a "log_file" is given or if
378 "setsid" is set, STDIN and STDOUT will automatically be opened to
379 /dev/null and STDERR will be opened to STDOUT. This will prevent
380 any output from ending up at the terminal.
381
382 pid_file
383 Filename to store pid of parent process. Generally applies only to
384 forking servers. Default is none (undef).
385
386 syslog_logsock
387 Only available if "log_file" is equal to "Sys::Syslog". May be
388 either "unix" of "inet". Default is "unix". See Sys::Syslog.
389
390 syslog_ident
391 Only available if "log_file" is equal to "Sys::Syslog". Id to
392 prepend on syslog entries. Default is "net_server". See Sys::Sys‐
393 log.
394
395 syslog_logopt
396 Only available if "log_file" is equal to "Sys::Syslog". May be
397 either zero or more of "pid","cons","ndelay","nowait". Default is
398 "pid". See Sys::Syslog.
399
400 syslog_facility
401 Only available if "log_file" is equal to "Sys::Syslog". See
402 Sys::Syslog and syslog. Default is "daemon".
403
404 port
405 See Net::Server::Proto. Local port/socket on which to bind. If
406 low port, process must start as root. If multiple ports are given,
407 all will be bound at server startup. May be of the form
408 "host:port/proto", "host:port", "port/proto", or "port", where host
409 represents a hostname residing on the local box, where port repre‐
410 sents either the number of the port (eg. "80") or the service des‐
411 ignation (eg. "http"), and where proto represents the protocol to
412 be used. See Net::Server::Proto. If you are working with unix
413 sockets, you may also specify "socket_file⎪unix" or
414 "socket_file⎪type⎪unix" where type is SOCK_DGRAM or SOCK_STREAM.
415 If the protocol is not specified, proto will default to the "proto"
416 specified in the arguments. If "proto" is not specified there it
417 will default to "tcp". If host is not specified, host will default
418 to "host" specified in the arguments. If "host" is not specified
419 there it will default to "*". Default port is 20203. Configura‐
420 tion passed to new or run may be either a scalar containing a sin‐
421 gle port number or an arrayref of ports.
422
423 host
424 Local host or addr upon which to bind port. If a value of '*' is
425 given, the server will bind that port on all available addresses on
426 the box. See Net::Server::Proto. See IO::Socket. Configuration
427 passed to new or run may be either a scalar containing a single
428 host or an arrayref of hosts - if the hosts array is shorter than
429 the ports array, the last host entry will be used to augment the
430 hosts arrary to the size of the ports array.
431
432 proto
433 See Net::Server::Proto. Protocol to use when binding ports. See
434 IO::Socket. As of release 0.70, Net::Server supports tcp, udp, and
435 unix. Other types will need to be added later (or custom modules
436 extending the Net::Server::Proto class may be used). Configuration
437 passed to new or run may be either a scalar containing a single
438 proto or an arrayref of protos - if the protos array is shorter
439 than the ports array, the last proto entry will be used to augment
440 the protos arrary to the size of the ports array.
441
442 listen
443 See L<IO::Socket>. Not used with udp protocol (or UNIX SOCK_DGRAM).
444
445 reverse_lookups
446 Specify whether to lookup the hostname of the connected IP. Infor‐
447 mation is cached in server object under "peerhost" property.
448 Default is to not use reverse_lookups (undef).
449
450 allow/deny
451 May be specified multiple times. Contains regex to compare to
452 incoming peeraddr or peerhost (if reverse_lookups has been
453 enabled). If allow or deny options are given, the incoming client
454 must match an allow and not match a deny or the client connection
455 will be closed. Defaults to empty array refs.
456
457 cidr_allow/cidr_deny
458 May be specified multiple times. Contains a CIDR block to compare
459 to incoming peeraddr. If cidr_allow or cidr_deny options are
460 given, the incoming client must match a cidr_allow and not match a
461 cidr_deny or the client connection will be closed. Defaults to
462 empty array refs.
463
464 chroot
465 Directory to chroot to after bind process has taken place and the
466 server is still running as root. Defaults to undef.
467
468 user
469 Userid or username to become after the bind process has occured.
470 Defaults to "nobody." If you would like the server to run as root,
471 you will have to specify "user" equal to "root".
472
473 group
474 Groupid or groupname to become after the bind process has occured.
475 Defaults to "nobody." If you would like the server to run as root,
476 you will have to specify "group" equal to "root".
477
478 background
479 Specifies whether or not the server should fork after the bind
480 method to release itself from the command line. Defaults to undef.
481 Process will also background if "setsid" is set.
482
483 setsid
484 Specifies whether or not the server should fork after the bind
485 method to release itself from the command line and then run the
486 "POSIX::setsid()" command to truly daemonize. Defaults to undef.
487 If a "log_file" is given or if "setsid" is set, STDIN and STDOUT
488 will automatically be opened to /dev/null and STDERR will be opened
489 to STDOUT. This will prevent any output from ending up at the ter‐
490 minal.
491
492 no_close_by_child
493 Boolean. Specifies whether or not a forked child process has per‐
494 mission or not to shutdown the entire server process. If set to 1,
495 the child may NOT signal the parent to shutdown all children.
496 Default is undef (not set).
497
498 no_client_stdout
499 Boolean. Default undef (not set). Specifies that STDIN and STDOUT
500 should not be opened on the client handle once a connection has
501 been accepted. By default the Net::Server will open STDIN and STD‐
502 OUT on the client socket making it easier for many types of scripts
503 to read directly from and write directly to the socket using normal
504 print and read methods. Disabling this is useful on clients that
505 may be opening their own connections to STDIN and STDOUT.
506
507 This option has no affect on STDIN and STDOUT which has a magic
508 client property that is tied to the already open STDIN and STDOUT.
509
510 leave_children_open_on_hup
511 Boolean. Default undef (not set). If set, the parent will not
512 attempt to close child processes if the parent receives a SIG HUP.
513 The parent will rebind the the open port and begin tracking a fresh
514 set of children.
515
516 Children of a Fork server will exit after their current request.
517 Children of a Prefork type server will finish the current request
518 and then exit.
519
520 Note - the newly restarted parent will start up a fresh set of
521 servers on fork servers. The new parent will attempt to keep track
522 of the children from the former parent but custom communication
523 channels (open pipes from the child to the old parent) will no
524 longer be available to the old child processes. New child pro‐
525 cesses will still connect properly to the new parent.
526
528 All of the "ARGUMENTS" listed above become properties of the server
529 object under the same name. These properties, as well as other inter‐
530 nal properties, are available during hooks and other method calls.
531
532 The structure of a Net::Server object is shown below:
533
534 $self = bless( {
535 'server' => {
536 'key1' => 'val1',
537 # more key/vals
538 }
539 }, 'Net::Server' );
540
541 This structure was chosen so that all server related properties are
542 grouped under a single key of the object hashref. This is so that
543 other objects could layer on top of the Net::Server object class and
544 still have a fairly clean namespace in the hashref.
545
546 You may get and set properties in two ways. The suggested way is to
547 access properties directly via
548
549 my $val = $self->{server}->{key1};
550
551 Accessing the properties directly will speed the server process. A
552 second way has been provided for object oriented types who believe in
553 methods. The second way consists of the following methods:
554
555 my $val = $self->get_property( 'key1' );
556 my $self->set_property( key1 => 'val1' );
557
558 Properties are allowed to be changed at any time with caution (please
559 do not undef the sock property or you will close the client connec‐
560 tion).
561
563 "Net::Server" allows for the use of a configuration file to read in
564 server parameters. The format of this conf file is simple key value
565 pairs. Comments and white space are ignored.
566
567 #-------------- file test.conf --------------
568
569 ### user and group to become
570 user somebody
571 group everybody
572
573 ### logging ?
574 log_file /var/log/server.log
575 log_level 3
576 pid_file /tmp/server.pid
577
578 ### optional syslog directive
579 ### used in place of log_file above
580 #log_file Sys::Syslog
581 #syslog_logsock unix
582 #syslog_ident myserver
583 #syslog_logopt pid⎪cons
584
585 ### access control
586 allow .+\.(net⎪com)
587 allow domain\.com
588 deny a.+
589 cidr_allow 127.0.0.0/8
590 cidr_allow 192.0.2.0/24
591 cidr_deny 192.0.2.4/30
592
593 ### background the process?
594 background 1
595
596 ### ports to bind (this should bind
597 ### 127.0.0.1:20205 and localhost:20204)
598 ### See Net::Server::Proto
599 host 127.0.0.1
600 port localhost:20204
601 port 20205
602
603 ### reverse lookups ?
604 # reverse_lookups on
605
606 #-------------- file test.conf --------------
607
609 The process flow is written in an open, easy to override, easy to hook,
610 fashion. The basic flow is shown below. This is the flow of the
611 "$self->run" method.
612
613 $self->configure_hook;
614
615 $self->configure(@_);
616
617 $self->post_configure;
618
619 $self->post_configure_hook;
620
621 $self->pre_bind;
622
623 $self->bind;
624
625 $self->post_bind_hook;
626
627 $self->post_bind;
628
629 $self->pre_loop_hook;
630
631 $self->loop;
632
633 ### routines inside a standard $self->loop
634 # $self->accept;
635 # $self->run_client_connection;
636 # $self->done;
637
638 $self->pre_server_close_hook;
639
640 $self->server_close;
641
642 The server then exits.
643
644 During the client processing phase ("$self->run_client_connection"),
645 the following represents the program flow:
646
647 $self->post_accept;
648
649 $self->get_client_info;
650
651 $self->post_accept_hook;
652
653 if( $self->allow_deny
654
655 && $self->allow_deny_hook ){
656
657 $self->process_request;
658
659 }else{
660
661 $self->request_denied_hook;
662
663 }
664
665 $self->post_process_request_hook;
666
667 $self->post_process_request;
668
669 The process then loops and waits for the next connection. For a more
670 in depth discussion, please read the code.
671
672 During the server shutdown phase ("$self->server_close"), the following
673 represents the program flow:
674
675 $self->close_children; # if any
676
677 $self->post_child_cleanup_hook;
678
679 if( Restarting server ){
680 $self->restart_close_hook();
681 $self->hup_server;
682 }
683
684 $self->shutdown_sockets;
685
686 $self->server_exit;
687
689 "$self->run"
690 This method incorporates the main process flow. This flow is
691 listed above.
692
693 The method run may be called in any of the following ways.
694
695 MyPackage->run(port => 20201);
696
697 MyPackage->new({port => 20201})->run;
698
699 my $obj = bless {server=>{port => 20201}}, 'MyPackage';
700 $obj->run;
701
702 The ->run method should typically be the last method called in a
703 server start script (the server will exit at the end of the ->run
704 method).
705
706 "$self->configure"
707 This method attempts to read configurations from the commandline,
708 from the run method call, or from a specified conf_file. All of
709 the configured parameters are then stored in the {"server"} prop‐
710 erty of the Server object.
711
712 "$self->post_configure"
713 The post_configure hook begins the startup of the server. During
714 this method running server instances are checked for, pid_files are
715 created, log_files are created, Sys::Syslog is initialized (as
716 needed), process backgrounding occurs and the server closes STDIN
717 and STDOUT (as needed).
718
719 "$self->pre_bind"
720 This method is used to initialize all of the socket objects used by
721 the server.
722
723 "$self->bind"
724 This method actually binds to the inialized sockets (or rebinds if
725 the server has been HUPed).
726
727 "$self->post_bind"
728 During this method priveleges are dropped. The INT, TERM, and QUIT
729 signals are set to run server_close. Sig PIPE is set to IGNORE.
730 Sig CHLD is set to sig_chld. And sig HUP is set to call sig_hup.
731
732 Under the Fork, PreFork, and PreFork simple personalities, these
733 signals are registered using Net::Server::SIG to allow for safe
734 signal handling.
735
736 "$self->loop"
737 During this phase, the server accepts incoming connections. The
738 behavior of how the accepting occurs and if a child process handles
739 the connection is controlled by what type of Net::Server personal‐
740 ity the server is using.
741
742 Net::Server and Net::Server single accept only one connection at a
743 time.
744
745 Net::Server::INET runs one connection and then exits (for use by
746 inetd or xinetd daemons).
747
748 Net::Server::MultiPlex allows for one process to simultaneously
749 handle multiple connections (but requires rewriting the
750 process_request code to operate in a more "packet-like" manner).
751
752 Net::Server::Fork forks off a new child process for each incoming
753 connection.
754
755 Net::Server::PreForkSimple starts up a fixed number of processes
756 that all accept on incoming connections.
757
758 Net::Server::PreFork starts up a base number of child processes
759 which all accept on incoming connections. The server throttles the
760 number of processes running depending upon the number of requests
761 coming in (similar to concept to how Apache controls its child pro‐
762 cesses in a PreFork server).
763
764 Read the documentation for each of the types for more information.
765
766 "$self->server_close"
767 This method is called once the server has been signaled to end, or
768 signaled for the server to restart (via HUP), or the loop method
769 has been exited.
770
771 This method takes care of cleaning up any remaining child pro‐
772 cesses, setting appropriate flags on sockets (for HUPing), closing
773 up logging, and then closing open sockets.
774
775 "$self->server_exit"
776 This method is called at the end of server_close. It calls exit,
777 but may be overridden to do other items. At this point all ser‐
778 vices should be shut down.
779
781 "$self->run_client_connection"
782 This method is run after the server has accepted and received a
783 client connection. The full process flow is listed above under
784 PROCESS FLOWS. This method takes care of handling each client con‐
785 nection.
786
787 "$self->post_accept"
788 This method opens STDIN and STDOUT to the client socket. This
789 allows any of the methods during the run_client_connection phase to
790 print directly to and read directly from the client socket.
791
792 "$self->get_client_info"
793 This method looks up information about the client connection such
794 as ip address, socket type, and hostname (as needed).
795
796 "$self->allow_deny"
797 This method uses the rules defined in the allow and deny configura‐
798 tion parameters to determine if the ip address should be accepted.
799
800 "$self->process_request"
801 This method is intended to handle all of the client communication.
802 At this point STDIN and STDOUT are opened to the client, the ip
803 address has been verified. The server can then interact with the
804 client connection according to whatever API or protocol the server
805 is implementing. Note that the stub implementation uses STDIN and
806 STDOUT and will not work if the no_client_stdout flag is set.
807
808 This is the main method to override.
809
810 The default method implements a simple echo server that will repeat
811 whatever is sent. It will quit the child if "quit" is sent, and
812 will exit the server if "exit" is sent.
813
814 "$self->post_process_request"
815 This method is used to clean up the client connection and to handle
816 any parent/child accounting for the forking servers.
817
819 "Net::Server" provides a number of "hooks" allowing for servers layered
820 on top of "Net::Server" to respond at different levels of execution
821 without having to "SUPER" class the main built-in methods. The place‐
822 ment of the hooks can be seen in the PROCESS FLOW section.
823
824 Almost all of the default hook methods do nothing. To use a hook you
825 simply need to override the method in your subclass. For example to
826 add your own post_configure_hook you could do something like the fol‐
827 lowing:
828
829 package MyServer;
830
831 sub post_configure_hook {
832 my $self = shift;
833 my $prop = $self->{'server'};
834
835 # do some validation here
836 }
837
838 The following describes the hooks available in the plain Net::Server
839 class (other flavors such as Fork or PreFork have additional hooks).
840
841 "$self->configure_hook()"
842 This hook takes place immediately after the "->run()" method is
843 called. This hook allows for setting up the object before any
844 built in configuration takes place. This allows for custom config‐
845 urability.
846
847 "$self->post_configure_hook()"
848 This hook occurs just after the reading of configuration parameters
849 and initiation of logging and pid_file creation. It also occurs
850 before the "->pre_bind()" and "->bind()" methods are called. This
851 hook allows for verifying configuration parameters.
852
853 "$self->post_bind_hook()"
854 This hook occurs just after the bind process and just before any
855 chrooting, change of user, or change of group occurs. At this
856 point the process will still be running as the user who started the
857 server.
858
859 "$self->pre_loop_hook()"
860 This hook occurs after chroot, change of user, and change of group
861 has occured. It allows for preparation before looping begins.
862
863 "$self->can_read_hook()"
864 This hook occurs after a socket becomes readible on an
865 accept_multi_port request (accept_multi_port is used if there are
866 multiple bound ports to accept on, or if the "multi_port" configu‐
867 ration parameter is set to true). This hook is intended to allow
868 for processing of arbitrary handles added to the IO::Select used
869 for the accept_multi_port. These handles could be added during the
870 post_bind_hook. No internal support is added for processing these
871 handles or adding them to the IO::Socket. Care must be used in how
872 much occurs during the can_read_hook as a long response time will
873 result in the server being susceptible to DOS attacks. A return
874 value of true indicates that the Server should not pass the readi‐
875 ble handle on to the post_accept and process_request phases.
876
877 It is generally suggested that other avenues be pursued for sending
878 messages via sockets not created by the Net::Server.
879
880 "$self->post_accept_hook()"
881 This hook occurs after a client has connected to the server. At
882 this point STDIN and STDOUT are mapped to the client socket. This
883 hook occurs before the processing of the request.
884
885 "$self->allow_deny_hook()"
886 This hook allows for the checking of ip and host information beyond
887 the "$self->allow_deny()" routine. If this hook returns 1, the
888 client request will be processed, otherwise, the request will be
889 denied processing.
890
891 "$self->request_denied_hook()"
892 This hook occurs if either the "$self->allow_deny()" or
893 "$self->allow_deny_hook()" have taken place.
894
895 "$self->post_process_request_hook()"
896 This hook occurs after the processing of the request, but before
897 the client connection has been closed.
898
899 "$self->pre_server_close_hook()"
900 This hook occurs before the server begins shutting down.
901
902 "$self->write_to_log_hook"
903 This hook handles writing to log files. The default hook is to
904 write to STDERR, or to the filename contained in the parameter
905 "log_file". The arguments passed are a log level of 0 to 4 (4
906 being very verbose), and a log line. If log_file is equal to
907 "Sys::Syslog", then logging will go to Sys::Syslog and will bypass
908 the write_to_log_hook.
909
910 "$self->fatal_hook"
911 This hook occurs when the server has encountered an unrecoverable
912 error. Arguments passed are the error message, the package, file,
913 and line number. The hook may close the server, but it is sug‐
914 gested that it simply return and use the built in shut down fea‐
915 tures.
916
917 "$self->post_child_cleanup_hook"
918 This hook occurs in the parent server process after all children
919 have been shut down and just before the server either restarts or
920 exits. It is intended for additional cleanup of information. At
921 this point pid_files and lockfiles still exist.
922
923 "$self->restart_open_hook"
924 This hook occurs if a server has been HUPed (restarted via the HUP
925 signal. It occurs just before reopening to the filenos of the
926 sockets that were already opened.
927
928 "$self->restart_close_hook"
929 This hook occurs if a server has been HUPed (restarted via the HUP
930 signal. It occurs just before restarting the server via exec.
931
933 "$self->default_values"
934 Allow for returning configuration values that will be used if no
935 other value could be found.
936
937 Should return a hashref.
938
939 sub default_values {
940 return {
941 port => 20201,
942 };
943 }
944
945 "$self->new"
946 As of Net::Server 0.91 there is finally a new method. This method
947 takes a class name and an argument hashref as parameters. The
948 argument hashref becomes the "server" property of the object.
949
950 package MyPackage;
951 use base qw(Net::Server);
952
953 my $obj = MyPackage->new({port => 20201});
954
955 # same as
956
957 my $obj = bless {server => {port => 20201}}, 'MyPackage';
958
959 "$self->log"
960 Parameters are a log_level and a message.
961
962 If log_level is set to 'Sys::Syslog', the parameters may alter‐
963 nately be a log_level, a format string, and format string parame‐
964 ters. (The second parameter is assumed to be a format string if
965 additional arguments are passed along). Passing arbitrary format
966 strings to Sys::Syslog will allow the server to be vulnerable to
967 exploit. The server maintainer should make sure that any string
968 treated as a format string is controlled.
969
970 # assuming log_file = 'Sys::Syslog'
971
972 $self->log(1, "My Message with %s in it");
973 # sends "%s", "My Message with %s in it" to syslog
974
975 $self->log(1, "My Message with %s in it", "Foo");
976 # sends "My Message with %s in it", "Foo" to syslog
977
978 If log_file is set to a file (other than Sys::Syslog), the message
979 will be appended to the log file by calling the write_to_log_hook.
980
981 "$self->shutdown_sockets"
982 This method will close any remaining open sockets. This is called
983 at the end of the server_close method.
984
986 Each of the server personalities (except for INET), support restarting
987 via a HUP signal (see "kill -l"). When a HUP is received, the server
988 will close children (if any), make sure that sockets are left open, and
989 re-exec using the same commandline parameters that initially started
990 the server. (Note: for this reason it is important that @ARGV is not
991 modified until "->run" is called).
992
993 The Net::Server will attempt to find out the commandline used for
994 starting the program. The attempt is made before any configuration
995 files or other arguments are processed. The outcome of this attempt is
996 stored using the method "->commandline". The stored commandline may
997 also be retrieved using the same method name. The stored contents will
998 undoubtedly contain Tainted items that will cause the server to die
999 during a restart when using the -T flag (Taint mode). As it is impos‐
1000 sible to arbitrarily decide what is taint safe and what is not, the
1001 individual program must clean up the tainted items before doing a
1002 restart.
1003
1004 sub configure_hook{
1005 my $self = shift;
1006
1007 ### see the contents
1008 my $ref = $self->commandline;
1009 use Data::Dumper;
1010 print Dumper $ref;
1011
1012 ### arbitrary untainting - VERY dangerous
1013 my @untainted = map {/(.+)/;$1} @$ref;
1014
1015 $self->commandline(\@untainted)
1016 }
1017
1019 The following files are installed as part of this
1020 distribution.
1021
1022 Net/Server.pm
1023 Net/Server/Fork.pm
1024 Net/Server/INET.pm
1025 Net/Server/MultiType.pm
1026 Net/Server/PreForkSimple.pm
1027 Net/Server/PreFork.pm
1028 Net/Server/Single.pm
1029 Net/Server/Daemonize.pm
1030 Net/Server/SIG.pm
1031 Net/Server/Proto.pm
1032 Net/Server/Proto/*.pm
1033
1035 Download and extract tarball before running these commands in its base
1036 directory:
1037
1038 perl Makefile.PL
1039 make
1040 make test
1041 make install
1042
1044 Paul Seamons <paul at seamons.com>
1045
1047 Thanks to Rob Brown (bbb at cpan.org) for help with miscellaneous con‐
1048 cepts such as tracking down the serialized select via flock ala Apache
1049 and the reference to IO::Select making multiport servers possible. And
1050 for researching into allowing sockets to remain open upon exec (making
1051 HUP possible).
1052
1053 Thanks to Jonathan J. Miner <miner at doit.wisc.edu> for patching a
1054 blatant problem in the reverse lookups.
1055
1056 Thanks to Bennett Todd <bet at rahul.net> for pointing out a problem in
1057 Solaris 2.5.1 which does not allow multiple children to accept on the
1058 same port at the same time. Also for showing some sample code from
1059 Viktor Duchovni which now represents the semaphore option of the seri‐
1060 alize argument in the PreFork server.
1061
1062 Thanks to traveler and merlyn from http://perlmonks.org for pointing me
1063 in the right direction for determining the protocol used on a socket
1064 connection.
1065
1066 Thanks to Jeremy Howard <j+daemonize at howard.fm> for numerous sugges‐
1067 tions and for work on Net::Server::Daemonize.
1068
1069 Thanks to Vadim <vadim at hardison.net> for patches to implement par‐
1070 ent/child communication on PreFork.pm.
1071
1072 Thanks to Carl Lewis for suggesting "-" in user names.
1073
1074 Thanks to Slaven Rezic for suggesing Reuse => 1 in Proto::UDP.
1075
1076 Thanks to Tim Watt for adding udp_broadcast to Proto::UDP.
1077
1078 Thanks to Christopher A Bongaarts for pointing out problems with the
1079 Proto::SSL implementation that currently locks around the socket accept
1080 and the SSL negotiation. See Net::Server::Proto::SSL.
1081
1082 Thanks to Alessandro Zummo for pointing out various bugs including some
1083 in configuration, commandline args, and cidr_allow.
1084
1085 Thanks to various other people for bug fixes over the years. These and
1086 future thank-you's are available in the Changes file as well as CVS
1087 comments.
1088
1089 Thanks to Ben Cohen and tye (on Permonks) for finding and diagnosing
1090 more correct behavior for dealing with re-opening STDIN and STDOUT on
1091 the client handles.
1092
1093 Thanks to Mark Martinec for trouble shooting other problems with STDIN
1094 and STDOUT (he proposed having a flag that is now the no_client_stdout
1095 flag).
1096
1097 Thanks to David (DSCHWEI) on cpan for asking for the nofatal option
1098 with syslog.
1099
1100 Thanks to Andreas Kippnick and Peter Beckman for suggesting leaving
1101 open child connections open during a HUP (this is now available via the
1102 leave_children_open_on_hup flag).
1103
1104 Thanks to LUPE on cpan for helping patch HUP with taint on.
1105
1106 Thanks to Michael Virnstein for fixing a bug in the check_for_dead sec‐
1107 tion of PreFork server.
1108
1109 Thanks to Rob Mueller for patching PreForkSimple to only open lock_file
1110 once during parent call. This patch should be portable on systems sup‐
1111 porting flock. Rob also suggested not closing STDIN/STDOUT but instead
1112 reopening them to /dev/null to prevent spurious warnings. Also sug‐
1113 gested short circuit in post_accept if in UDP. Also for cleaning up
1114 some of the child managment code of PreFork.
1115
1116 Thanks to Mark Martinec for suggesting additional log messages for
1117 failure during accept.
1118
1119 Thanks to Bill Nesbitt and Carlos Velasco for pointing out double
1120 decrement bug in PreFork.pm (rt #21271)
1121
1122 Thanks to John W. Krahn for pointing out glaring precended with non-
1123 parened open and ⎪⎪.
1124
1125 Thanks to Ricardo Signes for pointing out setuid bug for perl 5.6.1 (rt
1126 #21262).
1127
1128 Thanks to Carlos Velasco for updating the Syslog options (rt #21265).
1129
1130 Thanks to Steven Lembark for pointing out that no_client_stdout wasn't
1131 working with the Multiplex server.
1132
1133 Thanks to Peter Beckman for suggesting allowing Sys::SysLog keyworks be
1134 passed through the ->log method and for suggesting we allow more types
1135 of characters through in syslog_ident. Also to Peter Beckman for
1136 pointing out that a poorly setup localhost will cause tests to hang.
1137
1138 Thanks to Curtis Wilbar for pointing out that the Fork server called
1139 post_accept_hook twice. Changed to only let the child process call
1140 this, but added the pre_fork_hook method.
1141
1142 And just a general Thanks You to everybody who is using Net::Server or
1143 who has contributed fixes over the years.
1144
1146 Please see also Net::Server::Fork, Net::Server::INET, Net::Server::Pre‐
1147 ForkSimple, Net::Server::PreFork, Net::Server::MultiType,
1148 Net::Server::Single
1149
1151 Paul Seamons <paul at seamons.com>
1152 http://seamons.com/
1153
1154 Rob Brown <bbb at cpan.org>
1155
1157 This package may be distributed under the terms of either the
1158 GNU General Public License
1159 or the
1160 Perl Artistic License
1161
1162 All rights reserved.
1163
1164
1165
1166perl v5.8.8 2007-02-03 Net::Server(3)