/usr/share/perl5/Net/Server.pod is in libnet-server-perl 2.009-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 | =encoding utf8
=head1 NAME
Net::Server - Extensible, general Perl server engine
=head1 SYNOPSIS
#!/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: beginning in Net::Server 2.005, the default value for
ipv is IPv* meaning that if no host is passed, or
a hostname is past, any available IPv4 and IPv6 sockets will be
bound. You can force IPv4 only by adding an ipv => 4
configuration in any of the half dozen ways we let you
specify it.
=head1 FEATURES
* 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
=head1 DESCRIPTION
C<Net::Server> is an extensible, generic Perl server engine.
C<Net::Server> attempts to be a generic server as in C<Net::Daemon>
and C<NetServer::Generic>. It includes with it the ability to run as
an inetd process (C<Net::Server::INET>), a single connection server
(C<Net::Server> or C<Net::Server::Single>), a forking server
(C<Net::Server::Fork>), a preforking server which maintains a constant
number of preforked children (C<Net::Server::PreForkSimple>), or as a
managed preforking server which maintains the number of children based
on server load (C<Net::Server::PreFork>). In all but the inetd type,
the server provides the ability to connect to one or to multiple
server ports.
The additional server types are made possible via "personalities" or
sub classes of the C<Net::Server>. By moving the multiple types of
servers out of the main C<Net::Server> class, the C<Net::Server>
concept is easily extended to other types (in the near future, we
would like to add a "Thread" personality).
C<Net::Server> borrows several concepts from the Apache Webserver.
C<Net::Server> uses "hooks" to allow custom servers such as SMTP,
HTTP, POP3, etc. to be layered over the base C<Net::Server> class. In
addition the C<Net::Server::PreFork> class borrows concepts of
min_start_servers, max_servers, and min_waiting servers.
C<Net::Server::PreFork> also uses the concept of an flock serialized
accept when accepting on multiple ports (PreFork can choose between
flock, IPC::Semaphore, and pipe to control serialization).
=head1 PERSONALITIES
C<Net::Server> is built around a common class (Net::Server) and is
extended using sub classes, or C<personalities>. Each personality
inherits, overrides, or enhances the base methods of the base class.
Included with the Net::Server package are several basic personalities,
each of which has their own use.
=over 4
=item Fork
Found in the module Net/Server/Fork.pm (see L<Net::Server::Fork>).
This server binds to one or more ports and then waits for a
connection. When a client request is received, the parent forks a
child, which then handles the client and exits. This is good for
moderately hit services.
=item INET
Found in the module Net/Server/INET.pm (see L<Net::Server::INET>).
This server is designed to be used with inetd. The C<pre_bind>,
C<bind>, C<accept>, and C<post_accept> are all overridden as these
services are taken care of by the INET daemon.
=item MultiType
Found in the module Net/Server/MultiType.pm (see
L<Net::Server::MultiType>). This server has no server functionality
of its own. It is designed for servers which need a simple way to
easily switch between different personalities. Multiple
C<server_type> parameters may be given and Net::Server::MultiType will
cycle through until it finds a class that it can use.
=item Multiplex
Found in the module Net/Server/Multiplex.pm (see
L<Net::Server::Multiplex>). This server binds to one or more ports.
It 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. The
C<process_request> method is never used but the C<mux_input> callback
is used instead (see also L<IO::Multiplex>). See
examples/samplechat.pl for an example using most of the features of
Net::Server::Multiplex.
=item PreForkSimple
Found in the module Net/Server/PreFork.pm (see
L<Net::Server::PreFork>). This server binds to one or more ports and
then forks C<max_servers> child process. The server will make sure
that at any given time there are always C<max_servers> available to
receive a client request. Each of these children will process up to
C<max_requests> client connections. This type is good for a heavily
hit site that can dedicate max_server processes no matter what the
load. 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
single port in order to get around an OS that does not allow multiple
children to accept at the same time. For a further discussion of
serialization see L<Net::Server::PreFork>.
=item PreFork
Found in the module Net/Server/PreFork.pm (see
L<Net::Server::PreFork>). This server binds to one or more ports and
then forks C<min_servers> child process. The server will make sure
that at any given time there are at least C<min_spare_servers> but not
more than C<max_spare_servers> available to receive a client request,
up to C<max_servers>. Each of these children will process up to
C<max_requests> client connections. This type is good for a heavily
hit site, and 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
single port in order to get around an OS that does not allow multiple
children to accept at the same time. For a further discussion of
serialization see L<Net::Server::PreFork>.
=item Single
All methods fall back to Net::Server. This personality is provided
only as parallelism for Net::Server::MultiType.
=item HTTP
Not a distinct personality. Provides a basic HTTP daemon. This can
be combined with the SSL or SSLEAY proto to provide an HTTPS Daemon.
See L<Net::Server::HTTP>.
=back
C<Net::Server> was partially written to make it easy to add new
personalities. Using separate modules built upon an open architecture
allows for easy addition of new features, a separate development
process, and reduced code bloat in the core module.
=head1 SOCKET ACCESS
Once started, the Net::Server will take care of binding to port and
waiting for connections. Once a connection is received, the
Net::Server will accept on the socket and will store the result (the
client connection) in $self-E<gt>{server}-E<gt>{client}. This
property is a Socket blessed into the IO::Socket classes. UDP
servers are slightly different in that they will perform a B<recv>
instead of an B<accept>.
To make programming easier, during the post_accept phase, STDIN and
STDOUT are opened to the client connection. This allows for programs
to be written using E<lt>STDINE<gt> and print "out\n" to print to the
client connection. UDP will require using a -E<gt>send call.
=head1 SAMPLE CODE
The following is a very simple server. The main functionality occurs
in the process_request method call as shown below. Notice the use of
timeouts to prevent Denial of Service while reading. (Other examples
of using C<Net::Server> can, or will, be included with this
distribution).
#!/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;
Playing this file from the command line will invoke a Net::Server
using the PreFork personality. When building a server layer over the
Net::Server, it is important to use features such as timeouts to
prevent Denial Of Service attacks.
Net::Server comes with a built in echo server by default. You can test it
out by simply running the following from the commandline:
net-server
If you wanted to try another flavor you could try
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 are writing you could use
net-server HTTP --app ../../mycgi.cgi
=head1 ARGUMENTS
There are at least five possible ways to pass arguments to
Net::Server. They are I<passing to the new method>, I<passing on
command line>, I<passing parameters to run>, I<using a conf file>,
I<returning values in the default_values method>, or I<configuring the
values in post_configure_hook>.
The C<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 C<--key value> or C<--key=value>, and also
C<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: C<<Net::Server-E<gt>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. C<Net::Server> will look for
arguments in the following order:
1) Arguments passed to the C<new> method.
2) Arguments passed on command line.
3) Arguments passed to the C<run> method.
4) Arguments passed via a conf file.
5) Arguments set in the C<default_values> method.
Additionally the following hooks are available:
1) Arguments set in the configure_hook (occurs after new
but before any of the other areas are checked).
2) 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 C<Net::Server> can pass and
read their own parameters.
=head1 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 C<options> method allows for adding your own custom
fields. A template hashref is passed in, that should then be modified
to contain an 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 servers
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.
=head1 DEFAULT ARGUMENTS FOR Net::Server
The following arguments are available in the default C<Net::Server> or
C<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
port \d+ 20203
host "host" "*"
ipv (4|6|*) *
proto (tcp|udp|unix) "tcp"
listen \d+ SOMAXCONN
## 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 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.
=over 4
=item 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.
=item 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'.
=item 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 C<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 C<syslog_logsock>, C<syslog_ident>, and
C<syslog_logopt>,and C<syslog_facility> may also be defined. See
L<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 C<log4perl_conf>,
C<log4perl_poll>, C<log4perl_logger> may also be defined. See
L<Net::Server::Log::Log::Log4per>.
If a C<log_file> is given or if C<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.
=item pid_file
Filename to store pid of parent process. Generally applies only to
forking servers. Default is none (undef).
=item port
See L<Net::Server::Proto> for 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 C<host:port/proto>,
C<host:port/proto/ipv>, C<host:port>, C<port/proto>, or C<port>, where
I<host> represents a hostname residing on the local box, where I<port>
represents either the number of the port (eg. "80") or the service
designation (eg. "http"), where I<ipv> represents the IP protocol version
(IPv4 or IPv6 or IPv*) and where I<proto> represents the protocol to be
used. See L<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 I<host> given in a port specification overrides a default
binding address (a C<host> setting, see below). The I<host> part may
be enclosed in square brackets, but when it is a numerical IPv6
address it B<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, I<proto> will default to the
C<proto> specified in the arguments. If C<proto> is not specified
there it will default to "tcp". If I<host> is not specified, I<host>
will default to C<host> specified in the arguments. If C<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 C<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
C<socket_file|unix> or C<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.
=item 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 C<host> argument provides a default local host address
if the C<port> argument omits a host specification. See
L<Net::Server::Proto>. See L<IO::Socket>. Configuration passed to new
or run may 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
=item proto
See L<Net::Server::Proto>.
Protocol to use when binding ports. See L<IO::Socket>. As of release
2.0, Net::Server supports tcp, udp, and unix, unixdgram, ssl, and
ssleay. Other types will need to be added later (or custom modules
extending the Net::Server::Proto class may be used). Configuration
passed to new or run may 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.
=item ipv (IPv4 and IPv6)
See L<Net::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, or uninstall 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 C<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.
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
If I issue a C<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
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). 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 [*].
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" .
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.
=item listen
See L<IO::Socket>. Not used with udp protocol (or UNIX SOCK_DGRAM).
=item reverse_lookups
Specify whether to lookup the hostname of the connected IP.
Information is cached in server object under C<peerhost> property.
Default is to not use reverse_lookups (undef).
=item 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.
=item 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.
=item chroot
Directory to chroot to after bind process has taken place and the
server is still running as root. Defaults to undef.
=item user
Userid or username to become after the bind process has occurred.
Defaults to "nobody." If you would like the server to run as root,
you will have to specify C<user> equal to "root".
=item group
Groupid or groupname to become after the bind process has occurred.
Defaults to "nobody." If you would like the server to run as root,
you will have to specify C<group> equal to "root".
=item 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 C<setsid> is set.
=item setsid
Specifies whether or not the server should fork after the bind method
to release itself from the command line and then run the
C<POSIX::setsid()> command to truly daemonize. Defaults to undef. If
a C<log_file> is given or if C<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.
=item 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).
=item 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.
=item 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.
=item 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.
=item 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.
=item 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.
=item 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.
=back
=head1 PROPERTIES
All of the C<ARGUMENTS> listed above become properties of the server
object under the same name. These properties, as well as other
internal properties, are available during hooks and other method
calls.
The structure of a Net::Server object is shown below:
$self = bless({
server => {
key1 => 'val1',
# more key/vals
},
}, 'Net::Server');
This structure was chosen so that all server related properties are
grouped under a single key of the object hashref. This is so that
other objects could layer on top of the Net::Server object class and
still have a fairly clean namespace in the hashref.
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. 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).
=head1 CONFIGURATION FILE
C<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.
#-------------- 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 --------------
=head1 PROCESS FLOW
The process flow is written in an open, easy to
override, easy to hook, fashion. The basic flow is
shown below. This is the flow of the C<$self-E<gt>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.
During the client processing phase
(C<$self-E<gt>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 process then loops and waits for the next connection. For a more
in depth discussion, please read the code.
During the server shutdown phase (C<$self-E<gt>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;
=head1 MAIN SERVER METHODS
=over 4
=item C<$self-E<gt>run>
This method incorporates the main process flow. This flow is listed
above.
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).
=item C<$self-E<gt>configure>
This method attempts to read configurations from the commandline, from
the run method call, or from a specified conf_file (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.
=item C<$self-E<gt>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).
=item C<$self-E<gt>pre_bind>
This method is used to initialize all of the socket objects used by
the server.
=item C<$self-E<gt>bind>
This method actually binds to the initialized sockets (or rebinds if the
server has been HUPed).
=item C<$self-E<gt>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.
Under the Fork, PreFork, and PreFork simple personalities, these
signals are registered using Net::Server::SIG to allow for safe signal
handling.
=item C<$self-E<gt>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.
Net::Server and Net::Server single accept only one connection at a
time.
Net::Server::INET runs one connection and then exits (for use by inetd
or xinetd daemons).
Net::Server::MultiPlex allows for one process to simultaneously handle
multiple connections (but requires rewriting the process_request code
to operate in a more "packet-like" manner).
Net::Server::Fork forks off a new child process for each incoming
connection.
Net::Server::PreForkSimple starts up a fixed number of processes that
all accept on incoming connections.
Net::Server::PreFork starts 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.
=item C<$self-E<gt>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.
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.
Can optionally be passed an exit value that will be passed to the
server_exit call.
=item C<$self-E<gt>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.
Can optionally be passed an exit value that will be passed to the exit call.
=back
=head1 MAIN CLIENT CONNECTION METHODS
=over 4
=item C<$self-E<gt>run_client_connection>
This method is run after the server has accepted and received a client
connection. The full process flow is listed above under PROCESS
FLOWS. This method takes care of handling each client connection.
=item C<$self-E<gt>post_accept>
This method opens STDIN and STDOUT to the client socket. This allows
any of the methods during the run_client_connection phase to print
directly to and read directly from the client socket.
=item C<$self-E<gt>get_client_info>
This method looks up information about the client connection such as
ip address, socket type, and hostname (as needed).
=item C<$self-E<gt>allow_deny>
This method uses the rules defined in the allow and deny configuration
parameters to determine if the ip address should be accepted.
=item C<$self-E<gt>process_request>
This method is intended to handle all of the client communication. At
this point STDIN and STDOUT are 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 uses STDIN and STDOUT
and will not work if the no_client_stdout flag 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.
=item C<$self-E<gt>post_process_request>
This method is used to clean up the client connection and to handle
any parent/child accounting for the forking servers.
=back
=head1 HOOKS
C<Net::Server> provides a number of "hooks" allowing for servers
layered on top of C<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).
=over 4
=item C<$self-E<gt>configure_hook()>
This hook takes place immediately after the C<-E<gt>run()> method is
called. This hook allows for setting up the object before any built
in configuration takes place. This allows for custom configurability.
=item C<$self-E<gt>post_configure_hook()>
This hook occurs just after the reading of configuration parameters
and initiation of logging and pid_file creation. It also occurs
before the C<-E<gt>pre_bind()> and C<-E<gt>bind()> methods are called.
This hook allows for verifying configuration parameters.
=item C<$self-E<gt>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.
=item C<$self-E<gt>pre_loop_hook()>
This hook occurs after chroot, change of user, and change of group has
occurred. It allows for preparation before looping begins.
=item C<$self-E<gt>can_read_hook()>
This hook occurs after a socket becomes readable on an
accept_multi_port request (accept_multi_port is used if there are
multiple bound ports to accept on, or if the "multi_port"
configuration parameter is set to true). This hook is intended to
allow for processing of arbitrary handles added to the IO::Select used
for the accept_multi_port. These handles could be added during the
post_bind_hook. No internal support is added for processing these
handles or adding them to the IO::Socket. Care must be used in how
much occurs during the can_read_hook as 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 the post_accept and process_request phases.
It is generally suggested that other avenues be pursued for sending
messages via sockets not created by the Net::Server.
=item C<$self-E<gt>post_accept_hook()>
This hook occurs after a client has connected to the server. At this
point STDIN and STDOUT are mapped to the client socket. This hook
occurs before the processing of the request.
=item C<$self-E<gt>allow_deny_hook()>
This hook allows for the checking of ip and host information beyond
the C<$self-E<gt>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.
=item C<$self-E<gt>request_denied_hook()>
This hook occurs if either the C<$self-E<gt>allow_deny()> or
C<$self-E<gt>allow_deny_hook()> have taken place.
=item C<$self-E<gt>post_process_request_hook()>
This hook occurs after the processing of the request, but before the
client connection has been closed.
=item C<$self-E<gt>post_client_connection_hook>
This is one final hook that occurs at the very end of the
run_client_connection method. At this point all other methods and
hooks that will run during the run_client_connection have finished and
the client connection has already been closed.
item C<$self-E<gt>other_child_died_hook($pid)>
Net::Server takes 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 by Net::Server
itself. If Net::Server notices another child process dying that it
did not start, it will fire this hook with the PID of the terminated
process.
=item C<$self-E<gt>pre_server_close_hook()>
This hook occurs before the server begins shutting down.
=item C<$self-E<gt>write_to_log_hook>
This hook handles writing to log files. The default hook is to write
to STDERR, or to the filename contained in the parameter C<log_file>.
The arguments passed are a log level of 0 to 4 (4 being very verbose),
and a log line. If log_file is equal to "Sys::Syslog", then logging
will go to Sys::Syslog and will bypass the write_to_log_hook.
=item C<$self-E<gt>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.
=item C<$self-E<gt>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 point
pid_files and lockfiles still exist.
=item C<$self-E<gt>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.
=item C<$self-E<gt>restart_close_hook>
This hook occurs if a server has been HUPed (restarted via the HUP
signal. It occurs just before restarting the server via exec.
=item C<$self-E<gt>child_init_hook()>
This hook is called during the forking servers. It is also called
during run_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`);
}
=item C<$self-E<gt>pre_fork_hook()>
Similar to the child_init_hook, but occurs just before the fork.
=item C<$self-E<gt>child_finish_hook()>
Similar to the child_init_hook, but ran when the forked process is
about to finish up.
=back
=head1 OTHER METHODS
=over 4
=item C<$self-E<gt>default_values>
Allow for returning configuration values that will be used if no other
value could be found.
Should return a hashref.
sub default_values {
return {
port => 20201,
};
}
=item C<$self-E<gt>handle_syslog_error>
Called when log_file is set to 'Sys::Syslog' and an error occurs while
writing to the syslog. It is passed two arguments, the value of $@,
and an arrayref containing the arguments that were passed to the log
method when the error occurred.
=item C<$self-E<gt>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). 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
could easily be told to do nothing by using the following code in your
subclassed server:
sub handle_syslog_error {}
It 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;
}
=item C<$self-E<gt>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.
package MyPackage;
use base qw(Net::Server);
my $obj = MyPackage->new({port => 20201});
# same as
my $obj = bless {server => {port => 20201}}, 'MyPackage';
=item C<$self-E<gt>open_syslog>
Called during post_configure when the log_file option is set to
'Sys::Syslog'. By default it use 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.
=item C<$self-E<gt>shutdown_sockets>
This method will close any remaining open sockets. This is called at
the end of the server_close method.
=back
=head1 RESTARTING
Each of the server personalities (except for INET), support 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 C<-E<gt>run> is called).
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 C<-E<gt>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)
}
=head1 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.
=head1 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.
If the log_level is set to at 3, then the new value is displayed in
the logs.
=head1 FILES
The following files are installed as part of this distribution.
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
=head1 INSTALL
Download and extract tarball before running these commands in its base
directory:
perl Makefile.PL
make
make test
make install
=head1 AUTHOR
Paul Seamons <paul at seamons.com>
=head1 THANKS
As we move to a github flow, please be sure to add yourself to the
credits as patches are passed along (if you'd like to be mentioned).
Thanks to Rob Brown (bbb at cpan.org) for help with miscellaneous
concepts such as tracking down the serialized select via flock ala
Apache and the reference to IO::Select making multiport servers
possible. And for researching into allowing sockets to remain open
upon exec (making HUP possible).
Thanks to Jonathan J. Miner <miner at doit.wisc.edu> for patching a
blatant problem in the reverse lookups.
Thanks to Bennett Todd <bet at rahul.net> for pointing 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 for showing some sample code
from Viktor Duchovni which now represents the semaphore option of the
serialize argument in the PreFork server.
Thanks to I<traveler> and I<merlyn> from http://perlmonks.org for
pointing me in the right direction for determining the protocol used
on a socket connection.
Thanks to Jeremy Howard <j+daemonize at howard.fm> for numerous
suggestions and for work on Net::Server::Daemonize.
Thanks to Vadim <vadim at hardison.net> for patches to implement
parent/child communication on PreFork.pm.
Thanks to Carl Lewis for suggesting "-" in user names.
Thanks to Slaven Rezic for suggesting Reuse => 1 in Proto::UDP.
Thanks to Tim Watt for adding udp_broadcast to Proto::UDP.
Thanks to Christopher A Bongaarts for pointing out problems with the
Proto::SSL implementation that currently locks around the socket
accept and the SSL negotiation. See L<Net::Server::Proto::SSL>.
Thanks to Alessandro Zummo for pointing out various bugs including
some in configuration, commandline args, and cidr_allow.
Thanks to various other people for bug fixes over the years. These
and future thank-you's are available in the Changes file as well as
CVS comments.
Thanks to Ben Cohen and tye (on Permonks) for finding and diagnosing
more correct behavior for dealing with re-opening STDIN and STDOUT on
the client handles.
Thanks to Mark Martinec for trouble shooting other problems with STDIN
and STDOUT (he proposed having a flag that is now the no_client_stdout
flag).
Thanks to David (DSCHWEI) on cpan for asking for the nofatal option
with syslog.
Thanks to Andreas Kippnick and Peter Beckman for suggesting leaving
open child connections open during a HUP (this is now available via
the leave_children_open_on_hup flag).
Thanks to LUPE on cpan for helping patch HUP with taint on.
Thanks to Michael Virnstein for fixing a bug in the check_for_dead
section of PreFork server.
Thanks to Rob Mueller for patching PreForkSimple to only open
lock_file once during parent call. This patch should be portable on
systems supporting flock. Rob also suggested not closing STDIN/STDOUT
but instead reopening them to /dev/null to prevent spurious warnings.
Also suggested short circuit in post_accept if in UDP. Also for
cleaning up some of the child management code of PreFork.
Thanks to Mark Martinec for suggesting additional log messages for
failure during accept.
Thanks to Bill Nesbitt and Carlos Velasco for pointing out double
decrement bug in PreFork.pm (rt #21271)
Thanks to John W. Krahn for pointing out glaring precended with
non-parened open and ||.
Thanks to Ricardo Signes for pointing out setuid bug for perl 5.6.1
(rt #21262).
Thanks to Carlos Velasco for updating the Syslog options (rt #21265).
And for additional fixes later.
Thanks to Steven Lembark for pointing out that no_client_stdout wasn't
working with the Multiplex server.
Thanks to Peter Beckman for suggesting allowing Sys::SysLog keywords
be passed through the ->log method and for suggesting we allow more
types of characters through in syslog_ident. Also to Peter Beckman
for pointing out that a poorly setup localhost will cause tests to
hang.
Thanks to Curtis Wilbar for pointing out that the Fork server called
post_accept_hook twice. Changed to only let the child process call
this, but added the pre_fork_hook method.
And just a general Thanks You to everybody who is using Net::Server or
who has contributed fixes over the years.
Thanks to Paul Miller for some ->autoflush, FileHandle fixes.
Thanks to Patrik Wallstrom for suggesting handling syslog errors
better.
Thanks again to Rob Mueller for more logic cleanup for child
accounting in PreFork server.
Thanks to David Schweikert for suggesting handling setlogsock a little
better on newer versions of Sys::Syslog (>= 0.15).
Thanks to Mihail Nasedkin for suggesting adding a hook that is now
called post_client_connection_hook.
Thanks to Graham Barr for adding the ability to set the
check_for_spawn and min_child_ttl settings of the PreFork server.
Thanks to Daniel Kahn Gillmor for adding the other_child_died_hook.
Thanks to Dominic Humphries for helping not kill pid files on HUP.
Thanks to Kristoffer Møllerhøj for fixing UDP on Multiplex.
Thanks to mishikal for patches for helping identify un-cleaned up
children.
Thanks to rpkelly and tim@retout for pointing out error in header
regex of HTTP.
Thanks to dmcbride for some basic HTTP parsing fixes, as well as for
some broken tied handle fixes.
Thanks to Gareth for pointing out glaring bug issues with broken pipe
and semaphore serialization.
Thanks to CATONE for sending the idea for arbitrary signal passing to
children. (See the sig_passthrough option)
Thanks to intrigeri@boum for pointing out and giving code ideas for
NS_port not functioning after a HUP.
Thanks to Sergey Zasenko for adding sysread/syswrite support to SSLEAY
as well as the base test.
Thanks to mbarbon@users. for adding tally dequeue to prefork server.
Thanks to stefanos@cpan for fixes to PreFork under Win32
Thanks to Mark Martinec for much of the initial work towards getting
IPv6 going.
Thanks to the munin developers and Nicolai Langfeldt for hosting the
development version of Net::Server for so long and for fixes to the
allow_deny checking for IPv6 addresses.
Thanks to Tatsuhiko Miyagawa for feedback, and for suggesting adding
graceful shutdowns and hot deploy (max_servers adjustment).
Thanks to TONVOON@cpan for submitting a patch adding Log4perl functionality.
Thanks to Miko O'Sullivan for fixes to HTTP to correct tainting issues
and passing initial log fixes, and for patches to fix CLOSE on tied stdout
and various other HTTP issues.
=head1 SEE ALSO
Please see also
L<Net::Server::Fork>,
L<Net::Server::INET>,
L<Net::Server::PreForkSimple>,
L<Net::Server::PreFork>,
L<Net::Server::MultiType>,
L<Net::Server::Single>
L<Net::Server::HTTP>
=head1 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.
=head1 CODE REPOSITORY
https://github.com/rhandom/perl-net-server
=head1 AUTHOR
Paul Seamons <paul at seamons.com>
http://seamons.com/
Rob Brown <bbb at cpan.org>
=head1 LICENSE
This package may be distributed under the terms of either the
GNU General Public License
or the
Perl Artistic License
All rights reserved.
=cut
|