Net::Server(3)
π Net::Server(3) β User Contributed Perl Documentation π
okay bestie, buckle in, because we're about to talk about Net::Server(3) β yes that's the manual page, yes it's a whole vibe, and yes you're gonna understand it by the end. β¨
β¨ NAME β¨
Net::Server β the extensible, general Perl server engine. that's it, that's the name, and honestly it ate. π
π¦ SYNOPSIS π¦
okay so here's the whole thing in one look, no notes:
#!/usr/bin/perl -w -T
package MyPackage;
use base qw(Net::Server);
sub process_request {
my $self = shift;
while (<STDIN>) {
s/[\r\n]+$//;
print "You said '$_'\015\012"; # basic echo
last if /quit/i;
}
}
MyPackage->run(port => 160, ipv => '*');
# one liner to get going quickly
perl -e 'use base qw(Net::Server); main->run(port => 20208)'
π¨ NOTE, and this one's important fr fr: starting in Net::Server 2.005, the default value foripvisIPv*. what does that mean? it means that if no host is passed, or a hostname is passed, any available IPv4 and IPv6 sockets will be bound. if you wanna force IPv4 only, you just add anipv => 4configuration β and there are like, a half dozen ways we let you specify it, so pick your fighter. π
π FEATURES π
here's the menu, and it's giving chef's kiss:
- Full IPv6 support π¦
- Working SSL sockets and https (both with and without
IO::Socket::SSL) π₯ - Single Server Mode
- Inetd Server Mode
- Preforking Simple Mode (
PreForkSimple) - Preforking Managed Mode (
PreFork) - Forking Mode
- Multiplexing Mode using a single process
- Multi port accepts on Single, Preforking, and Forking modes
- Basic HTTP Daemon (supports IPv6, SSL, full apache style logs) π
- Basic PSGI Daemon
- Simultaneous accept/recv on tcp/udp/unix, ssl/tcp, and IPv4/IPv6 sockets
- Safe signal handling in Fork/PreFork avoids perl signal trouble
- User customizable hooks π
- Chroot ability after bind
- Change of user and group after bind
- Basic allow/deny access control
- Pluggable logging (
Sys::Syslog,Log::Log4perl,log_file,STDERR, or your own) π - HUP able server (clean restarts via sig HUP)
- Graceful shutdowns (via sig QUIT)
- Hot deploy in Fork and PreFork modes (via sig TTIN and TTOU)
- Dequeue ability in all Fork and PreFork modes.
- Taint clean β¨
- Written in Perl
- Protection against buffer overflow
- Clean process flow
- Extensibility
like, look at that list. it's long, it's comprehensive, it's the main character of server engines. π
π DESCRIPTION π
so, Net::Server is an extensible, generic Perl server engine. say it with me. π«Ά
it attempts to be a generic server, the same way Net::Daemon and NetServer::Generic are. and it comes with a whole little found family of abilities built right in:
- run as an inetd process (
Net::Server::INET) - a single connection server (
Net::ServerorNet::Server::Single) - a forking server (
Net::Server::Fork) - a preforking server that keeps a constant number of preforked children (
Net::Server::PreForkSimple) - or a managed preforking server that keeps the number of children based on server load (
Net::Server::PreFork)
and in all but the inetd type, the server can connect to one or to multiple server ports. multi-port? she does that. π
the extra server types exist thanks to "personalities" β which are just sub classes of Net::Server. and the whole point of moving all the different server types out of the main Net::Server class is that the Net::Server concept stays easy to extend to other types. (and yeah, in the near future they'd like to add a Thread personality β manifesting it for them π§)
also, Net::Server borrows several concepts from the Apache Webserver, which, respectfully, queen behavior. it uses "hooks" so you can layer custom servers like SMTP, HTTP, POP3, etc. over the base Net::Server class. and the Net::Server::PreFork class specifically borrows the concepts of min_start_servers, max_servers, and min_waiting servers. Net::Server::PreFork also uses the concept of an flock serialized accept when accepting on multiple ports β and PreFork can choose between flock, IPC::Semaphore, and pipe to control that serialization. choices! β
π PERSONALITIES π
Net::Server is built around one common class (Net::Server) and gets extended using sub classes β the personalities. each personality inherits, overrides, or enhances the base methods of the base class. it's giving nepotism but make it engineering. π
the Net::Server package ships with several basic personalities, and each one has its own ~thing~:
πΈ Fork
found in the module Net/Server/Fork.pm (see Net::Server::Fork). this server binds to one or more ports and then waits for a connection. when a client request comes in, the parent forks a child, which then handles the client and exits. good for moderately hit services.
πΈ INET
found in the module Net/Server/INET.pm (see Net::Server::INET). this server is designed to be used with inetd. pre_bind, bind, accept, and post_accept are all overridden, because those services are taken care of by the INET daemon. she doesn't do the work, she outsources it. π
πΈ MultiType
found in the module Net/Server/MultiType.pm (see Net::Server::MultiType). this server has no server functionality of its own β it's designed for servers that need a simple way to easily switch between different personalities. you can give multiple server_type parameters, and Net::Server::MultiType will cycle through until it finds a class it can use. it's a talent scout, basically. π
πΈ Multiplex
found in the module Net/Server/Multiplex.pm (see Net::Server::Multiplex). this server binds to one or more ports and uses IO::Multiplex to multiplex between waiting for new connections and waiting for input on currently established connections. this personality is designed to run as one process without forking. heads up: the process_request method is never used β the mux_input callback is used instead (see also IO::Multiplex). and if you want an example using most of the features of Net::Server::Multiplex, go look at examples/samplechat.pl. go, shoo, look. π¦
πΈ PreForkSimple
found in the module Net/Server/PreFork.pm (see Net::Server::PreFork). this server binds to one or more ports and then forks max_servers child process. the server makes sure that at any given time there are always max_servers available to receive a client request. each of those children will process up to max_requests client connections. this type is good for a heavily hit site that can dedicate max_server processes no matter what the load β and it should scale well for most applications. multi port accept is accomplished using either flock, IPC::Semaphore, or pipe to serialize the children. serialization may also be switched on for a single port, to get around an OS that doesn't allow multiple children to accept at the same time. for a further discussion of serialization, see Net::Server::PreFork. π
πΈ PreFork
found in the module Net/Server/PreFork.pm (see Net::Server::PreFork). this server binds to one or more ports and then forks min_servers child process. the server makes sure that at any given time there are at least min_spare_servers but not more than max_spare_servers available to receive a client request, up to max_servers. each of those children will process up to max_requests client connections. this type is good for a heavily hit site and should scale well for most applications. again: multi port accept uses either flock, IPC::Semaphore, or pipe to serialize the children, and serialization may also be switched on for a single port to get around an OS that doesn't allow multiple children to accept at the same time. for a further discussion of serialization, see Net::Server::PreFork. (yes bestie, this one's basically PreForkSimple's more emotionally mature sister π)
πΈ Single
all methods fall back to Net::Server. this personality is provided only as parallelism for Net::Server::MultiType. that's legit its whole job. π
πΈ HTTP
not a distinct personality. it provides a basic HTTP daemon. you can combine it with the SSL or SSLEAY proto to get an HTTPS Daemon. see Net::Server::HTTP. π₯
and to wrap the personality talk up: Net::Server was partially written to make it easy to add new personalities. using separate modules built on an open architecture means easy addition of new features, a separate development process, and reduced code bloat in the core module. iconic design philosophy ngl. β¨
π«Ά SOCKET ACCESS π«Ά
once started, Net::Server takes care of binding to port and waiting for connections. once a connection is received, Net::Server will accept on the socket and store the result (the client connection) in $self->{server}->{client}. that property is a Socket blessed into the IO::Socket classes. π¦
UDP servers are slightly different β they perform a recv instead of an accept. different strokes. π
to make programming easier, during the post_accept phase, STDIN and STDOUT are opened to the client connection. that means you can write programs using <STDIN> and print "out\n" to print to the client connection. UDP, though? UDP will require using a ->send call. no shortcuts there, sorry bestie. π
π SAMPLE CODE π
here's a very simple server. the main functionality happens in the process_request method call, as shown below. and notice the use of timeouts to prevent Denial of Service while reading β that part is not optional, that part is self-care. (other examples of using Net::Server can, or will, be included with this distribution. stay tuned. π)
#!/usr/bin/perl -w -T
package MyPackage;
use strict;
use base qw(Net::Server::PreFork); # any personality will do
MyPackage->run;
# over-ride the default echo handler
sub process_request {
my $self = shift;
eval {
local $SIG{'ALRM'} = sub { die "Timed Out!\n" };
my $timeout = 30; # give the user 30 seconds to type some lines
my $previous_alarm = alarm($timeout);
while (<STDIN>) {
s/\r?\n$//;
print "You said '$_'\r\n";
alarm($timeout);
}
alarm($previous_alarm);
};
if ($@ =~ /timed out/i) {
print STDOUT "Timed Out.\r\n";
return;
}
}
1;
running this file from the command line will invoke a Net::Server using the PreFork personality. and when you're building a server layer over Net::Server, it is important to use features like timeouts to prevent Denial Of Service attacks. seriously. do not skip the timeout. do not pass go. π¨
Net::Server comes with a built in echo server by default. you can test it out by simply running this from the commandline:
net-server
if you wanted to try another flavor, you could go:
net-server PreFork
if you wanted to try out a basic HTTP server, you could use:
net-server HTTP
or if you wanted to test out a CGI you're writing, you could use:
net-server HTTP --app ../../mycgi.cgi
and that's where we're pausing, bestie β because there is so much more coming π
π¬ ARGUMENTS π¬
Okay bestie, so there are at least five possible ways to pass arguments to Net::Server. They are: passing to the new method, passing on the command line, passing parameters to run, using a conf file, returning values in the default_values method, or configuring the values in post_configure_hook.
The options method is used to determine which arguments the server will search for and can be used to extend the parsed parameters. Any arguments found from the command line, parameters passed to run, and arguments found in the conf_file will be matched against the keys of the options template. Any commandline parameters that do not match will be left in place and can be further processed by the server in the various hooks (by looking at @ARGV). Arguments passed to new will automatically win over any other options β this can be used if you would like to disallow a user passing in other arguments.
Arguments consist of key value pairs. On the commandline these pairs follow the POSIX fashion of "--key value" or "--key=value", and also "key=value". In the conf file the parameter passing can best be shown by the following regular expression: ($key,$val)=~/^(\w+)\s+(\S+?)\s+$/. Passing arguments to the run method is done as follows: "<Net::Server->run(key1 =" 'val1')>>. Passing arguments via a prebuilt object can best be shown in the following code:
#!/usr/bin/perl -w -T
package MyPackage;
use strict;
use base qw(Net::Server);
my $server = MyPackage->new({
key1 => 'val1',
});
$server->run;
All five methods for passing arguments may be used at the same time. Once an argument has been set, it is not over written if another method passes the same argument. "Net::Server" will look for arguments in the following order:
- Arguments passed to the
newmethod. - Arguments passed on command line.
- Arguments passed to the
runmethod. - Arguments passed via a conf file.
- Arguments set in the
default_valuesmethod.
Additionally the following hooks are available:
- Arguments set in the
configure_hook(occurs afternewbut before any of the other areas are checked). - Arguments set and validated in the
post_configure_hook(occurs after all of the other areas are checked).
Each of these levels will override parameters of the same name specified in subsequent levels. For example, specifying --setsid=0 on the command line will override a value of "setsid 1" in the conf file.
Note that the configure_hook method doesn't return values to set, but is there to allow for setting up configured values before the configure method is called.
Key/value pairs used by the server are removed by the configuration process so that server layers on top of "Net::Server" can pass and read their own parameters.
π οΈ ADDING CUSTOM ARGUMENTS π οΈ
It is possible to add in your own custom parameters to those parsed by Net::Server. The following code shows how this is done:
sub options {
my $self = shift;
my $prop = $self->{'server'};
my $template = shift;
# setup options in the parent classes
$self->SUPER::options($template);
# add a single value option
$prop->{'my_option'} ||= undef;
$template->{'my_option'} = \ $prop->{'my_option'};
# add a multi value option
$prop->{'an_arrayref_item'} ||= [];
$template->{'an_arrayref_item'} = $prop->{'an_arrayref_item'};
}
Overriding the "options" method allows for adding your own custom fields. A template hashref is passed in, that should then be modified to contain any of your custom fields. Fields which are intended to receive a single scalar value should have a reference to the destination scalar given. Fields which are intended to receive multiple values should reference the corresponding destination arrayref.
You are responsible for validating your custom options once they have been parsed. The post_configure_hook is a good place to do your validation.
Some emails have asked why we use this "template" method. The idea is that you are creating the data structure to store the values in, and you are also creating a way to get the values into the data structure. The template is the way to get the values to the server's data structure. One of the possibilities (that probably isn't used that much) is that by letting you specify the mapping, you could build a nested data structure β even though the passed in arguments are flat. It also allows you to setup aliases to your names.
For example, a basic structure might look like this:
$prop = $self->{'server'}
$prop->{'my_custom_option'} ||= undef;
$prop->{'my_custom_array'} ||= [];
$template = {
my_custom_option => \ $prop->{'my_custom_option'},
mco => \ $prop->{'my_custom_option'}, # alias
my_custom_array => $prop->{'my_custom_array'},
mca => $prop->{'my_custom_array'}, # an alias
};
$template->{'mco2'} = $template->{'mco'}; # another way to alias
But you could also have more complex data:
$prop = $self->{'server'};
$prop->{'one_layer'} = {
two_layer => [
undef,
undef,
],
};
$template = {
param1 => \ $prop->{'one_layer'}->{'two_layer'}->[0],
param2 => \ $prop->{'one_layer'}->{'two_layer'}->[1],
};
This is of course a contrived example β but it does show that you can get the data from the flat passed in arguments to whatever type of structure you need β with only a little bit of effort.
π DEFAULT ARGUMENTS FOR Net::Server π
The following arguments are available in the default "Net::Server" or "Net::Server::Single" modules. (Other personalities may use additional parameters and may optionally not use parameters from the base class.)
Key Value Default
conf_file "filename" undef
log_level 0-4 2
log_file (filename|Sys::Syslog
|Log::Log4perl) undef
log_function undef
port \d+ 20203
host "host" "*"
ipv (4|6|*) *
proto (tcp|udp|unix) "tcp"
listen \d+ SOMAXCONN
ipv6_package (IO::Socket::INET6 IO::Socket::IP
|IO::Socket::IP)
## syslog parameters (if log_file eq Sys::Syslog)
syslog_logsock (native|unix|inet|udp
|tcp|stream|console) unix (on Sys::Syslog < 0.15)
syslog_ident "identity" "net_server"
syslog_logopt (cons|ndelay|nowait|pid) pid
syslog_facility \w+ daemon
reverse_lookups (1|double|double-debug) undef
double_reverse_lookups (1|debug|autofail) undef
allow /regex/ none
deny /regex/ none
cidr_allow CIDR none
cidr_deny CIDR none
## daemonization parameters
pid_file "filename" undef
chroot "directory" undef
user (uid|username) "nobody"
group (gid|group) "nobody"
background 1 undef
setsid 1 undef
no_close_by_child (1|undef) undef
## See Net::Server::Proto::(TCP|UDP|UNIX|SSL|SSLeay|etc)
## for more sample parameters.
ποΈ conf_file ποΈ
Filename from which to read additional key value pair arguments for starting the server. Default is undef.
There are two ways that you can specify a default location for a conf_file. The first is to pass the default value to the run method as in:
MyServer->run({
conf_file => '/etc/my_server.conf',
});
If the end user passes in --conf_file=/etc/their_server.conf then the value will be overridden.
The second way to do this was added in the 0.96 version. It uses the default_values method as in:
sub default_values {
return {
conf_file => '/etc/my_server.conf',
}
}
This method has the advantage of also being able to be overridden in the run method.
If you do not want the user to be able to specify a conf_file at all, you can pass conf_file to the new method when creating your object:
MyServer->new({
conf_file => '/etc/my_server.conf',
})->run;
If passed this way, the value passed to new will "win" over any of the other passed in values.
π log_level π
Ranges from 0 to 4 in level. Specifies what level of error will be logged. "O" means logging is off. "4" means very verbose. These levels should be able to correlate to syslog levels. Default is 2. These levels correlate to syslog levels as defined by the following key/value pairs: 0=>'err', 1=>'warning', 2=>'notice', 3=>'info', 4=>'debug'.
πͺ΅ log_file πͺ΅
Name of log file or log subsystem to be written to. If no name is given and the write_to_log_hook is not overridden, log goes to STDERR. Default is undef.
The log_file may also be the name of a Net::Server pluggable logging class. Net::Server is packaged with Sys::Syslog and Log::Log4perl. If the log_file looks like a module name, it will have "Net::Server::Log::" added to the front and it will then be required. The package should provide an "initialize" class method that returns a single function which will be used for logging. This returned function will be passed log_level, and message.
If the magic name "Sys::Syslog" is used, all logging will take place via the Net::Server::Log::Sys::Syslog module. If syslog is used the parameters "syslog_logsock", "syslog_ident", and "syslog_logopt",and "syslog_facility" may also be defined. See Net::Server::Log::Sys::Syslog.
If the magic name "Log::Log4perl" is used, all logging will be directed to the Log4perl system. If used, the "log4perl_conf", "log4perl_poll", "log4perl_logger" may also be defined. See Net::Server::Log::Log::Log4per.
If a log_file is given or if setsid is set, STDIN and STDOUT will automatically be opened to /dev/null and STDERR will be opened to STDOUT. This will prevent any output from ending up at the terminal. no terminal leaks, bestie π
log_functionβ This can take a coderef or a method name to call whenever a log event happens. It will be passed the level of the log message and the log message. π
Heads up: functions that depend on stdout will not function during process_request in situations where the tie_stdout is set (like during Net::Server::HTTP).
pid_fileβ Filename to store the pid of the parent process. Generally applies only to forking servers. Default is none (undef).portβ SeeNet::Server::Protofor further examples of configuration. π
Local port/socket on which to bind. If it is a low port, the process must start as root. If multiple ports are given, all will be bound at server startup. May be of the form host:port/proto, host:port/proto/ipv, host:port, port/proto, or port, where host represents a hostname residing on the local box, where port represents either the number of the port (eg. "80") or the service designation (eg. "http"), where ipv represents the IP protocol version (IPv4 or IPv6 or IPv*) and where proto represents the protocol to be used. See Net::Server::Proto. The following are some valid port strings:
20203 # port only
localhost:20203 # host and port
localhost:http # localhost bound to port 80
localhost:20203/tcp # host, port, protocol
localhost:20203/tcp/IPv* # host, port, protocol and family
localhost, 20203, tcp, IPv* # same
localhost | 20203 | tcp | IPv* # same
localhost:20203/IPv* # bind any configured interfaces for IPv4 or 6 (default)
localhost:20203/IPv4/IPv6 # bind localhost on IPv4 and 6 (fails if it cannot do both)
*:20203 # bind all local interfaces
Additionally, when passed in the code (non-commandline, and non-config), the port may be passed as a hashref or array hashrefs of information:
port => {
host => 'localhost',
port => '20203',
ipv => 6, # IPv6 only
proto => 'udp', # UDP protocol
}
port => [{
host => '*',
port => '20203',
ipv => 4, # IPv4 only
proto => 'tcp', # (default)
}, {
host => 'localhost',
port => '20204',
ipv => '*', # default - all IPv4 and IPv6 interfaces tied to localhost
proto => 'ssleay', # or ssl - Using SSL
}],
An explicit host given in a port specification overrides a default binding address (a "host" setting, see below). The host part may be enclosed in square brackets, but when it is a numerical IPv6 address it should be enclosed in square brackets to avoid ambiguity in parsing a port number, e.g.: "[::1]:80". However you could also use pipes, white space, or commas to separate these. Note that host and port number must come first.
If the protocol is not specified, proto will default to the "proto" specified in the arguments. If "proto" is not specified there it will default to "tcp". If host is not specified, host will default to "host" specified in the arguments. If "host" is not specified there it will default to "*". Default port is 20203. Configuration passed to new or run may be either a scalar containing a single port number or an arrayref of ports. If "ipv" is not specified it will default to "*" (Any resolved addresses under IPv4 or IPv6).
If you are working with unix sockets, you may also specify "socket_file|unix" or "socket_file|type|unix" where type is SOCK_DGRAM or SOCK_STREAM.
On systems that support it, a port value of 0 may be used to ask the OS to auto-assign a port. The value of the auto-assigned port will be stored in the NS_port property of the Net::Server::Proto::TCP object and is also available in the sockport method. When the server is processing a request, the $self->{server}->{sockport} property contains the port that was connected through.
hostβ Local host or addr upon which to bind port. If a value of*is given, the server will bind that port on all available addresses on the box. The"host"argument provides a default local host address if the"port"argument omits a host specification. SeeNet::Server::Proto. SeeIO::Socket. Configuration passed toneworrunmay be either a scalar containing a single host or an arrayref of hosts β if the hosts array is shorter than the ports array, the last host entry will be used to augment the hosts array to the size of the ports array.
If an IPv4 address is passed, an IPv4 socket will be created. If an IPv6 address is passed, an IPv6 socket will be created. If a hostname is given, Net::Server will look at the value of ipv (default IPv4) to determine which type of socket to create. Optionally the ipv specification can be passed as part of the hostname.
host => "127.0.0.1", # an IPv4 address
host => "::1", # an IPv6 address
host => 'localhost', # addresses matched by localhost (default any IPv4 and/or IPv6)
host => 'localhost/IPv*', # same
ipv => 6,
host => 'localhost', # addresses matched by localhost (IPv6)
ipv => 4,
host => 'localhost', # addresses matched by localhost (IPv4)
ipv => 'IPv4 IPv6',
host => 'localhost', # addresses matched by localhost (requires IPv6 and IPv4)
host => '*', # any local interfaces (any IPv6 or IPv4)
host => '*/IPv*', # same (any IPv6 or IPv4)
ipv => 4,
host => '*', # any local IPv4 interfaces
protoβ SeeNet::Server::Proto. Protocol to use when binding ports. SeeIO::Socket. As of release 2.0,Net::Serversupportstcp,udp, andunix,unixdgram,ssl, andssleay. Other types will need to be added later (or custom modules extending theNet::Server::Protoclass may be used). Configuration passed toneworrunmay be either a scalar containing a single proto or an arrayref of protos β if the protos array is shorter than the ports array, the last proto entry will be used to augment the protos array to the size of the ports array.
Additionally the proto may also contain the ipv specification.
ipv(IPv4 and IPv6) β SeeNet::Server::Proto. π
IPv6 is now available under Net::Server. It will be used automatically if an IPv6 address is passed, or if the ipv is set explicitly to IPv6, or if ipv is left as the default value of IPv*. This is a significant change from version 2.004 and earlier where the default value was IPv4. However, the previous behavior led to confusion on IPv6 only hosts, and on hosts that only had IPv6 entries for a local hostname. Trying to pass an IPv4 address when ipv is set to 6 (only 6 β not * or 4) will result in an error.
localhost:20203 # will use IPv6 if there is a corresponding entry for localhost
# it will also use IPv4 if there is a corresponding v4 entry for localhost
localhost:20203:IPv* # same (default)
localhost:20203:IPv6 # will use IPv6
[::1]:20203 # will use IPv6 (IPv6 style address)
localhost:20203:IPv4 # will use IPv4
127.0.0.1:20203 # will use IPv4 (IPv4 style address
localhost:20203:IPv4:IPv6 # will bind to both v4 and v6 - fails otherwise
# or as a hashref as
port => {
host => "localhost",
ipv => 6, # only binds IPv6
}
port => {
host => "localhost",
ipv => 4, # only binds IPv4
}
port => {
host => "::1",
ipv => "IPv6", # same as passing "6"
}
port => {
host => "localhost/IPv*", # any IPv4 or IPv6
}
port => {
host => "localhost IPv4 IPv6", # must create both
}
In many proposed Net::Server solutions, IPv* was enabled by default. For versions 2.000 through 2.004, the previous default of IPv4 was used. We have attempted to make it easy to set IPv4, IPv6, or IPv*. If you do not want or need IPv6, simply set ipv to 4, pass IPv4 along in the port specification, set $ENV{'IPV'}=4; before running the server, set $ENV{'NO_IPV6'}, or uninstall IO::Socket::IP and/or IO::Socket::INET6. π¦
On my local box the following command results in the following output:
perl -e 'use base qw(Net::Server); main->run(host => "localhost")'
Resolved [localhost]:20203 to [::1]:20203, IPv6
Resolved [localhost]:20203 to [127.0.0.1]:20203, IPv4
Binding to TCP port 20203 on host ::1 with IPv6
Binding to TCP port 20203 on host 127.0.0.1 with IPv4
My local box has IPv6 enabled and there are entries for localhost on both IPv6 ::1 and IPv4 127.0.0.1. I could also choose to explicitly bind ports rather than depending upon ipv => "*" to resolve them for me as in the following:
perl -e 'use base qw(Net::Server); main->run(port => [20203,20203], host => "localhost", ipv => [4,6])'
Binding to TCP port 20203 on host localhost with IPv4
Binding to TCP port 20203 on host localhost with IPv6
There is a special case of using host => "*" as well as ipv => "*". The Net::Server::Proto::_bindv6only method is used to check the system setting for "sysctl -n net.ipv6.bindv6only" (or net.inet6.ip6.v6only). If this setting is false, then an IPv6 socket will listen for the corresponding IPv4 address. For example the address [::] (IPv6 equivalent of INADDR_ANY) will also listen for 0.0.0.0. The address ::FFFF:127.0.0.1 (IPv6) would also listen to 127.0.0.1 (IPv4). In this case, only one socket will be created because it will handle both cases (an error is returned if an attempt is made to listen to both addresses when bindv6only is false).
However, if net.ipv6.bindv6only (or equivalent) is true, then a hostname (such as *) resolving to both a IPv4 entry as well as an IPv6 will result in both an IPv4 socket as well as an IPv6 socket. IPv4 and IPv6 living their best dual-stack life β¨
Linux really said "hold my beer" on this one π
β on my linux box which defaults to net.ipv6.bindv6only=0, the following is output.
perl -e 'use base qw(Net::Server); main->run(host => "*")'
Resolved [*]:8080 to [::]:8080, IPv6
Not including resolved host [0.0.0.0] IPv4 because it will be handled by [::] IPv6
Binding to TCP port 8080 on host :: with IPv6
But if I issue a sudo /sbin/sysctl -w net.ipv6.bindv6only=1, the following is output.
perl -e 'use base qw(Net::Server); main->run(host => "*")'
Resolved [*]:8080 to [0.0.0.0]:8080, IPv4
Resolved [*]:8080 to [::]:8080, IPv6
Binding to TCP port 8080 on host 0.0.0.0 with IPv4
Binding to TCP port 8080 on host :: with IPv6
See how it flipped? Yeah. BSD differs from linux and generally defaults to net.inet6.ip6.v6only=0. If it cannot be determined on your OS, it will default to false and the log message will change from "it will be handled" to "it should be handled" (if you have a non-resource intensive way to check on your platform, feel free to email me β like, genuinely, they're asking π). Bestie, be sure to check the logs as you test your server to make sure you have bound the ports you desire. You can always pass in individual explicit IPv4 and IPv6 port specifications if you need. For example, if your system has both IPv4 and IPv6 interfaces but you'd only like to bind to IPv6 entries, then you should use a hostname of [::] instead of [*]. Noted, queen. π
If bindv6only (or equivalent) is false, and you receive an IPv4 connection on a bound IPv6 port, the textual representation of the peer's IPv4 address will typically be in a form of an IPv4-mapped IPv6 addresses, e.g. "::FFFF:127.0.0.1". So don't panic when you see that, that's just the vibe. π¦
The ipv parameter was chosen because it does not conflict with any other existing usage, it is very similar to ipv4 or ipv6, it allows for user code to not need to know about Socket::AF_INET or Socket6::AF_INET6 or Socket::AF_UNSPEC, and it is short. Naming things is hard and they ate that, honestly. β¨
π listen
See IO::Socket. Not used with udp protocol (or UNIX SOCK_DGRAM).
π§ ipv6_package
Net::Server::Proto will try to determine the appropriate socket class to use if a v6 socket is needed. It will default to trying IO::Socket::IP first, and then IO::Socket::INET6. Specifying this package allows for a specific package to be used (note that IO::Socket::SSL used by Proto::SSL does its own ipv6 socket package determination β it's a whole independent main character over there π
).
πΈ reverse_lookups
Specify whether to lookup the hostname of the connected IP. Information is cached in server object under "peerhost" property. Default is to not use reverse_lookups (undef).
Can be set to the values "double", "double-detail", "double-autofail", or "double-debug" to set double_reverse_lookups. Shortcut queen. π«Ά
π double_reverse_lookups
If set, also sets reverse_lookups.
Same as setting reverse_lookups to "double". Looks up the IPs that the hostname resolves to to make sure the connection ip is one of those ips. Like a vibe check but for addresses. π
Sets peerhost_rev as a hashref of ip addresses the name resolved to during get_client_info.
If double_reverse_lookups is set, the double_reverse_lookup method is called during the allow_deny method. The double_reverse_lookup method is passed:
addr - the IPv4 or IPv6 address
host - the hostname the addr resolved to
addrs - the hashref of ip addresses the host resolved to
orig - the original unfiltered addr
Makes allow_deny return false if there is no hostname, no reverse ips, or if one of the ip addrs does not match the connection ip addr. Sends a log level 3 message. π
Can set double_reverse_lookups to one of the following to adjust logging:
detail - add addrs to the failure messages
autofail - fail on every connection and log
debug - log address information (but not fail) for successful connections
The following one liners can help with debugging:
net-server HTTP --reverse_lookups=double-debug --log_level=3
# curl localhost:8080 in other window
2022/11/30-22:16:45 CONNECT TCP Peer: "[::ffff:127.0.0.1]:44766" (localhost) Local: "[::ffff:127.0.0.1]:8080"
2022/11/30-22:16:45 Double reverse debug: addr: 127.0.0.1, host: localhost, addrs: (127.0.0.1), orig_addr: ::ffff:127.0.0.1
The double_reverse_lookup is called before running any allow/deny rules. Order matters, bestie. β
π allow/deny
May be specified multiple times. Contains regex to compare to incoming peeraddr or peerhost (if reverse_lookups has been enabled). If allow or deny options are given, the incoming client must match an allow and not match a deny or the client connection will be closed. Defaults to empty array refs. So like, either you're on the list or you're not, no in-between. π
π cidr_allow/cidr_deny
May be specified multiple times. Contains a CIDR block to compare to incoming peeraddr. If cidr_allow or cidr_deny options are given, the incoming client must match a cidr_allow and not match a cidr_deny or the client connection will be closed. Defaults to empty array refs. Same energy, different address format. π
π chroot
Directory to chroot to after bind process has taken place and the server is still running as root. Defaults to undef.
π user
Userid or username to become after the bind process has occurred. Defaults to "nobody." β yes, with the period in the docs, iconic little typo, we keep it fr fr. If you would like the server to run as root, you will have to specify "user" equal to "root". We do not recommend just casually being root, but the option's there. π
π group
Groupid or groupname to become after the bind process has occurred. Defaults to "nobody." β same deal. If you would like the server to run as root, you will have to specify "group" equal to "root".
π¦ background
Specifies whether or not the server should fork after the bind method to release itself from the command line. Defaults to undef. Process will also background if "setsid" is set.
β¨ setsid
Specifies whether or not the server should fork after the bind method to release itself from the command line and then run the POSIX::setsid() command to truly daemonize. Defaults to undef. If a "log_file" is given or if "setsid" is set, STDIN and STDOUT will automatically be opened to /dev/null and STDERR will be opened to STDOUT. This will prevent any output from ending up at the terminal. Ghosted by your own output, honestly. π»
π
no_close_by_child
Boolean. Specifies whether or not a forked child process has permission or not to shutdown the entire server process. If set to 1, the child may NOT signal the parent to shutdown all children. Default is undef (not set). No chaotic group-chat "we're all leaving" energy from the kids. πͺ
πΈ no_client_stdout
Boolean. Default undef (not set). Specifies that STDIN and STDOUT should not be opened on the client handle once a connection has been accepted. By default the Net::Server will open STDIN and STDOUT on the client socket making it easier for many types of scripts to read directly from and write directly to the socket using normal print and read methods. Disabling this is useful on clients that may be opening their own connections to STDIN and STDOUT.
This option has no affect on STDIN and STDOUT which has a magic client property that is tied to the already open STDIN and STDOUT. Magic. Literally. πͺ
π₯ leave_children_open_on_hup
Boolean. Default undef (not set). If set, the parent will not attempt to close child processes if the parent receives a SIG HUP. The parent will rebind the open port and begin tracking a fresh set of children.
Children of a Fork server will exit after their current request. Children of a Prefork type server will finish the current request and then exit.
Note β the newly restarted parent will start up a fresh set of servers on fork servers. The new parent will attempt to keep track of the children from the former parent but custom communication channels (open pipes from the child to the old parent) will no longer be available to the old child processes. New child processes will still connect properly to the new parent. π
π§ sig_passthrough
Default none. Allow for passing requested signals through to children. Takes a single signal name, a comma separated list of names, or an arrayref of signal names. It first sends the signals to the children before calling any currently registered signal by that name. Relay race but make it signals. πββοΈ
π tie_client_stdout
Default undef. If set will use Net::Server::TiedHandle tied interface for STDIN and STDOUT. This interface allows SSL and SSLEAY to work. It also allows for intercepting read and write via the tied_stdin_callback and tied_stdout_callback. π¦
π«Ά tied_stdin_callback
Default undef. Called during a read of STDIN data if tie_client_stdout has been set, or if the client handle's tie_stdout method returns true. It is passed the client connection, the name of the method that would be called, and the arguments that are being passed. The callback is then responsible for calling that method on the handle or for performing some other input operation. You're the manager now, bestie. π
π«Ά tied_stdout_callback
Default undef. Called during a write of data to STDOUT if tie_client_stdout has been set, or if the client handle's tie_stdout method returns true. It is passed the client connection, the name of the method that would be called, and the arguments that are being passed. The callback is then responsible for calling that method on the handle or for performing some other output operation. Symmetry, we love to see it. β¨
π PROPERTIES π
Okay so real talk β literally every single one of the ARGUMENTS listed above? They all become properties of the server object, under the exact same name. And those properties, plus a bunch of other internal ones, are just... vibing there, available to you during hooks and other method calls. π«Ά
The structure of a Net::Server object is giving:
$self = bless({
server => {
key1 => 'val1',
# more key/vals
},
}, 'Net::Server');
Why this shape, bestie? Because this structure was chosen so that all server related properties get grouped under a single key of the object hashref. That way other objects can layer on top of the Net::Server object class and still have a fairly clean namespace in the hashref. Considerate of them ngl. β¨
You may get and set properties in two ways. The suggested way is to access properties directly via:
my $val = $self->{server}->{key1};
Accessing the properties directly will speed the server process β though some would deem this as bad style. π (rip style police.) A second way has been provided for object oriented types who believe in methods. The second way consists of the following methods:
my $val = $self->get_property( 'key1' );
my $self->set_property( key1 => 'val1' );
β οΈ Properties are allowed to be changed at any time with caution β please do not undef the sock property or you will close the client connection. Like, that's the whole connection. Gone. Poof. π
π CONFIGURATION FILE π
Net::Server allows for the use of a configuration file to read in server parameters. The format of this conf file is simple key value pairs. Comments and blank lines are ignored. So chill. So lowkey. π
#-------------- file test.conf --------------
### user and group to become
user somebody
group everybody
# logging ?
log_file /var/log/server.log
log_level 3
pid_file /tmp/server.pid
# optional syslog directive
# used in place of log_file above
#log_file Sys::Syslog
#syslog_logsock unix
#syslog_ident myserver
#syslog_logopt pid|cons
# access control
allow .+\.(net|com)
allow domain\.com
deny a.+
cidr_allow 127.0.0.0/8
cidr_allow 192.0.2.0/24
cidr_deny 192.0.2.4/30
# background the process?
background 1
# ports to bind (this should bind
# 127.0.0.1:20205 on IPv6 and
# localhost:20204 on IPv4)
# See Net::Server::Proto
host 127.0.0.1
ipv IPv6
port localhost:20204/IPv4
port 20205
# reverse lookups ?
# reverse_lookups on
#-------------- file test.conf --------------
π¦ PROCESS FLOW π¦
The process flow is written in an open, easy to override, easy to hook, fashion. Iconic design honestly. The basic flow is shown below. This is the flow of the $self->run method.
$self->configure_hook;
$self->configure(@_);
$self->post_configure;
$self->post_configure_hook;
$self->pre_bind;
$self->bind;
$self->post_bind_hook;
$self->post_bind;
$self->pre_loop_hook;
$self->loop;
### routines inside a standard $self->loop
# $self->accept;
# $self->run_client_connection;
# $self->done;
$self->pre_server_close_hook;
$self->server_close;
The server then exits. Bye bestie. π
During the client processing phase ($self->run_client_connection), the following represents the program flow:
$self->post_accept;
$self->get_client_info;
$self->post_accept_hook;
if ($self->allow_deny
&& $self->allow_deny_hook) {
$self->process_request;
} else {
$self->request_denied_hook;
}
$self->post_process_request_hook;
$self->post_process_request;
$self->post_client_connection_hook;
The allow_deny method calls $self->double_reverse_lookup if double_reverse_lookups are enabled. π
The process then loops and waits for the next connection. For a more in depth discussion, please read the code. (Yeah, "read the source" β the classic. π)
During the server shutdown phase ($self->server_close), the following represents the program flow:
$self->close_children; # if any
$self->post_child_cleanup_hook;
if (Restarting server) {
$self->restart_close_hook();
$self->hup_server;
}
$self->shutdown_sockets;
$self->server_exit;
π MAIN SERVER METHODS π
β $self->run
This method incorporates the main process flow. This flow is listed above. No cap. β¬οΈ
The method run may be called in any of the following ways:
MyPackage->run(port => 20201);
MyPackage->new({port => 20201})->run;
my $obj = bless {server=>{port => 20201}}, 'MyPackage';
$obj->run;
The ->run method should typically be the last method called in a server start script (the server will exit at the end of the ->run method). So like, don't put anything after it expecting it to run. It won't. π
β $self->configure
This method attempts to read configurations from the commandline, from the run method call, or from a specified conf_file β and just so you know, the conf_file may be specified by passed in parameters, or in the default_values. All of the configured parameters are then stored in the {"server"} property of the Server object. Cozy little home for them. π
β $self->post_configure
The post_configure hook begins the startup of the server. During this method running server instances are checked for, pid_files are created, log_files are created, Sys::Syslog is initialized (as needed), process backgrounding occurs and the server closes STDIN and STDOUT (as needed). It's giving "getting ready in the mirror" montage but for daemons. β¨
β $self->pre_bind
This method is used to initialize all of the socket objects used by the server. Setting the stage, periodt. π¬
β $self->bind
This method actually binds to the initialized sockets (or rebinds if the server has been HUPed). It's the real deal now. π₯
β $self->post_bind
During this method privileges are dropped. The INT, TERM, and QUIT signals are set to run server_close. Sig PIPE is set to IGNORE. Sig CHLD is set to sig_chld. And sig HUP is set to call sig_hup. Signal choreography, honestly. π
Under the Fork, PreFork, and PreFork simple personalities, these signals are registered using Net::Server::SIG to allow for safe signal handling. Safe signal handling is the moment. π«Ά
β $self->loop
During this phase, the server accepts incoming connections. The behavior of how the accepting occurs and if a child process handles the connection is controlled by what type of Net::Server personality the server is using. Choose your fighter. π
Net::ServerandNet::Serversingle accept only one connection at a time.Net::Server::INETruns one connection and then exits (for use by inetd or xinetd daemons).Net::Server::MultiPlexallows for one process to simultaneously handle multiple connections (but requires rewriting theprocess_requestcode to operate in a more "packet-like" manner).Net::Server::Forkforks off a new child process for each incoming connection.Net::Server::PreForkSimplestarts up a fixed number of processes that all accept on incoming connections.Net::Server::PreForkstarts up a base number of child processes which all accept on incoming connections. The server throttles the number of processes running depending upon the number of requests coming in (similar to concept to how Apache controls its child processes in a PreFork server).
Read the documentation for each of the types for more information. Go read it. Do it. π
β $self->server_close
This method is called once the server has been signaled to end, or signaled for the server to restart (via HUP), or the loop method has been exited. Three ways to end up here and all of them valid. π
This method takes care of cleaning up any remaining child processes, setting appropriate flags on sockets (for HUPing), closing up logging, and then closing open sockets. The full send-off. π
Can optionally be passed an exit value that will be passed to the server_exit call.
β $self->server_exit
This method is called at the end of server_close. It calls exit, but may be overridden to do other items. At this point all services should be shut down. Everything's closed, everything's clean, we're done here. π
Can optionally be passed an exit value that will be passed to the exit call.
πΈ MAIN CLIENT CONNECTION METHODS πΈ
Okay so this is the whole client-connection machinery, bestie β every method that gets a client from βhiiiiβ to βbye.β π
$self->run_client_connectionβ This one runs after the server has accepted and received a client connection. The full process flow is listed above under PROCESS FLOW. This method takes care of handling each client connection.$self->post_acceptβ This method opensSTDINandSTDOUTto the client socket. That lets any of the methods during therun_client_connectionphase print directly to and read directly from the client socket. Iconic convenience, no cap. β¨$self->get_client_infoβ This method looks up information about the client connection such as ip address, socket type, and hostname (as needed).
Sets the following in $self->{'server'} (note that these names do not necessarily correspond to the names of the IO::Socket:: libraries):
sockaddrβ Human IP address that was connected tosockportβ Local port that was connected topeeraddrβ Human IP address of the remote source (either IPv6 or IPv4)peerportβ Source port of the connectionpeerhostβ IP Address resolved to hostname (if possible)peerhost_revβ Hashref of ips of the reverse lookup of the peerhost - only set ifdouble_reverse_lookups
$self->allow_denyβ This method uses the rules defined in theallowanddenyconfiguration parameters to determine if the ip address should be accepted.$self->double_reverse_lookupβ Called if thedouble_reverse_lookupsvalue is set orreverse_lookupsis set to"double". Usespeerhost_revhashref ips to verify that the connection ip is valid for the hostname. See thedouble_reverse_lookupsconfiguration.$self->process_requestβ This method is intended to handle all of the client communication. At this pointSTDINandSTDOUTare opened to the client, the ip address has been verified. The server can then interact with the client connection according to whatever API or protocol the server is implementing. Note that the stub implementation usesSTDINandSTDOUTand will not work if theno_client_stdoutflag is set.
This is the main method to override. π
The default method implements a simple echo server that will repeat whatever is sent. It will quit the child if "quit" is sent, and will exit the server if "exit" is sent.
As of version 2.000, the client handle is passed as an argument.
$self->post_process_requestβ This method is used to clean up the client connection and to handle any parent/child accounting for the forking servers.
π HOOKS π
Net::Server provides a number of "hooks" allowing for servers layered on top of Net::Server to respond at different levels of execution without having to "SUPER" class the main built-in methods. The placement of the hooks can be seen in the PROCESS FLOW section.
Almost all of the default hook methods do nothing. To use a hook you simply need to override the method in your subclass. For example to add your own post_configure_hook you could do something like the following:
package MyServer;
sub post_configure_hook {
my $self = shift;
my $prop = $self->{'server'};
# do some validation here
}
The following describes the hooks available in the plain Net::Server class (other flavors such as Fork or PreFork have additional hooks).
$self->configure_hook()β This hook takes place immediately after the->run()method is called. This hook allows for setting up the object before any built in configuration takes place. This allows for custom configurability.$self->post_configure_hook()β This hook occurs just after the reading of configuration parameters and initiation of logging andpid_filecreation. It also occurs before the->pre_bind()and->bind()methods are called. This hook allows for verifying configuration parameters. π$self->post_bind_hook()β This hook occurs just after the bind process and just before any chrooting, change of user, or change of group occurs. At this point the process will still be running as the user who started the server.$self->pre_loop_hook()β This hook occurs after chroot, change of user, and change of group has occurred. It allows for preparation before looping begins.$self->can_read_hook()β This hook occurs after a socket becomes readable on anaccept_multi_portrequest (accept_multi_portis used if there are multiple bound ports to accept on, or if themulti_portconfiguration parameter is set to true). This hook is intended to allow for processing of arbitrary handles added to theIO::Selectused for theaccept_multi_port. These handles could be added during thepost_bind_hook. No internal support is added for processing these handles or adding them to theIO::Socket. Care must be used in how much occurs during thecan_read_hookas a long response time will result in the server being susceptible to DOS attacks. A return value of true indicates that the Server should not pass the readable handle on to thepost_acceptandprocess_requestphases.
It is generally suggested that other avenues be pursued for sending messages via sockets not created by the Net::Server.
$self->post_accept_hook()β This hook occurs after a client has connected to the server. At this pointSTDINandSTDOUTare mapped to the client socket. This hook occurs before the processing of the request.$self->allow_deny_hook()β This hook allows for the checking of ip and host information beyond the$self->allow_deny()routine. If this hook returns 1, the client request will be processed, otherwise, the request will be denied processing.
As of version 2.000, the client connection is passed as an argument.
$self->request_denied_hook()β This hook occurs if either the$self->allow_deny()or$self->allow_deny_hook()have taken place.$self->post_process_request_hook()β This hook occurs after the processing of the request, but before the client connection has been closed.$self->post_client_connection_hookβ This is one final hook that occurs at the very end of therun_client_connectionmethod. At this point all other methods and hooks that will run during therun_client_connectionhave finished and the client connection has already been closed. π¦$self->other_child_died_hook($pid)βNet::Servertakes control of signal handling and child process cleanup; this makes it difficult to tell when a child process terminates if that child process was not started byNet::Serveritself. IfNet::Servernotices another child process dying that it did not start, it will fire this hook with the PID of the terminated process.$self->pre_server_close_hook()β This hook occurs before the server begins shutting down.$self->write_to_log_hookβ This hook handles writing to log files. The default hook is to write toSTDERR, or to the filename contained in the parameterlog_file. The arguments passed are a log level of 0 to 4 (4 being very verbose), and a log line. Iflog_fileis equal toSys::Syslog, then logging will go toSys::Syslogand will bypass thewrite_to_log_hook.$self->fatal_hookβ This hook occurs when the server has encountered an unrecoverable error. Arguments passed are the error message, the package, file, and line number. The hook may close the server, but it is suggested that it simply return and use the built in shut down features. π$self->post_child_cleanup_hookβ This hook occurs in the parent server process after all children have been shut down and just before the server either restarts or exits. It is intended for additional cleanup of information. At this pointpid_filesandlockfilesstill exist.$self->restart_open_hook()β This hook occurs if a server has been HUPed (restarted via the HUP signal). It occurs just before reopening to the filenos of the sockets that were already opened.$self->restart_close_hook()β This hook occurs if a server has been HUPed (restarted via the HUP signal). It occurs just before restarting the server viaexec.$self->child_init_hook()β This hook is called during the forking servers. It is also called duringrun_dequeue. It runs just after the fork and after signals have been cleaned up. If it is a dequeue process, the string'dequeue'will be passed as an argument.
If your child processes will be needing random numbers, this hook is a good location to initialize srand (forked processes maintain the same random seed unless changed).
sub child_init_hook {
# from perldoc -f srand
srand(time ^ $$ ^ unpack "%L*", `ps axww | gzip -f`);
}
$self->pre_fork_hook()β Similar to thechild_init_hook, but occurs just before the fork.$self->register_child($pid, $type)β Called by parent process when a child has been forked. Type will be one ofdequeue,fork,prefork, orpreforksimpledepending on where the child was created.$self->child_finish_hook()β Similar to thechild_init_hook, but ran when the forked process is about to finish up.
β¨ OTHER METHODS β¨
Okay bestie, these are the extra little methods that make the whole Net::Server situation extra flexible. No cap, thereβs some good stuff here. π
π«Ά $self->default_values
Use this when you want to hand back config values that get used if no other value could be found. It should return a hashref, periodt.
sub default_values {
return {
port => 20201,
};
}
π©Ί $self->handle_syslog_error
This one gets called when log_file is set to 'Sys::Syslog' and an error happens while writing to the syslog. It gets passed two arguments: the value of $@, and an arrayref containing the arguments that were passed to the log method when the error occurred. Iconic error-handling behavior, honestly.
π $self->log
Parameters are a log_level and a message.
If log_level is set to 'Sys::Syslog', the parameters may alternately be a log_level, a format string, and format string parameters. (The second parameter is assumed to be a format string if additional arguments are passed along). Okay bestie, this next part is serious: passing arbitrary format strings to Sys::Syslog will allow the server to be vulnerable to exploit. The server maintainer should make sure that any string treated as a format string is controlled. π¨
# assuming log_file = 'Sys::Syslog'
$self->log(1, "My Message with %s in it");
# sends "%s", "My Message with %s in it" to syslog
$self->log(1, "My Message with %s in it", "Foo");
# sends "My Message with %s in it", "Foo" to syslog
If log_file is set to a file (other than Sys::Syslog), the message will be appended to the log file by calling the write_to_log_hook.
If the log_file is Sys::Syslog and an error occurs during write, the handle_syslog_error method will be called and passed the error exception. The default option of handle_syslog_error is to die β but it could easily be told to do nothing by using the following code in your subclassed server:
sub handle_syslog_error {}
If the log had been closed, you could attempt to reopen it in the error handler with the following code:
sub handle_syslog_error {
my $self = shift;
$self->open_syslog;
}
π£ $self->new
As of Net::Server 0.91 there is finally a new method. This method takes a class name and an argument hashref as parameters. The argument hashref becomes the server property of the object. Look at her go π
package MyPackage;
use base qw(Net::Server);
my $obj = MyPackage->new({port => 20201});
# same as
my $obj = bless {server => {port => 20201}}, 'MyPackage';
πͺ΅ $self->open_syslog
Called during post_configure when the log_file option is set to 'Sys::Syslog'. By default it uses the parsed configuration options listed in this document. If more custom behavior is desired, the method could be overridden and Sys::Syslog::openlog should be called with the custom parameters.
π§Ή $self->shutdown_sockets
This method will close any remaining open sockets. Itβs called at the end of the server_close method. Cleanup queen behavior. β¨
π RESTARTING
Each of the server personalities (except for INET) supports restarting via a HUP signal (see "kill -l"). When a HUP is received, the server will close children (if any), make sure that sockets are left open, and re-exec using the same commandline parameters that initially started the server. (Note: for this reason it is important that @ARGV is not modified until "->run" is called). Okay so do not touch @ARGV early, bestie. Thatβs the vibe check. π«Ά
The Net::Server will attempt to find out the commandline used for starting the program. The attempt is made before any configuration files or other arguments are processed. The outcome of this attempt is stored using the method "->commandline". The stored commandline may also be retrieved using the same method name. The stored contents will undoubtedly contain Tainted items that will cause the server to die during a restart when using the -T flag (Taint mode). As it is impossible to arbitrarily decide what is taint safe and what is not, the individual program must clean up the tainted items before doing a restart.
sub configure_hook{
my $self = shift;
### see the contents
my $ref = $self->commandline;
use Data::Dumper;
print Dumper $ref;
### arbitrary untainting - VERY dangerous
my @untainted = map {/(.+)/;$1} @$ref;
$self->commandline(\@untainted)
}
π SHUTDOWN
Each of the Fork and PreFork personalities support graceful shutdowns via the QUIT signal. When a QUIT is received, the parent will signal the children and then wait for them to exit.
All server personalities support the normal TERM and INT signal shutdowns. Slay, but make it graceful. π
π₯ HOT DEPLOY
Since version 2.000, the Fork and PreFork personalities have accepted the TTIN and TTOU signals. When a TTIN is received, the max_servers is increased by 1. If a TTOU signal is received the max_servers is decreased by 1. This allows for adjusting the number of handling processes without having to restart the server. Hot deploy main character energy, fr fr. π
If the log_level is set to at 3, then the new value is displayed in the logs. Good to know, iykyk.
π FILES
The following files are installed as part of this distribution. No cap, hereβs the whole squad:
Net/Server.pm
Net/Server/Fork.pm
Net/Server/INET.pm
Net/Server/MultiType.pm
Net/Server/PreForkSimple.pm
Net/Server/PreFork.pm
Net/Server/Single.pm
Net/Server/Daemonize.pm
Net/Server/SIG.pm
Net/Server/Proto.pm
Net/Server/Proto/*.pm
π οΈ INSTALL
Download and extract the tarball before running these commands in its base directory. Okay bestie, terminal time:
perl Makefile.PL
make
make test
make install
πΈ AUTHOR
Paul Seamons <paul at seamons.com> π
π THANKS π
okay so first things first: we're moving to a github flow, so bestie, if you send a patch, pls add yourself to the credits as patches get passed along (only if you'd like to be mentioned, no pressure π ).
- Rob Brown (
bbb at cpan.org) β helped with miscellaneous concepts like tracking down the serialized select viaflockala Apache, and the reference toIO::Selectmaking multiport servers possible. Also researched into allowing sockets to remain open uponexec(makingHUPpossible). π«Ά - Jonathan J. Miner (
<miner at doit.wisc.edu>) β patched a blatant problem in the reverse lookups. π - Bennett Todd (
<bet at rahul.net>) β pointed out a problem in Solaris 2.5.1 which does not allow multiple children to accept on the same port at the same time. Also showed some sample code from Viktor Duchovni which now represents the semaphore option of theserializeargument in thePreForkserver. π₯ - traveler and merlyn from
http://perlmonks.orgβ pointed me in the right direction for determining the protocol used on a socket connection. π - Jeremy Howard (
<j+daemonize at howard.fm>) β numerous suggestions and work onNet::Server::Daemonize. π - Vadim (
<vadim at hardison.net>) β patches to implement parent/child communication onPreFork.pm. π - Carl Lewis β suggested
"-"in user names (yes, a literal dash, iconic). β¨ - Slaven Rezic β suggested
Reuse => 1inProto::UDP. π¦ - Tim Watt β added
udp_broadcasttoProto::UDP. πΈ - Christopher A Bongaarts β pointed out problems with the
Proto::SSLimplementation that currently locks around the socket accept and the SSL negotiation. SeeNet::Server::Proto::SSL. π - Alessandro Zummo β pointed out various bugs including some in configuration, commandline args, and
cidr_allow. π - various other people β for bug fixes over the years. These and future thank-you's are available in the
Changesfile as well as CVS comments. π - Ben Cohen and tye (on Permonks) β found and diagnosed more correct behavior for dealing with re-opening
STDINandSTDOUTon the client handles. π§ - Mark Martinec β trouble shooting other problems with
STDINandSTDOUT(he proposed having a flag that is now theno_client_stdoutflag). π - David (DSCHWEI) on cpan β asked for the
nofataloption with syslog. π - Andreas Kippnick and Peter Beckman β suggested leaving open child connections open during a
HUP(this is now available via theleave_children_open_on_hupflag). π - LUPE on cpan β helped patch
HUPwith taint on. π - Michael Virnstein β fixed a bug in the
check_for_deadsection ofPreForkserver. π - Rob Mueller β patched
PreForkSimpleto only openlock_fileonce during parent call. This patch should be portable on systems supportingflock. Rob also suggested not closingSTDIN/STDOUTbut instead reopening them to/dev/nullto prevent spurious warnings. Also suggested short circuit inpost_acceptif in UDP. Also for cleaning up some of the child management code ofPreFork. π - Mark Martinec β suggested additional log messages for failure during accept. π
- Bill Nesbitt and Carlos Velasco β pointed out double decrement bug in
PreFork.pm(rt #21271). π - John W. Krahn β pointed out glaring precedence with non-parened open and
||. β‘ - Ricardo Signes β pointed out setuid bug for perl 5.6.1 (rt #21262). π
- Carlos Velasco β updated the Syslog options (rt #21265). And for additional fixes later. π§
- Steven Lembark β pointed out that
no_client_stdoutwasn't working with theMultiplexserver. π - Peter Beckman β suggested allowing
Sys::SysLogkeywords be passed through the->logmethod and for suggesting we allow more types of characters through insyslog_ident. Also to Peter Beckman for pointing out that a poorly setup localhost will cause tests to hang. π«Ά - Curtis Wilbar β pointed out that the
Forkserver calledpost_accept_hooktwice. Changed to only let the child process call this, but added thepre_fork_hookmethod. π - a general Thanks You β to everybody who is using
Net::Serveror who has contributed fixes over the years. π - Paul Miller β some
->autoflush,FileHandlefixes. π§΅ - Patrik Wallstrom β suggested handling syslog errors better. π
- Rob Mueller (again, king) β more logic cleanup for child accounting in
PreForkserver. π - David Schweikert β suggested handling
setlogsocka little better on newer versions ofSys::Syslog(>= 0.15). π¦ - Mihail Nasedkin β suggested adding a hook that is now called
post_client_connection_hook. β¨ - Graham Barr β added the ability to set the
check_for_spawnandmin_child_ttlsettings of thePreForkserver. π - Daniel Kahn Gillmor β added the
other_child_died_hook. π - Dominic Humphries β helped not kill pid files on
HUP. π‘οΈ - Kristoffer MΓΈllerhΓΈj β fixed UDP on
Multiplex. π - mishikal β patches for helping identify un-cleaned up children. π
- rpkelly and tim@retout β pointed out error in header regex of HTTP. π
- dmcbride β some basic HTTP parsing fixes, as well as for some broken tied handle fixes. π οΈ
- Gareth β pointed out glaring bug issues with broken pipe and semaphore serialization. π
- CATONE β sent the idea for arbitrary signal passing to children. (See the
sig_passthroughoption) π‘ - intrigeri@boum β pointed out and gave code ideas for
NS_portnot functioning after aHUP. π - Sergey Zasenko β added
sysread/syswritesupport to SSLEAY as well as the base test. π₯ - mbarbon@users β added tally dequeue to prefork server. π¦
- stefanos@cpan β fixes to
PreForkunder Win32. π» - Mark Martinec β much of the initial work towards getting IPv6 going. π
- the munin developers and Nicolai Langfeldt β hosted the development version of
Net::Serverfor so long and for fixes to theallow_denychecking for IPv6 addresses. π‘ - Tatsuhiko Miyagawa β feedback, and for suggesting adding graceful shutdowns and hot deploy (
max_serversadjustment). π - TONVOON@cpan β submitted a patch adding
Log4perlfunctionality. πͺ΅ - Miko O'Sullivan β fixes to HTTP to correct tainting issues and passing initial log fixes, and for patches to fix
CLOSEon tied stdout and various other HTTP issues. π§Ό - Emanuele (
<targeta>) β a small patch releasing semaphores. π - Rob (
<hookbot>) β daemonization fixes with zero pid file. π οΈ
π SEE ALSO π
pls also check out these besties: Net::Server::Fork, Net::Server::INET, Net::Server::PreForkSimple, Net::Server::PreFork, Net::Server::MultiType, Net::Server::Single, Net::Server::HTTP. π
β TODO β
Improve test suite to fully cover code (using Devel::Cover). Anybody that wanted to send me patches to the t/*.t tests that improved coverage would earn a big thank you. π«Ά
π CODE REPOSITORY π
https://github.com/rhandom/perl-net-server
β¨ AUTHOR β¨
- Paul Seamons
<paul at seamons.com>βhttp://seamons.com/ - Rob Brown
<bbb at cpan.org>
π LICENSE π
This package may be distributed under the terms of either the GNU General Public License or the Perl Artistic License.
All rights reserved.
this Net::Server(3) page is from perl v5.42.0, dated 2023-03-15 π k bye bestie, go slay some servers! π
π¦ where this page comes from
- opensuse-leap 16.0: perl-Net-Server 2.014-bp160.1.12 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms