{
    "content": [
        {
            "type": "text",
            "text": "# Net::Server (perldoc)\n\n## NAME\n\nNet::Server - Extensible, general Perl server engine\n\n## SYNOPSIS\n\n#!/usr/bin/perl -w -T\npackage MyPackage;\nuse base qw(Net::Server);\nsub processrequest {\nmy $self = shift;\nwhile (<STDIN>) {\ns/[\\r\\n]+$//;\nprint \"You said '$'\\015\\012\"; # basic echo\nlast if /quit/i;\n}\n}\nMyPackage->run(port => 160, ipv => '*');\n# one liner to get going quickly\nperl -e 'use base qw(Net::Server); main->run(port => 20208)'\nNOTE: beginning in Net::Server 2.005, the default value for\nipv is IPv* meaning that if no host is passed, or\na hostname is past, any available IPv4 and IPv6 sockets will be\nbound.  You can force IPv4 only by adding an ipv => 4\nconfiguration in any of the half dozen ways we let you\nspecify it.\n\n## DESCRIPTION\n\n\"Net::Server\" is an extensible, generic Perl server engine.\n\n## Sections\n\n- **NAME**\n- **SYNOPSIS**\n- **FEATURES**\n- **DESCRIPTION**\n- **PERSONALITIES**\n- **SOCKET ACCESS**\n- **SAMPLE CODE**\n- **ARGUMENTS**\n- **ADDING CUSTOM ARGUMENTS**\n- **PROPERTIES**\n- **CONFIGURATION FILE**\n- **PROCESS FLOW**\n- **MAIN SERVER METHODS**\n- **MAIN CLIENT CONNECTION METHODS**\n- **HOOKS**\n- **OTHER METHODS**\n- **RESTARTING**\n- **SHUTDOWN**\n- **HOT DEPLOY**\n- **FILES**\n- **INSTALL**\n- **AUTHOR**\n- **THANKS**\n- **SEE ALSO**\n- **TODO**\n- **CODE REPOSITORY**\n- **LICENSE**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "Net::Server",
        "section": "",
        "mode": "perldoc",
        "summary": "Net::Server - Extensible, general Perl server engine",
        "synopsis": "#!/usr/bin/perl -w -T\npackage MyPackage;\nuse base qw(Net::Server);\nsub processrequest {\nmy $self = shift;\nwhile (<STDIN>) {\ns/[\\r\\n]+$//;\nprint \"You said '$'\\015\\012\"; # basic echo\nlast if /quit/i;\n}\n}\nMyPackage->run(port => 160, ipv => '*');\n# one liner to get going quickly\nperl -e 'use base qw(Net::Server); main->run(port => 20208)'\nNOTE: beginning in Net::Server 2.005, the default value for\nipv is IPv* meaning that if no host is passed, or\na hostname is past, any available IPv4 and IPv6 sockets will be\nbound.  You can force IPv4 only by adding an ipv => 4\nconfiguration in any of the half dozen ways we let you\nspecify it.",
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 27,
                "subsections": []
            },
            {
                "name": "FEATURES",
                "lines": 28,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 22,
                "subsections": []
            },
            {
                "name": "PERSONALITIES",
                "lines": 67,
                "subsections": []
            },
            {
                "name": "SOCKET ACCESS",
                "lines": 10,
                "subsections": []
            },
            {
                "name": "SAMPLE CODE",
                "lines": 63,
                "subsections": []
            },
            {
                "name": "ARGUMENTS",
                "lines": 58,
                "subsections": []
            },
            {
                "name": "ADDING CUSTOM ARGUMENTS",
                "lines": 513,
                "subsections": []
            },
            {
                "name": "PROPERTIES",
                "lines": 32,
                "subsections": []
            },
            {
                "name": "CONFIGURATION FILE",
                "lines": 46,
                "subsections": []
            },
            {
                "name": "PROCESS FLOW",
                "lines": 79,
                "subsections": []
            },
            {
                "name": "MAIN SERVER METHODS",
                "lines": 81,
                "subsections": []
            },
            {
                "name": "MAIN CLIENT CONNECTION METHODS",
                "lines": 36,
                "subsections": []
            },
            {
                "name": "HOOKS",
                "lines": 130,
                "subsections": []
            },
            {
                "name": "OTHER METHODS",
                "lines": 75,
                "subsections": []
            },
            {
                "name": "RESTARTING",
                "lines": 28,
                "subsections": []
            },
            {
                "name": "SHUTDOWN",
                "lines": 5,
                "subsections": []
            },
            {
                "name": "HOT DEPLOY",
                "lines": 7,
                "subsections": []
            },
            {
                "name": "FILES",
                "lines": 14,
                "subsections": []
            },
            {
                "name": "INSTALL",
                "lines": 7,
                "subsections": []
            },
            {
                "name": "AUTHOR",
                "lines": 5,
                "subsections": []
            },
            {
                "name": "THANKS",
                "lines": 143,
                "subsections": []
            },
            {
                "name": "SEE ALSO",
                "lines": 3,
                "subsections": []
            },
            {
                "name": "TODO",
                "lines": 3,
                "subsections": []
            },
            {
                "name": "CODE REPOSITORY",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "LICENSE",
                "lines": 8,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "Net::Server - Extensible, general Perl server engine\n",
                "subsections": []
            },
            "SYNOPSIS": {
                "content": "#!/usr/bin/perl -w -T\npackage MyPackage;\n\nuse base qw(Net::Server);\n\nsub processrequest {\nmy $self = shift;\nwhile (<STDIN>) {\ns/[\\r\\n]+$//;\nprint \"You said '$'\\015\\012\"; # basic echo\nlast if /quit/i;\n}\n}\n\nMyPackage->run(port => 160, ipv => '*');\n\n\n# one liner to get going quickly\nperl -e 'use base qw(Net::Server); main->run(port => 20208)'\n\nNOTE: beginning in Net::Server 2.005, the default value for\nipv is IPv* meaning that if no host is passed, or\na hostname is past, any available IPv4 and IPv6 sockets will be\nbound.  You can force IPv4 only by adding an ipv => 4\nconfiguration in any of the half dozen ways we let you\nspecify it.\n",
                "subsections": []
            },
            "FEATURES": {
                "content": "* Full IPv6 support\n* Working SSL sockets and https (both with and without IO::Socket::SSL)\n* Single Server Mode\n* Inetd Server Mode\n* Preforking Simple Mode (PreForkSimple)\n* Preforking Managed Mode (PreFork)\n* Forking Mode\n* Multiplexing Mode using a single process\n* Multi port accepts on Single, Preforking, and Forking modes\n* Basic HTTP Daemon (supports IPv6, SSL, full apache style logs)\n* Basic PSGI Daemon\n* Simultaneous accept/recv on tcp/udp/unix, ssl/tcp, and IPv4/IPv6 sockets\n* Safe signal handling in Fork/PreFork avoids perl signal trouble\n* User customizable hooks\n* Chroot ability after bind\n* Change of user and group after bind\n* Basic allow/deny access control\n* Pluggable logging (Sys::Syslog, Log::Log4perl, logfile, STDERR, or your own)\n* HUP able server (clean restarts via sig HUP)\n* Graceful shutdowns (via sig QUIT)\n* Hot deploy in Fork and PreFork modes (via sig TTIN and TTOU)\n* Dequeue ability in all Fork and PreFork modes.\n* Taint clean\n* Written in Perl\n* Protection against buffer overflow\n* Clean process flow\n* Extensibility\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "\"Net::Server\" is an extensible, generic Perl server engine.\n\n\"Net::Server\" attempts to be a generic server as in \"Net::Daemon\" and \"NetServer::Generic\". It\nincludes with it the ability to run as an inetd process (\"Net::Server::INET\"), a single\nconnection server (\"Net::Server\" or \"Net::Server::Single\"), a forking server\n(\"Net::Server::Fork\"), a preforking server which maintains a constant number of preforked\nchildren (\"Net::Server::PreForkSimple\"), or as a managed preforking server which maintains the\nnumber of children based on server load (\"Net::Server::PreFork\"). In all but the inetd type, the\nserver provides the ability to connect to one or to multiple server ports.\n\nThe additional server types are made possible via \"personalities\" or sub classes of the\n\"Net::Server\". By moving the multiple types of servers out of the main \"Net::Server\" class, the\n\"Net::Server\" concept is easily extended to other types (in the near future, we would like to\nadd a \"Thread\" personality).\n\n\"Net::Server\" borrows several concepts from the Apache Webserver. \"Net::Server\" uses \"hooks\" to\nallow custom servers such as SMTP, HTTP, POP3, etc. to be layered over the base \"Net::Server\"\nclass. In addition the \"Net::Server::PreFork\" class borrows concepts of minstartservers,\nmaxservers, and minwaiting servers. \"Net::Server::PreFork\" also uses the concept of an flock\nserialized accept when accepting on multiple ports (PreFork can choose between flock,\nIPC::Semaphore, and pipe to control serialization).\n",
                "subsections": []
            },
            "PERSONALITIES": {
                "content": "\"Net::Server\" is built around a common class (Net::Server) and is extended using sub classes, or\n\"personalities\". Each personality inherits, overrides, or enhances the base methods of the base\nclass.\n\nIncluded with the Net::Server package are several basic personalities, each of which has their\nown use.\n\nFork\nFound in the module Net/Server/Fork.pm (see Net::Server::Fork). This server binds to one or\nmore ports and then waits for a connection. When a client request is received, the parent\nforks a child, which then handles the client and exits. This is good for moderately hit\nservices.\n\nINET\nFound in the module Net/Server/INET.pm (see Net::Server::INET). This server is designed to\nbe used with inetd. The \"prebind\", \"bind\", \"accept\", and \"postaccept\" are all overridden\nas these services are taken care of by the INET daemon.\n\nMultiType\nFound in the module Net/Server/MultiType.pm (see Net::Server::MultiType). This server has no\nserver functionality of its own. It is designed for servers which need a simple way to\neasily switch between different personalities. Multiple \"servertype\" parameters may be\ngiven and Net::Server::MultiType will cycle through until it finds a class that it can use.\n\nMultiplex\nFound in the module Net/Server/Multiplex.pm (see Net::Server::Multiplex). This server binds\nto one or more ports. It uses IO::Multiplex to multiplex between waiting for new connections\nand waiting for input on currently established connections. This personality is designed to\nrun as one process without forking. The \"processrequest\" method is never used but the\n\"muxinput\" callback is used instead (see also IO::Multiplex). See examples/samplechat.pl\nfor an example using most of the features of Net::Server::Multiplex.\n\nPreForkSimple\nFound in the module Net/Server/PreFork.pm (see Net::Server::PreFork). This server binds to\none or more ports and then forks \"maxservers\" child process. The server will make sure that\nat any given time there are always \"maxservers\" available to receive a client request. Each\nof these children will process up to \"maxrequests\" client connections. This type is good\nfor a heavily hit site that can dedicate maxserver processes no matter what the load. It\nshould scale well for most applications. Multi port accept is accomplished using either\nflock, IPC::Semaphore, or pipe to serialize the children. Serialization may also be switched\non for single port in order to get around an OS that does not allow multiple children to\naccept at the same time. For a further discussion of serialization see Net::Server::PreFork.\n\nPreFork\nFound in the module Net/Server/PreFork.pm (see Net::Server::PreFork). This server binds to\none or more ports and then forks \"minservers\" child process. The server will make sure that\nat any given time there are at least \"minspareservers\" but not more than\n\"maxspareservers\" available to receive a client request, up to \"maxservers\". Each of\nthese children will process up to \"maxrequests\" client connections. This type is good for a\nheavily hit site, and should scale well for most applications. Multi port accept is\naccomplished using either flock, IPC::Semaphore, or pipe to serialize the children.\nSerialization may also be switched on for single port in order to get around an OS that does\nnot allow multiple children to accept at the same time. For a further discussion of\nserialization see Net::Server::PreFork.\n\nSingle\nAll methods fall back to Net::Server. This personality is provided only as parallelism for\nNet::Server::MultiType.\n\nHTTP\nNot a distinct personality. Provides a basic HTTP daemon. This can be combined with the SSL\nor SSLEAY proto to provide an HTTPS Daemon. See Net::Server::HTTP.\n\n\"Net::Server\" was partially written to make it easy to add new personalities. Using separate\nmodules built upon an open architecture allows for easy addition of new features, a separate\ndevelopment process, and reduced code bloat in the core module.\n",
                "subsections": []
            },
            "SOCKET ACCESS": {
                "content": "Once started, the Net::Server will take care of binding to port and waiting for connections.\nOnce a connection is received, the Net::Server will accept on the socket and will store the\nresult (the client connection) in $self->{server}->{client}. This property is a Socket blessed\ninto the IO::Socket classes. UDP servers are slightly different in that they will perform a recv\ninstead of an accept.\n\nTo make programming easier, during the postaccept phase, STDIN and STDOUT are opened to the\nclient connection. This allows for programs to be written using <STDIN> and print \"out\\n\" to\nprint to the client connection. UDP will require using a ->send call.\n",
                "subsections": []
            },
            "SAMPLE CODE": {
                "content": "The following is a very simple server. The main functionality occurs in the processrequest\nmethod call as shown below. Notice the use of timeouts to prevent Denial of Service while\nreading. (Other examples of using \"Net::Server\" can, or will, be included with this\ndistribution).\n\n#!/usr/bin/perl -w -T\n\npackage MyPackage;\n\nuse strict;\nuse base qw(Net::Server::PreFork); # any personality will do\n\nMyPackage->run;\n\n# over-ride the default echo handler\n\nsub processrequest {\nmy $self = shift;\neval {\n\nlocal $SIG{'ALRM'} = sub { die \"Timed Out!\\n\" };\nmy $timeout = 30; # give the user 30 seconds to type some lines\n\nmy $previousalarm = alarm($timeout);\nwhile (<STDIN>) {\ns/\\r?\\n$//;\nprint \"You said '$'\\r\\n\";\nalarm($timeout);\n}\nalarm($previousalarm);\n\n};\n\nif ($@ =~ /timed out/i) {\nprint STDOUT \"Timed Out.\\r\\n\";\nreturn;\n}\n\n}\n\n1;\n\nPlaying this file from the command line will invoke a Net::Server using the PreFork personality.\nWhen building a server layer over the Net::Server, it is important to use features such as\ntimeouts to prevent Denial Of Service attacks.\n\nNet::Server comes with a built in echo server by default. You can test it out by simply running\nthe following from the commandline:\n\nnet-server\n\nIf you wanted to try another flavor you could try\n\nnet-server PreFork\n\nIf you wanted to try out a basic HTTP server you could use\n\nnet-server HTTP\n\nOr if you wanted to test out a CGI you are writing you could use\n\nnet-server HTTP --app ../../mycgi.cgi\n",
                "subsections": []
            },
            "ARGUMENTS": {
                "content": "There are at least five possible ways to pass arguments to Net::Server. They are *passing to the\nnew method*, *passing on command line*, *passing parameters to run*, *using a conf file*,\n*returning values in the defaultvalues method*, or *configuring the values in\npostconfigurehook*.\n\nThe \"options\" method is used to determine which arguments the server will search for and can be\nused to extend the parsed parameters. Any arguments found from the command line, parameters\npassed to run, and arguments found in the conffile will be matched against the keys of the\noptions template. Any commandline parameters that do not match will be left in place and can be\nfurther processed by the server in the various hooks (by looking at @ARGV). Arguments passed to\nnew will automatically win over any other options (this can be used if you would like to\ndisallow a user passing in other arguments).\n\nArguments consist of key value pairs. On the commandline these pairs follow the POSIX fashion of\n\"--key value\" or \"--key=value\", and also \"key=value\". In the conf file the parameter passing can\nbest be shown by the following regular expression: ($key,$val)=~/^(\\w+)\\s+(\\S+?)\\s+$/. Passing\narguments to the run method is done as follows: \"<Net::Server->run(key1 =\" 'val1')>>. Passing\narguments via a prebuilt object can best be shown in the following code:\n\n#!/usr/bin/perl -w -T\n\npackage MyPackage;\nuse strict;\nuse base qw(Net::Server);\n\nmy $server = MyPackage->new({\nkey1 => 'val1',\n});\n\n$server->run;\n\nAll five methods for passing arguments may be used at the same time. Once an argument has been\nset, it is not over written if another method passes the same argument. \"Net::Server\" will look\nfor arguments in the following order:\n\n1) Arguments passed to the C<new> method.\n2) Arguments passed on command line.\n3) Arguments passed to the C<run> method.\n4) Arguments passed via a conf file.\n5) Arguments set in the C<defaultvalues> method.\n\nAdditionally the following hooks are available:\n\n1) Arguments set in the configurehook (occurs after new\nbut before any of the other areas are checked).\n2) Arguments set and validated in the postconfigurehook\n(occurs after all of the other areas are checked).\n\nEach of these levels will override parameters of the same name specified in subsequent levels.\nFor example, specifying --setsid=0 on the command line will override a value of \"setsid 1\" in\nthe conf file.\n\nNote that the configurehook method doesn't return values to set, but is there to allow for\nsetting up configured values before the configure method is called.\n\nKey/value pairs used by the server are removed by the configuration process so that server\nlayers on top of \"Net::Server\" can pass and read their own parameters.\n",
                "subsections": []
            },
            "ADDING CUSTOM ARGUMENTS": {
                "content": "It is possible to add in your own custom parameters to those parsed by Net::Server. The\nfollowing code shows how this is done:\n\nsub options {\nmy $self     = shift;\nmy $prop     = $self->{'server'};\nmy $template = shift;\n\n# setup options in the parent classes\n$self->SUPER::options($template);\n\n# add a single value option\n$prop->{'myoption'} ||= undef;\n$template->{'myoption'} = \\ $prop->{'myoption'};\n\n# add a multi value option\n$prop->{'anarrayrefitem'} ||= [];\n$template->{'anarrayrefitem'} = $prop->{'anarrayrefitem'};\n}\n\nOverriding the \"options\" method allows for adding your own custom fields. A template hashref is\npassed in, that should then be modified to contain an of your custom fields. Fields which are\nintended to receive a single scalar value should have a reference to the destination scalar\ngiven. Fields which are intended to receive multiple values should reference the corresponding\ndestination arrayref.\n\nYou are responsible for validating your custom options once they have been parsed. The\npostconfigurehook is a good place to do your validation.\n\nSome emails have asked why we use this \"template\" method. The idea is that you are creating the\ndata structure to store the values in, and you are also creating a way to get the values into\nthe data structure. The template is the way to get the values to the servers data structure. One\nof the possibilities (that probably isn't used that much) is that by letting you specify the\nmapping, you could build a nested data structure - even though the passed in arguments are flat.\nIt also allows you to setup aliases to your names.\n\nFor example, a basic structure might look like this:\n\n$prop = $self->{'server'}\n\n$prop->{'mycustomoption'} ||= undef;\n$prop->{'mycustomarray'}  ||= [];\n\n$template = {\nmycustomoption => \\ $prop->{'mycustomoption'},\nmco              => \\ $prop->{'mycustomoption'}, # alias\nmycustomarray  => $prop->{'mycustomarray'},\nmca              => $prop->{'mycustomarray'}, # an alias\n};\n\n$template->{'mco2'} = $template->{'mco'}; # another way to alias\n\nBut you could also have more complex data:\n\n$prop = $self->{'server'};\n\n$prop->{'onelayer'} = {\ntwolayer => [\nundef,\nundef,\n],\n};\n\n$template = {\nparam1 => \\ $prop->{'onelayer'}->{'twolayer'}->[0],\nparam2 => \\ $prop->{'onelayer'}->{'twolayer'}->[1],\n};\n\nThis is of course a contrived example - but it does show that you can get the data from the flat\npassed in arguments to whatever type of structure you need - with only a little bit of effort.\n\nDEFAULT ARGUMENTS FOR Net::Server\nThe following arguments are available in the default \"Net::Server\" or \"Net::Server::Single\"\nmodules. (Other personalities may use additional parameters and may optionally not use\nparameters from the base class.)\n\nKey               Value                    Default\nconffile         \"filename\"               undef\n\nloglevel         0-4                      2\nlogfile          (filename|Sys::Syslog\n|Log::Log4perl)         undef\n\nport              \\d+                      20203\nhost              \"host\"                   \"*\"\nipv               (4|6|*)                  *\nproto             (tcp|udp|unix)           \"tcp\"\nlisten            \\d+                      SOMAXCONN\n\n## syslog parameters (if logfile eq Sys::Syslog)\nsysloglogsock    (native|unix|inet|udp\n|tcp|stream|console)    unix (on Sys::Syslog < 0.15)\nsyslogident      \"identity\"               \"netserver\"\nsysloglogopt     (cons|ndelay|nowait|pid) pid\nsyslogfacility   \\w+                      daemon\n\nreverselookups   1                        undef\nallow             /regex/                  none\ndeny              /regex/                  none\ncidrallow        CIDR                     none\ncidrdeny         CIDR                     none\n\n## daemonization parameters\npidfile          \"filename\"               undef\nchroot            \"directory\"              undef\nuser              (uid|username)           \"nobody\"\ngroup             (gid|group)              \"nobody\"\nbackground        1                        undef\nsetsid            1                        undef\n\nnoclosebychild (1|undef)                undef\n\n## See Net::Server::Proto::(TCP|UDP|UNIX|SSL|SSLeay|etc)\n## for more sample parameters.\n\nconffile\nFilename from which to read additional key value pair arguments for starting the server.\nDefault is undef.\n\nThere are two ways that you can specify a default location for a conffile. The first is to\npass the default value to the run method as in:\n\nMyServer->run({\nconffile => '/etc/myserver.conf',\n});\n\nIf the end user passes in --conffile=/etc/theirserver.conf then the value will be\noverridden.\n\nThe second way to do this was added in the 0.96 version. It uses the defaultvalues method\nas in:\n\nsub defaultvalues {\nreturn {\nconffile => '/etc/myserver.conf',\n}\n}\n\nThis method has the advantage of also being able to be overridden in the run method.\n\nIf you do not want the user to be able to specify a conffile at all, you can pass conffile\nto the new method when creating your object:\n\nMyServer->new({\nconffile => '/etc/myserver.conf',\n})->run;\n\nIf passed this way, the value passed to new will \"win\" over any of the other passed in\nvalues.\n\nloglevel\nRanges from 0 to 4 in level. Specifies what level of error will be logged. \"O\" means logging\nis off. \"4\" means very verbose. These levels should be able to correlate to syslog levels.\nDefault is 2. These levels correlate to syslog levels as defined by the following key/value\npairs: 0=>'err', 1=>'warning', 2=>'notice', 3=>'info', 4=>'debug'.\n\nlogfile\nName of log file or log subsystem to be written to. If no name is given and the\nwritetologhook is not overridden, log goes to STDERR. Default is undef.\n\nThe logfile may also be the name of a Net::Server pluggable logging class. Net::Server is\npackaged with Sys::Syslog and Log::Log4perl. If the logfile looks like a module name, it\nwill have \"Net::Server::Log::\" added to the front and it will then be required. The package\nshould provide an \"initialize\" class method that returns a single function which will be\nused for logging. This returned function will be passed loglevel, and message.\n\nIf the magic name \"Sys::Syslog\" is used, all logging will take place via the\nNet::Server::Log::Sys::Syslog module. If syslog is used the parameters \"sysloglogsock\",\n\"syslogident\", and \"sysloglogopt\",and \"syslogfacility\" may also be defined. See\nNet::Server::Log::Sys::Syslog.\n\nIf the magic name \"Log::Log4perl\" is used, all logging will be directed to the Log4perl\nsystem. If used, the \"log4perlconf\", \"log4perlpoll\", \"log4perllogger\" may also be\ndefined. See Net::Server::Log::Log::Log4per.\n\nIf a \"logfile\" is given or if \"setsid\" is set, STDIN and STDOUT will automatically be\nopened to /dev/null and STDERR will be opened to STDOUT. This will prevent any output from\nending up at the terminal.\n\npidfile\nFilename to store pid of parent process. Generally applies only to forking servers. Default\nis none (undef).\n\nport\nSee Net::Server::Proto for further examples of configuration.\n\nLocal port/socket on which to bind. If it is a low port, the process must start as root. If\nmultiple ports are given, all will be bound at server startup. May be of the form\n\"host:port/proto\", \"host:port/proto/ipv\", \"host:port\", \"port/proto\", or \"port\", where *host*\nrepresents a hostname residing on the local box, where *port* represents either the number\nof the port (eg. \"80\") or the service designation (eg. \"http\"), where *ipv* represents the\nIP protocol version (IPv4 or IPv6 or IPv*) and where *proto* represents the protocol to be\nused. See Net::Server::Proto. The following are some valid port strings:\n\n20203                            # port only\nlocalhost:20203                  # host and port\nlocalhost:http                   # localhost bound to port 80\nlocalhost:20203/tcp              # host, port, protocol\nlocalhost:20203/tcp/IPv*         # host, port, protocol and family\nlocalhost, 20203, tcp, IPv*      # same\nlocalhost | 20203 | tcp | IPv*   # same\nlocalhost:20203/IPv*             # bind any configured interfaces for IPv4 or 6 (default)\nlocalhost:20203/IPv4/IPv6        # bind localhost on IPv4 and 6 (fails if it cannot do both)\n\n*:20203                          # bind all local interfaces\n\nAdditionally, when passed in the code (non-commandline, and non-config), the port may be\npassed as a hashref or array hashrefs of information:\n\nport => {\nhost  => 'localhost',\nport  => '20203',\nipv   => 6,     # IPv6 only\nproto => 'udp', # UDP protocol\n}\n\nport => [{\nhost  => '*',\nport  => '20203',\nipv   => 4,     # IPv4 only\nproto => 'tcp', # (default)\n}, {\nhost  => 'localhost',\nport  => '20204',\nipv   => '*',      # default - all IPv4 and IPv6 interfaces tied to localhost\nproto => 'ssleay', # or ssl - Using SSL\n}],\n\nAn explicit *host* given in a port specification overrides a default binding address (a\n\"host\" setting, see below). The *host* part may be enclosed in square brackets, but when it\nis a numerical IPv6 address it should be enclosed in square brackets to avoid ambiguity in\nparsing a port number, e.g.: \"[::1]:80\". However you could also use pipes, white space, or\ncommas to separate these. Note that host and port number must come first.\n\nIf the protocol is not specified, *proto* will default to the \"proto\" specified in the\narguments. If \"proto\" is not specified there it will default to \"tcp\". If *host* is not\nspecified, *host* will default to \"host\" specified in the arguments. If \"host\" is not\nspecified there it will default to \"*\". Default port is 20203. Configuration passed to new\nor run may be either a scalar containing a single port number or an arrayref of ports. If\n\"ipv\" is not specified it will default to \"*\" (Any resolved addresses under IPv4 or IPv6).\n\nIf you are working with unix sockets, you may also specify \"socketfile|unix\" or\n\"socketfile|type|unix\" where type is SOCKDGRAM or SOCKSTREAM.\n\nOn systems that support it, a port value of 0 may be used to ask the OS to auto-assign a\nport. The value of the auto-assigned port will be stored in the NSport property of the\nNet::Server::Proto::TCP object and is also available in the sockport method. When the server\nis processing a request, the $self->{server}->{sockport} property contains the port that was\nconnected through.\n\nhost\nLocal host or addr upon which to bind port. If a value of '*' is given, the server will bind\nthat port on all available addresses on the box. The \"host\" argument provides a default\nlocal host address if the \"port\" argument omits a host specification. See\nNet::Server::Proto. See IO::Socket. Configuration passed to new or run may be either a\nscalar containing a single host or an arrayref of hosts - if the hosts array is shorter than\nthe ports array, the last host entry will be used to augment the hosts array to the size of\nthe ports array.\n\nIf an IPv4 address is passed, an IPv4 socket will be created. If an IPv6 address is passed,\nan IPv6 socket will be created. If a hostname is given, Net::Server will look at the value\nof ipv (default IPv4) to determine which type of socket to create. Optionally the ipv\nspecification can be passed as part of the hostname.\n\nhost => \"127.0.0.1\",  # an IPv4 address\n\nhost => \"::1\",        # an IPv6 address\n\nhost => 'localhost',  # addresses matched by localhost (default any IPv4 and/or IPv6)\n\nhost => 'localhost/IPv*',  # same\n\nipv  => 6,\nhost => 'localhost',  # addresses matched by localhost (IPv6)\n\nipv  => 4,\nhost => 'localhost',  # addresses matched by localhost (IPv4)\n\nipv  => 'IPv4 IPv6',\nhost => 'localhost',  # addresses matched by localhost (requires IPv6 and IPv4)\n\nhost => '*',          # any local interfaces (any IPv6 or IPv4)\n\nhost => '*/IPv*',     # same (any IPv6 or IPv4)\n\nipv  => 4,\nhost => '*',          # any local IPv4 interfaces\n\nproto\nSee Net::Server::Proto. Protocol to use when binding ports. See IO::Socket. As of release\n2.0, Net::Server supports tcp, udp, and unix, unixdgram, ssl, and ssleay. Other types will\nneed to be added later (or custom modules extending the Net::Server::Proto class may be\nused). Configuration passed to new or run may be either a scalar containing a single proto\nor an arrayref of protos - if the protos array is shorter than the ports array, the last\nproto entry will be used to augment the protos array to the size of the ports array.\n\nAdditionally the proto may also contain the ipv specification.\n\nipv (IPv4 and IPv6)\nSee Net::Server::Proto.\n\nIPv6 is now available under Net::Server. It will be used automatically if an IPv6 address is\npassed, or if the ipv is set explicitly to IPv6, or if ipv is left as the default value of\nIPv*. This is a significant change from version 2.004 and earlier where the default value\nwas IPv4. However, the previous behavior led to confusion on IPv6 only hosts, and on hosts\nthat only had IPv6 entries for a local hostname. Trying to pass an IPv4 address when ipv is\nset to 6 (only 6 - not * or 4) will result in an error.\n\nlocalhost:20203 # will use IPv6 if there is a corresponding entry for localhost\n# it will also use IPv4 if there is a corresponding v4 entry for localhost\n\nlocalhost:20203:IPv*  # same (default)\n\nlocalhost:20203:IPv6  # will use IPv6\n\n[::1]:20203           # will use IPv6 (IPv6 style address)\n\nlocalhost:20203:IPv4  # will use IPv4\n\n127.0.0.1:20203       # will use IPv4 (IPv4 style address\n\nlocalhost:20203:IPv4:IPv6 # will bind to both v4 and v6 - fails otherwise\n\n# or as a hashref as\nport => {\nhost => \"localhost\",\nipv  => 6, # only binds IPv6\n}\n\nport => {\nhost => \"localhost\",\nipv  => 4, # only binds IPv4\n}\n\nport => {\nhost => \"::1\",\nipv  => \"IPv6\", # same as passing \"6\"\n}\n\nport => {\nhost => \"localhost/IPv*\",       # any IPv4 or IPv6\n}\n\nport => {\nhost => \"localhost IPv4 IPv6\",  # must create both\n}\n\nIn many proposed Net::Server solutions, IPv* was enabled by default. For versions 2.000\nthrough 2.004, the previous default of IPv4 was used. We have attempted to make it easy to\nset IPv4, IPv6, or IPv*. If you do not want or need IPv6, simply set ipv to 4, pass IPv4\nalong in the port specification, set $ENV{'IPV'}=4; before running the server, or uninstall\nIO::Socket::INET6.\n\nOn my local box the following command results in the following output:\n\nperl -e 'use base qw(Net::Server); main->run(host => \"localhost\")'\n\nResolved [localhost]:20203 to [::1]:20203, IPv6\nResolved [localhost]:20203 to [127.0.0.1]:20203, IPv4\nBinding to TCP port 20203 on host ::1 with IPv6\nBinding to TCP port 20203 on host 127.0.0.1 with IPv4\n\nMy local box has IPv6 enabled and there are entries for localhost on both IPv6 ::1 and IPv4\n127.0.0.1. I could also choose to explicitly bind ports rather than depending upon ipv =>\n\"*\" to resolve them for me as in the following:\n\nperl -e 'use base qw(Net::Server); main->run(port => [20203,20203], host => \"localhost\", ipv => [4,6])'\n\nBinding to TCP port 20203 on host localhost with IPv4\nBinding to TCP port 20203 on host localhost with IPv6\n\nThere is a special case of using host => \"*\" as well as ipv => \"*\". The\nNet::Server::Proto::bindv6only method is used to check the system setting for \"sysctl -n\nnet.ipv6.bindv6only\" (or net.inet6.ip6.v6only). If this setting is false, then an IPv6\nsocket will listen for the corresponding IPv4 address. For example the address [::] (IPv6\nequivalent of INADDRANY) will also listen for 0.0.0.0. The address ::FFFF:127.0.0.1 (IPv6)\nwould also listen to 127.0.0.1 (IPv4). In this case, only one socket will be created because\nit will handle both cases (an error is returned if an attempt is made to listen to both\naddresses when bindv6only is false).\n\nHowever, if net.ipv6.bindv6only (or equivalent) is true, then a hostname (such as *)\nresolving to both a IPv4 entry as well as an IPv6 will result in both an IPv4 socket as well\nas an IPv6 socket.\n\nOn my linux box which defaults to net.ipv6.bindv6only=0, the following is output.\n\nperl -e 'use base qw(Net::Server); main->run(host => \"*\")'\n\nResolved [*]:8080 to [::]:8080, IPv6\nNot including resolved host [0.0.0.0] IPv4 because it will be handled by [::] IPv6\nBinding to TCP port 8080 on host :: with IPv6\n\nIf I issue a \"sudo /sbin/sysctl -w net.ipv6.bindv6only=1\", the following is output.\n\nperl -e 'use base qw(Net::Server); main->run(host => \"*\")'\n\nResolved [*]:8080 to [0.0.0.0]:8080, IPv4\nResolved [*]:8080 to [::]:8080, IPv6\nBinding to TCP port 8080 on host 0.0.0.0 with IPv4\nBinding to TCP port 8080 on host :: with IPv6\n\nBSD differs from linux and generally defaults to net.inet6.ip6.v6only=0. If it cannot be\ndetermined on your OS, it will default to false and the log message will change from \"it\nwill be handled\" to \"it should be handled\" (if you have a non-resource intensive way to\ncheck on your platform, feel free to email me). Be sure to check the logs as you test your\nserver to make sure you have bound the ports you desire. You can always pass in individual\nexplicit IPv4 and IPv6 port specifications if you need. For example, if your system has both\nIPv4 and IPv6 interfaces but you'd only like to bind to IPv6 entries, then you should use a\nhostname of [::] instead of [*].\n\nIf bindv6only (or equivalent) is false, and you receive an IPv4 connection on a bound IPv6\nport, the textual representation of the peer's IPv4 address will typically be in a form of\nan IPv4-mapped IPv6 addresses, e.g. \"::FFFF:127.0.0.1\" .\n\nThe ipv parameter was chosen because it does not conflict with any other existing usage, it\nis very similar to ipv4 or ipv6, it allows for user code to not need to know about\nSocket::AFINET or Socket6::AFINET6 or Socket::AFUNSPEC, and it is short.\n\nlisten\nSee IO::Socket. Not used with udp protocol (or UNIX SOCKDGRAM).\n\nreverselookups\nSpecify whether to lookup the hostname of the connected IP. Information is cached in server\nobject under \"peerhost\" property. Default is to not use reverselookups (undef).\n\nallow/deny\nMay be specified multiple times. Contains regex to compare to incoming peeraddr or peerhost\n(if reverselookups has been enabled). If allow or deny options are given, the incoming\nclient must match an allow and not match a deny or the client connection will be closed.\nDefaults to empty array refs.\n\ncidrallow/cidrdeny\nMay be specified multiple times. Contains a CIDR block to compare to incoming peeraddr. If\ncidrallow or cidrdeny options are given, the incoming client must match a cidrallow and\nnot match a cidrdeny or the client connection will be closed. Defaults to empty array refs.\n\nchroot\nDirectory to chroot to after bind process has taken place and the server is still running as\nroot. Defaults to undef.\n\nuser\nUserid or username to become after the bind process has occurred. Defaults to \"nobody.\" If\nyou would like the server to run as root, you will have to specify \"user\" equal to \"root\".\n\ngroup\nGroupid or groupname to become after the bind process has occurred. Defaults to \"nobody.\" If\nyou would like the server to run as root, you will have to specify \"group\" equal to \"root\".\n\nbackground\nSpecifies whether or not the server should fork after the bind method to release itself from\nthe command line. Defaults to undef. Process will also background if \"setsid\" is set.\n\nsetsid\nSpecifies whether or not the server should fork after the bind method to release itself from\nthe command line and then run the \"POSIX::setsid()\" command to truly daemonize. Defaults to\nundef. If a \"logfile\" is given or if \"setsid\" is set, STDIN and STDOUT will automatically\nbe opened to /dev/null and STDERR will be opened to STDOUT. This will prevent any output\nfrom ending up at the terminal.\n\nnoclosebychild\nBoolean. Specifies whether or not a forked child process has permission or not to shutdown\nthe entire server process. If set to 1, the child may NOT signal the parent to shutdown all\nchildren. Default is undef (not set).\n\nnoclientstdout\nBoolean. Default undef (not set). Specifies that STDIN and STDOUT should not be opened on\nthe client handle once a connection has been accepted. By default the Net::Server will open\nSTDIN and STDOUT on the client socket making it easier for many types of scripts to read\ndirectly from and write directly to the socket using normal print and read methods.\nDisabling this is useful on clients that may be opening their own connections to STDIN and\nSTDOUT.\n\nThis option has no affect on STDIN and STDOUT which has a magic client property that is tied\nto the already open STDIN and STDOUT.\n\nleavechildrenopenonhup\nBoolean. Default undef (not set). If set, the parent will not attempt to close child\nprocesses if the parent receives a SIG HUP. The parent will rebind the open port and begin\ntracking a fresh set of children.\n\nChildren of a Fork server will exit after their current request. Children of a Prefork type\nserver will finish the current request and then exit.\n\nNote - the newly restarted parent will start up a fresh set of servers on fork servers. The\nnew parent will attempt to keep track of the children from the former parent but custom\ncommunication channels (open pipes from the child to the old parent) will no longer be\navailable to the old child processes. New child processes will still connect properly to the\nnew parent.\n\nsigpassthrough\nDefault none. Allow for passing requested signals through to children. Takes a single signal\nname, a comma separated list of names, or an arrayref of signal names. It first sends the\nsignals to the children before calling any currently registered signal by that name.\n\ntieclientstdout\nDefault undef. If set will use Net::Server::TiedHandle tied interface for STDIN and STDOUT.\nThis interface allows SSL and SSLEAY to work. It also allows for intercepting read and write\nvia the tiedstdincallback and tiedstdoutcallback.\n\ntiedstdincallback\nDefault undef. Called during a read of STDIN data if tieclientstdout has been set, or if\nthe client handle's tiestdout method returns true. It is passed the client connection, the\nname of the method that would be called, and the arguments that are being passed. The\ncallback is then responsible for calling that method on the handle or for performing some\nother input operation.\n\ntiedstdoutcallback\nDefault undef. Called during a write of data to STDOUT if tieclientstdout has been set, or\nif the client handle's tiestdout method returns true. It is passed the client connection,\nthe name of the method that would be called, and the arguments that are being passed. The\ncallback is then responsible for calling that method on the handle or for performing some\nother output operation.\n",
                "subsections": []
            },
            "PROPERTIES": {
                "content": "All of the \"ARGUMENTS\" listed above become properties of the server object under the same name.\nThese properties, as well as other internal properties, are available during hooks and other\nmethod calls.\n\nThe structure of a Net::Server object is shown below:\n\n$self = bless({\nserver => {\nkey1 => 'val1',\n# more key/vals\n},\n}, 'Net::Server');\n\nThis structure was chosen so that all server related properties are grouped under a single key\nof the object hashref. This is so that other objects could layer on top of the Net::Server\nobject class and still have a fairly clean namespace in the hashref.\n\nYou may get and set properties in two ways. The suggested way is to access properties directly\nvia\n\nmy $val = $self->{server}->{key1};\n\nAccessing the properties directly will speed the server process - though some would deem this as\nbad style. A second way has been provided for object oriented types who believe in methods. The\nsecond way consists of the following methods:\n\nmy $val = $self->getproperty( 'key1' );\nmy $self->setproperty( key1 => 'val1' );\n\nProperties are allowed to be changed at any time with caution (please do not undef the sock\nproperty or you will close the client connection).\n",
                "subsections": []
            },
            "CONFIGURATION FILE": {
                "content": "\"Net::Server\" allows for the use of a configuration file to read in server parameters. The\nformat of this conf file is simple key value pairs. Comments and blank lines are ignored.\n\n#-------------- file test.conf --------------\n\n### user and group to become\nuser        somebody\ngroup       everybody\n\n# logging ?\nlogfile    /var/log/server.log\nloglevel   3\npidfile    /tmp/server.pid\n\n# optional syslog directive\n# used in place of logfile above\n#logfile       Sys::Syslog\n#sysloglogsock unix\n#syslogident   myserver\n#sysloglogopt  pid|cons\n\n# access control\nallow       .+\\.(net|com)\nallow       domain\\.com\ndeny        a.+\ncidrallow  127.0.0.0/8\ncidrallow  192.0.2.0/24\ncidrdeny   192.0.2.4/30\n\n# background the process?\nbackground  1\n\n# ports to bind (this should bind\n# 127.0.0.1:20205 on IPv6 and\n# localhost:20204 on IPv4)\n# See Net::Server::Proto\nhost        127.0.0.1\nipv         IPv6\nport        localhost:20204/IPv4\nport        20205\n\n# reverse lookups ?\n# reverselookups on\n\n#-------------- file test.conf --------------\n",
                "subsections": []
            },
            "PROCESS FLOW": {
                "content": "The process flow is written in an open, easy to override, easy to hook, fashion. The basic flow\nis shown below. This is the flow of the \"$self->run\" method.\n\n$self->configurehook;\n\n$self->configure(@);\n\n$self->postconfigure;\n\n$self->postconfigurehook;\n\n$self->prebind;\n\n$self->bind;\n\n$self->postbindhook;\n\n$self->postbind;\n\n$self->preloophook;\n\n$self->loop;\n\n### routines inside a standard $self->loop\n# $self->accept;\n# $self->runclientconnection;\n# $self->done;\n\n$self->preserverclosehook;\n\n$self->serverclose;\n\nThe server then exits.\n\nDuring the client processing phase (\"$self->runclientconnection\"), the following represents\nthe program flow:\n\n$self->postaccept;\n\n$self->getclientinfo;\n\n$self->postaccepthook;\n\nif ($self->allowdeny\n&& $self->allowdenyhook) {\n\n$self->processrequest;\n\n} else {\n\n$self->requestdeniedhook;\n\n}\n\n$self->postprocessrequesthook;\n\n$self->postprocessrequest;\n\n$self->postclientconnectionhook;\n\nThe process then loops and waits for the next connection. For a more in depth discussion, please\nread the code.\n\nDuring the server shutdown phase (\"$self->serverclose\"), the following represents the program\nflow:\n\n$self->closechildren;  # if any\n\n$self->postchildcleanuphook;\n\nif (Restarting server) {\n$self->restartclosehook();\n$self->hupserver;\n}\n\n$self->shutdownsockets;\n\n$self->serverexit;\n",
                "subsections": []
            },
            "MAIN SERVER METHODS": {
                "content": "\"$self->run\"\nThis method incorporates the main process flow. This flow is listed above.\n\nThe method run may be called in any of the following ways.\n\nMyPackage->run(port => 20201);\n\nMyPackage->new({port => 20201})->run;\n\nmy $obj = bless {server=>{port => 20201}}, 'MyPackage';\n$obj->run;\n\nThe ->run method should typically be the last method called in a server start script (the\nserver will exit at the end of the ->run method).\n\n\"$self->configure\"\nThis method attempts to read configurations from the commandline, from the run method call,\nor from a specified conffile (the conffile may be specified by passed in parameters, or in\nthe defaultvalues). All of the configured parameters are then stored in the {\"server\"}\nproperty of the Server object.\n\n\"$self->postconfigure\"\nThe postconfigure hook begins the startup of the server. During this method running server\ninstances are checked for, pidfiles are created, logfiles are created, Sys::Syslog is\ninitialized (as needed), process backgrounding occurs and the server closes STDIN and STDOUT\n(as needed).\n\n\"$self->prebind\"\nThis method is used to initialize all of the socket objects used by the server.\n\n\"$self->bind\"\nThis method actually binds to the initialized sockets (or rebinds if the server has been\nHUPed).\n\n\"$self->postbind\"\nDuring this method privileges are dropped. The INT, TERM, and QUIT signals are set to run\nserverclose. Sig PIPE is set to IGNORE. Sig CHLD is set to sigchld. And sig HUP is set to\ncall sighup.\n\nUnder the Fork, PreFork, and PreFork simple personalities, these signals are registered\nusing Net::Server::SIG to allow for safe signal handling.\n\n\"$self->loop\"\nDuring this phase, the server accepts incoming connections. The behavior of how the\naccepting occurs and if a child process handles the connection is controlled by what type of\nNet::Server personality the server is using.\n\nNet::Server and Net::Server single accept only one connection at a time.\n\nNet::Server::INET runs one connection and then exits (for use by inetd or xinetd daemons).\n\nNet::Server::MultiPlex allows for one process to simultaneously handle multiple connections\n(but requires rewriting the processrequest code to operate in a more \"packet-like\" manner).\n\nNet::Server::Fork forks off a new child process for each incoming connection.\n\nNet::Server::PreForkSimple starts up a fixed number of processes that all accept on incoming\nconnections.\n\nNet::Server::PreFork starts up a base number of child processes which all accept on incoming\nconnections. The server throttles the number of processes running depending upon the number\nof requests coming in (similar to concept to how Apache controls its child processes in a\nPreFork server).\n\nRead the documentation for each of the types for more information.\n\n\"$self->serverclose\"\nThis method is called once the server has been signaled to end, or signaled for the server\nto restart (via HUP), or the loop method has been exited.\n\nThis method takes care of cleaning up any remaining child processes, setting appropriate\nflags on sockets (for HUPing), closing up logging, and then closing open sockets.\n\nCan optionally be passed an exit value that will be passed to the serverexit call.\n\n\"$self->serverexit\"\nThis method is called at the end of serverclose. It calls exit, but may be overridden to do\nother items. At this point all services should be shut down.\n\nCan optionally be passed an exit value that will be passed to the exit call.\n",
                "subsections": []
            },
            "MAIN CLIENT CONNECTION METHODS": {
                "content": "\"$self->runclientconnection\"\nThis method is run after the server has accepted and received a client connection. The full\nprocess flow is listed above under PROCESS FLOWS. This method takes care of handling each\nclient connection.\n\n\"$self->postaccept\"\nThis method opens STDIN and STDOUT to the client socket. This allows any of the methods\nduring the runclientconnection phase to print directly to and read directly from the\nclient socket.\n\n\"$self->getclientinfo\"\nThis method looks up information about the client connection such as ip address, socket\ntype, and hostname (as needed).\n\n\"$self->allowdeny\"\nThis method uses the rules defined in the allow and deny configuration parameters to\ndetermine if the ip address should be accepted.\n\n\"$self->processrequest\"\nThis method is intended to handle all of the client communication. At this point STDIN and\nSTDOUT are opened to the client, the ip address has been verified. The server can then\ninteract with the client connection according to whatever API or protocol the server is\nimplementing. Note that the stub implementation uses STDIN and STDOUT and will not work if\nthe noclientstdout flag is set.\n\nThis is the main method to override.\n\nThe default method implements a simple echo server that will repeat whatever is sent. It\nwill quit the child if \"quit\" is sent, and will exit the server if \"exit\" is sent.\n\nAs of version 2.000, the client handle is passed as an argument.\n\n\"$self->postprocessrequest\"\nThis method is used to clean up the client connection and to handle any parent/child\naccounting for the forking servers.\n",
                "subsections": []
            },
            "HOOKS": {
                "content": "\"Net::Server\" provides a number of \"hooks\" allowing for servers layered on top of \"Net::Server\"\nto respond at different levels of execution without having to \"SUPER\" class the main built-in\nmethods. The placement of the hooks can be seen in the PROCESS FLOW section.\n\nAlmost all of the default hook methods do nothing. To use a hook you simply need to override the\nmethod in your subclass. For example to add your own postconfigurehook you could do something\nlike the following:\n\npackage MyServer;\n\nsub postconfigurehook {\nmy $self = shift;\nmy $prop = $self->{'server'};\n\n# do some validation here\n}\n\nThe following describes the hooks available in the plain Net::Server class (other flavors such\nas Fork or PreFork have additional hooks).\n\n\"$self->configurehook()\"\nThis hook takes place immediately after the \"->run()\" method is called. This hook allows for\nsetting up the object before any built in configuration takes place. This allows for custom\nconfigurability.\n\n\"$self->postconfigurehook()\"\nThis hook occurs just after the reading of configuration parameters and initiation of\nlogging and pidfile creation. It also occurs before the \"->prebind()\" and \"->bind()\"\nmethods are called. This hook allows for verifying configuration parameters.\n\n\"$self->postbindhook()\"\nThis hook occurs just after the bind process and just before any chrooting, change of user,\nor change of group occurs. At this point the process will still be running as the user who\nstarted the server.\n\n\"$self->preloophook()\"\nThis hook occurs after chroot, change of user, and change of group has occurred. It allows\nfor preparation before looping begins.\n\n\"$self->canreadhook()\"\nThis hook occurs after a socket becomes readable on an acceptmultiport request\n(acceptmultiport is used if there are multiple bound ports to accept on, or if the\n\"multiport\" configuration parameter is set to true). This hook is intended to allow for\nprocessing of arbitrary handles added to the IO::Select used for the acceptmultiport.\nThese handles could be added during the postbindhook. No internal support is added for\nprocessing these handles or adding them to the IO::Socket. Care must be used in how much\noccurs during the canreadhook as a long response time will result in the server being\nsusceptible to DOS attacks. A return value of true indicates that the Server should not pass\nthe readable handle on to the postaccept and processrequest phases.\n\nIt is generally suggested that other avenues be pursued for sending messages via sockets not\ncreated by the Net::Server.\n\n\"$self->postaccepthook()\"\nThis hook occurs after a client has connected to the server. At this point STDIN and STDOUT\nare mapped to the client socket. This hook occurs before the processing of the request.\n\n\"$self->allowdenyhook()\"\nThis hook allows for the checking of ip and host information beyond the\n\"$self->allowdeny()\" routine. If this hook returns 1, the client request will be processed,\notherwise, the request will be denied processing.\n\nAs of version 2.000, the client connection is passed as an argument.\n\n\"$self->requestdeniedhook()\"\nThis hook occurs if either the \"$self->allowdeny()\" or \"$self->allowdenyhook()\" have\ntaken place.\n\n\"$self->postprocessrequesthook()\"\nThis hook occurs after the processing of the request, but before the client connection has\nbeen closed.\n\n\"$self->postclientconnectionhook\"\nThis is one final hook that occurs at the very end of the runclientconnection method. At\nthis point all other methods and hooks that will run during the runclientconnection have\nfinished and the client connection has already been closed.\n\nitem \"$self->otherchilddiedhook($pid)\"\n\nNet::Server takes control of signal handling and child process cleanup; this makes it\ndifficult to tell when a child process terminates if that child process was not started by\nNet::Server itself. If Net::Server notices another child process dying that it did not\nstart, it will fire this hook with the PID of the terminated process.\n\n\"$self->preserverclosehook()\"\nThis hook occurs before the server begins shutting down.\n\n\"$self->writetologhook\"\nThis hook handles writing to log files. The default hook is to write to STDERR, or to the\nfilename contained in the parameter \"logfile\". The arguments passed are a log level of 0 to\n4 (4 being very verbose), and a log line. If logfile is equal to \"Sys::Syslog\", then\nlogging will go to Sys::Syslog and will bypass the writetologhook.\n\n\"$self->fatalhook\"\nThis hook occurs when the server has encountered an unrecoverable error. Arguments passed\nare the error message, the package, file, and line number. The hook may close the server,\nbut it is suggested that it simply return and use the built in shut down features.\n\n\"$self->postchildcleanuphook\"\nThis hook occurs in the parent server process after all children have been shut down and\njust before the server either restarts or exits. It is intended for additional cleanup of\ninformation. At this point pidfiles and lockfiles still exist.\n\n\"$self->restartopenhook\"\nThis hook occurs if a server has been HUPed (restarted via the HUP signal. It occurs just\nbefore reopening to the filenos of the sockets that were already opened.\n\n\"$self->restartclosehook\"\nThis hook occurs if a server has been HUPed (restarted via the HUP signal. It occurs just\nbefore restarting the server via exec.\n\n\"$self->childinithook()\"\nThis hook is called during the forking servers. It is also called during rundequeue. It\nruns just after the fork and after signals have been cleaned up. If it is a dequeue process,\nthe string 'dequeue' will be passed as an argument.\n\nIf your child processes will be needing random numbers, this hook is a good location to\ninitialize srand (forked processes maintain the same random seed unless changed).\n\nsub childinithook {\n# from perldoc -f srand\nsrand(time ^ $$ ^ unpack \"%L*\", `ps axww | gzip -f`);\n}\n\n\"$self->preforkhook()\"\nSimilar to the childinithook, but occurs just before the fork.\n\n\"$self->childfinishhook()\"\nSimilar to the childinithook, but ran when the forked process is about to finish up.\n",
                "subsections": []
            },
            "OTHER METHODS": {
                "content": "\"$self->defaultvalues\"\nAllow for returning configuration values that will be used if no other value could be found.\n\nShould return a hashref.\n\nsub defaultvalues {\nreturn {\nport => 20201,\n};\n}\n\n\"$self->handlesyslogerror\"\nCalled when logfile is set to 'Sys::Syslog' and an error occurs while writing to the\nsyslog. It is passed two arguments, the value of $@, and an arrayref containing the\narguments that were passed to the log method when the error occurred.\n\n\"$self->log\"\nParameters are a loglevel and a message.\n\nIf loglevel is set to 'Sys::Syslog', the parameters may alternately be a loglevel, a\nformat string, and format string parameters. (The second parameter is assumed to be a format\nstring if additional arguments are passed along). Passing arbitrary format strings to\nSys::Syslog will allow the server to be vulnerable to exploit. The server maintainer should\nmake sure that any string treated as a format string is controlled.\n\n# assuming logfile = 'Sys::Syslog'\n\n$self->log(1, \"My Message with %s in it\");\n# sends \"%s\", \"My Message with %s in it\" to syslog\n\n$self->log(1, \"My Message with %s in it\", \"Foo\");\n# sends \"My Message with %s in it\", \"Foo\" to syslog\n\nIf logfile is set to a file (other than Sys::Syslog), the message will be appended to the\nlog file by calling the writetologhook.\n\nIf the logfile is Sys::Syslog and an error occurs during write, the handlesyslogerror\nmethod will be called and passed the error exception. The default option of\nhandlesyslogerror is to die - but could easily be told to do nothing by using the\nfollowing code in your subclassed server:\n\nsub handlesyslogerror {}\n\nIt the log had been closed, you could attempt to reopen it in the error handler with the\nfollowing code:\n\nsub handlesyslogerror {\nmy $self = shift;\n$self->opensyslog;\n}\n\n\"$self->new\"\nAs of Net::Server 0.91 there is finally a \"new\" method. This method takes a class name and\nan argument hashref as parameters. The argument hashref becomes the \"server\" property of the\nobject.\n\npackage MyPackage;\nuse base qw(Net::Server);\n\nmy $obj = MyPackage->new({port => 20201});\n\n# same as\n\nmy $obj = bless {server => {port => 20201}}, 'MyPackage';\n\n\"$self->opensyslog\"\nCalled during postconfigure when the logfile option is set to 'Sys::Syslog'. By default it\nuse the parsed configuration options listed in this document. If more custom behavior is\ndesired, the method could be overridden and Sys::Syslog::openlog should be called with the\ncustom parameters.\n\n\"$self->shutdownsockets\"\nThis method will close any remaining open sockets. This is called at the end of the\nserverclose method.\n",
                "subsections": []
            },
            "RESTARTING": {
                "content": "Each of the server personalities (except for INET), support restarting via a HUP signal (see\n\"kill -l\"). When a HUP is received, the server will close children (if any), make sure that\nsockets are left open, and re-exec using the same commandline parameters that initially started\nthe server. (Note: for this reason it is important that @ARGV is not modified until \"->run\" is\ncalled).\n\nThe Net::Server will attempt to find out the commandline used for starting the program. The\nattempt is made before any configuration files or other arguments are processed. The outcome of\nthis attempt is stored using the method \"->commandline\". The stored commandline may also be\nretrieved using the same method name. The stored contents will undoubtedly contain Tainted items\nthat will cause the server to die during a restart when using the -T flag (Taint mode). As it is\nimpossible to arbitrarily decide what is taint safe and what is not, the individual program must\nclean up the tainted items before doing a restart.\n\nsub configurehook{\nmy $self = shift;\n\n### see the contents\nmy $ref  = $self->commandline;\nuse Data::Dumper;\nprint Dumper $ref;\n\n### arbitrary untainting - VERY dangerous\nmy @untainted = map {/(.+)/;$1} @$ref;\n\n$self->commandline(\\@untainted)\n}\n",
                "subsections": []
            },
            "SHUTDOWN": {
                "content": "Each of the Fork and PreFork personalities support graceful shutdowns via the QUIT signal. When\na QUIT is received, the parent will signal the children and then wait for them to exit.\n\nAll server personalities support the normal TERM and INT signal shutdowns.\n",
                "subsections": []
            },
            "HOT DEPLOY": {
                "content": "Since version 2.000, the Fork and PreFork personalities have accepted the TTIN and TTOU signals.\nWhen a TTIN is received, the maxservers is increased by 1. If a TTOU signal is received the\nmaxservers is decreased by 1. This allows for adjusting the number of handling processes\nwithout having to restart the server.\n\nIf the loglevel is set to at 3, then the new value is displayed in the logs.\n",
                "subsections": []
            },
            "FILES": {
                "content": "The following files are installed as part of this distribution.\n\nNet/Server.pm\nNet/Server/Fork.pm\nNet/Server/INET.pm\nNet/Server/MultiType.pm\nNet/Server/PreForkSimple.pm\nNet/Server/PreFork.pm\nNet/Server/Single.pm\nNet/Server/Daemonize.pm\nNet/Server/SIG.pm\nNet/Server/Proto.pm\nNet/Server/Proto/*.pm\n",
                "subsections": []
            },
            "INSTALL": {
                "content": "Download and extract tarball before running these commands in its base directory:\n\nperl Makefile.PL\nmake\nmake test\nmake install\n",
                "subsections": []
            },
            "AUTHOR": {
                "content": "Paul Seamons <paul at seamons.com>\nhttp://seamons.com/\n\nRob Brown <bbb at cpan.org>\n",
                "subsections": []
            },
            "THANKS": {
                "content": "As we move to a github flow, please be sure to add yourself to the credits as patches are passed\nalong (if you'd like to be mentioned).\n\nThanks to Rob Brown (bbb at cpan.org) for help with miscellaneous concepts such as tracking down\nthe serialized select via flock ala Apache and the reference to IO::Select making multiport\nservers possible. And for researching into allowing sockets to remain open upon exec (making HUP\npossible).\n\nThanks to Jonathan J. Miner <miner at doit.wisc.edu> for patching a blatant problem in the\nreverse lookups.\n\nThanks to Bennett Todd <bet at rahul.net> for pointing out a problem in Solaris 2.5.1 which does\nnot allow multiple children to accept on the same port at the same time. Also for showing some\nsample code from Viktor Duchovni which now represents the semaphore option of the serialize\nargument in the PreFork server.\n\nThanks to *traveler* and *merlyn* from http://perlmonks.org for pointing me in the right\ndirection for determining the protocol used on a socket connection.\n\nThanks to Jeremy Howard <j+daemonize at howard.fm> for numerous suggestions and for work on\nNet::Server::Daemonize.\n\nThanks to Vadim <vadim at hardison.net> for patches to implement parent/child communication on\nPreFork.pm.\n\nThanks to Carl Lewis for suggesting \"-\" in user names.\n\nThanks to Slaven Rezic for suggesting Reuse => 1 in Proto::UDP.\n\nThanks to Tim Watt for adding udpbroadcast to Proto::UDP.\n\nThanks to Christopher A Bongaarts for pointing out problems with the Proto::SSL implementation\nthat currently locks around the socket accept and the SSL negotiation. See\nNet::Server::Proto::SSL.\n\nThanks to Alessandro Zummo for pointing out various bugs including some in configuration,\ncommandline args, and cidrallow.\n\nThanks to various other people for bug fixes over the years. These and future thank-you's are\navailable in the Changes file as well as CVS comments.\n\nThanks to Ben Cohen and tye (on Permonks) for finding and diagnosing more correct behavior for\ndealing with re-opening STDIN and STDOUT on the client handles.\n\nThanks to Mark Martinec for trouble shooting other problems with STDIN and STDOUT (he proposed\nhaving a flag that is now the noclientstdout flag).\n\nThanks to David (DSCHWEI) on cpan for asking for the nofatal option with syslog.\n\nThanks to Andreas Kippnick and Peter Beckman for suggesting leaving open child connections open\nduring a HUP (this is now available via the leavechildrenopenonhup flag).\n\nThanks to LUPE on cpan for helping patch HUP with taint on.\n\nThanks to Michael Virnstein for fixing a bug in the checkfordead section of PreFork server.\n\nThanks to Rob Mueller for patching PreForkSimple to only open lockfile once during parent call.\nThis patch should be portable on systems supporting flock. Rob also suggested not closing\nSTDIN/STDOUT but instead reopening them to /dev/null to prevent spurious warnings. Also\nsuggested short circuit in postaccept if in UDP. Also for cleaning up some of the child\nmanagement code of PreFork.\n\nThanks to Mark Martinec for suggesting additional log messages for failure during accept.\n\nThanks to Bill Nesbitt and Carlos Velasco for pointing out double decrement bug in PreFork.pm\n(rt #21271)\n\nThanks to John W. Krahn for pointing out glaring precended with non-parened open and ||.\n\nThanks to Ricardo Signes for pointing out setuid bug for perl 5.6.1 (rt #21262).\n\nThanks to Carlos Velasco for updating the Syslog options (rt #21265). And for additional fixes\nlater.\n\nThanks to Steven Lembark for pointing out that noclientstdout wasn't working with the\nMultiplex server.\n\nThanks to Peter Beckman for suggesting allowing Sys::SysLog keywords be passed through the ->log\nmethod and for suggesting we allow more types of characters through in syslogident. Also to\nPeter Beckman for pointing out that a poorly setup localhost will cause tests to hang.\n\nThanks to Curtis Wilbar for pointing out that the Fork server called postaccepthook twice.\nChanged to only let the child process call this, but added the preforkhook method.\n\nAnd just a general Thanks You to everybody who is using Net::Server or who has contributed fixes\nover the years.\n\nThanks to Paul Miller for some ->autoflush, FileHandle fixes.\n\nThanks to Patrik Wallstrom for suggesting handling syslog errors better.\n\nThanks again to Rob Mueller for more logic cleanup for child accounting in PreFork server.\n\nThanks to David Schweikert for suggesting handling setlogsock a little better on newer versions\nof Sys::Syslog (>= 0.15).\n\nThanks to Mihail Nasedkin for suggesting adding a hook that is now called\npostclientconnectionhook.\n\nThanks to Graham Barr for adding the ability to set the checkforspawn and minchildttl\nsettings of the PreFork server.\n\nThanks to Daniel Kahn Gillmor for adding the otherchilddiedhook.\n\nThanks to Dominic Humphries for helping not kill pid files on HUP.\n\nThanks to Kristoffer Møllerhøj for fixing UDP on Multiplex.\n\nThanks to mishikal for patches for helping identify un-cleaned up children.\n\nThanks to rpkelly and tim@retout for pointing out error in header regex of HTTP.\n\nThanks to dmcbride for some basic HTTP parsing fixes, as well as for some broken tied handle\nfixes.\n\nThanks to Gareth for pointing out glaring bug issues with broken pipe and semaphore\nserialization.\n\nThanks to CATONE for sending the idea for arbitrary signal passing to children. (See the\nsigpassthrough option)\n\nThanks to intrigeri@boum for pointing out and giving code ideas for NSport not functioning\nafter a HUP.\n\nThanks to Sergey Zasenko for adding sysread/syswrite support to SSLEAY as well as the base test.\n\nThanks to mbarbon@users. for adding tally dequeue to prefork server.\n\nThanks to stefanos@cpan for fixes to PreFork under Win32\n\nThanks to Mark Martinec for much of the initial work towards getting IPv6 going.\n\nThanks to the munin developers and Nicolai Langfeldt for hosting the development version of\nNet::Server for so long and for fixes to the allowdeny checking for IPv6 addresses.\n\nThanks to Tatsuhiko Miyagawa for feedback, and for suggesting adding graceful shutdowns and hot\ndeploy (maxservers adjustment).\n\nThanks to TONVOON@cpan for submitting a patch adding Log4perl functionality.\n\nThanks to Miko O'Sullivan for fixes to HTTP to correct tainting issues and passing initial log\nfixes, and for patches to fix CLOSE on tied stdout and various other HTTP issues.\n",
                "subsections": []
            },
            "SEE ALSO": {
                "content": "Please see also Net::Server::Fork, Net::Server::INET, Net::Server::PreForkSimple,\nNet::Server::PreFork, Net::Server::MultiType, Net::Server::Single Net::Server::HTTP\n",
                "subsections": []
            },
            "TODO": {
                "content": "Improve test suite to fully cover code (using Devel::Cover). Anybody that wanted to send me\npatches to the t/*.t tests that improved coverage would earn a big thank you.\n",
                "subsections": []
            },
            "CODE REPOSITORY": {
                "content": "https://github.com/rhandom/perl-net-server\n",
                "subsections": []
            },
            "LICENSE": {
                "content": "This package may be distributed under the terms of either the\n\nGNU General Public License\nor the\nPerl Artistic License\n\nAll rights reserved.\n",
                "subsections": []
            }
        }
    }
}