/usr/share/doc/libapache2-mod-perl2-doc/docs/2.0/user/handlers/protocols.html is in libapache2-mod-perl2-doc 2.0.10-2ubuntu3.
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 | <?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:root@localhost" />
</head>
<body>
<ul id="index">
<li><a href="#NAME">NAME</a></li>
<li><a href="#Description">Description</a></li>
<li><a href="#Connection-Cycle-Phases">Connection Cycle Phases</a>
<ul>
<li><a href="#PerlPreConnectionHandler">PerlPreConnectionHandler</a></li>
<li><a href="#PerlProcessConnectionHandler">PerlProcessConnectionHandler</a>
<ul>
<li><a href="#Socket-based-Protocol-Module">Socket-based Protocol Module</a></li>
<li><a href="#Bucket-Brigades-based-Protocol-Module">Bucket Brigades-based Protocol Module</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#Examples">Examples</a>
<ul>
<li><a href="#Command-Server">Command Server</a></li>
</ul>
</li>
<li><a href="#CPAN-Modules">CPAN Modules</a></li>
<li><a href="#Maintainers">Maintainers</a></li>
<li><a href="#Authors">Authors</a></li>
</ul>
<h1 id="NAME">NAME</h1>
<p>Protocol Handlers</p>
<h1 id="Description">Description</h1>
<p>This chapter explains how to implement Protocol (Connection) Handlers in mod_perl.</p>
<h1 id="Connection-Cycle-Phases">Connection Cycle Phases</h1>
<p>As we saw earlier, each child server (be it a thread or a process) is engaged in processing connections. Each connection may be served by different connection protocols, e.g., HTTP, POP3, SMTP, etc. Each connection may include more than one request, e.g., several HTTP requests can be served over a single connection, when several images are requested for the same webpage.</p>
<p>The following diagram depicts the connection life cycle and highlights which handlers are available to mod_perl 2.0:</p>
<img src="connection_cycle.gif" width="598" height="498"
align="middle" alt="connection cycle"><br><br>
<p>When a connection is issued by a client, it's first run through <code>PerlPreConnectionHandler</code> and then passed to the <code>PerlProcessConnectionHandler</code>, which generates the response. When <code>PerlProcessConnectionHandler</code> is reading data from the client, it can be filtered by connection input filters. The generated response can be also filtered though connection output filters. Filters are usually used for modifying the data flowing though them, but can be used for other purposes as well (e.g., logging interesting information). For example the following diagram shows the connection cycle mapped to the time scale:</p>
<img src="connection_cycle_time.gif" width="599" height="300"
align="middle" alt="connection cycle timing"><br><br>
<p>The arrows show the program control. In addition, the black-headed arrows also show the data flow. This diagram matches an interactive protocol, where a client send something to the server, the server filters the input, processes it and send it out through output filters. This cycle is repeated till the client or the server don't tell each other to go away or abort the connection. Before the cycle starts any registered pre_connection handlers are run.</p>
<p>Now let's discuss each of the <code>PerlPreConnectionHandler</code> and <code>PerlProcessConnectionHandler</code> handlers in detail.</p>
<h2 id="PerlPreConnectionHandler">PerlPreConnectionHandler</h2>
<p>The <i>pre_connection</i> phase happens just after the server accepts the connection, but before it is handed off to a protocol module to be served. It gives modules an opportunity to modify the connection as soon as possible and insert filters if needed. The core server uses this phase to setup the connection record based on the type of connection that is being used. mod_perl itself uses this phase to register the connection input and output filters.</p>
<p>This phase is of type <code><a>RUN_ALL</a></code>.</p>
<p>The handler's configuration scope is <code><a>SRV</a></code>, because it's not known yet which resource the request will be mapped to.</p>
<p><b>Arguments</b></p>
<p>A <i>pre_connection</i> handler is passed a <code><a>connection record</a></code> as its argument:</p>
<pre><code> sub handler {
my $c = shift;
# ...
return Apache2::Const::OK;
}</code></pre>
<p>[META: There is another argument passed (the actual client socket), but it is currently an undef]</p>
<p><b>Return</b></p>
<p>The handler should return <code><a>Apache2::Const::OK</a></code> if it completes successfully or <code><a>Apache2::Const::FORBIDDEN</a></code> if the request is forbidden.</p>
<p><b>Examples</b></p>
<p>Here is a useful <i>pre_connection</i> phase example: provide a facility to block remote clients by their IP, before too many resources were consumed. This is almost as good as a firewall blocking, as it's executed before Apache has started to do any work at all.</p>
<p><code>MyApache2::BlockIP2</code> retrieves client's remote IP and looks it up in the black list (which should certainly live outside the code, e.g. dbm file, but a hardcoded list is good enough for our example).</p>
<pre><code> #file:MyApache2/BlockIP2.pm
#-------------------------
package MyApache2::BlockIP2;
use strict;
use warnings;
use Apache2::Connection ();
use Apache2::Const -compile => qw(FORBIDDEN OK);
my %bad_ips = map {$_ => 1} qw(127.0.0.1 10.0.0.4);
sub handler {
my Apache2::Connection $c = shift;
my $ip = $c->remote_ip;
if (exists $bad_ips{$ip}) {
warn "IP $ip is blocked\n";
return Apache2::Const::FORBIDDEN;
}
return Apache2::Const::OK;
}
1;</code></pre>
<p>This all happens during the <i>pre_connection</i> phase:</p>
<pre><code> PerlPreConnectionHandler MyApache2::BlockIP2</code></pre>
<p>If a client connects from a blacklisted IP, Apache will simply abort the connection without sending any reply to the client, and move on to serving the next request.</p>
<h2 id="PerlProcessConnectionHandler">PerlProcessConnectionHandler</h2>
<p>The <i>process_connection</i> phase is used to process incoming connections. Only protocol modules should assign handlers for this phase, as it gives them an opportunity to replace the standard HTTP processing with processing for some other protocols (e.g., POP3, FTP, etc.).</p>
<p>This phase is of type <code><a>RUN_FIRST</a></code>.</p>
<p>The handler's configuration scope is <code><a>SRV</a></code>. Therefore the only way to run protocol servers different than the core HTTP is inside dedicated virtual hosts.</p>
<p><b>Arguments</b></p>
<p>A <i>process_connection</i> handler is passed a <code><a>connection record</a></code> object as its only argument.</p>
<p>A socket object can be retrieved from the connection record object.</p>
<p><b>Return</b></p>
<p>The handler should return <code><a>Apache2::Const::OK</a></code> if it completes successfully.</p>
<p><b>Examples</b></p>
<p>Here is a simplified handler skeleton:</p>
<pre><code> sub handler {
my ($c) = @_;
my $sock = $c->client_socket;
$sock->opt_set(APR::Const::SO_NONBLOCK, 0);
# ...
return Apache2::Const::OK;
}</code></pre>
<p>Most likely you'll need to set the socket to perform blocking IO. On some platforms (e.g. Linux) Apache gives us a socket which is set for blocking, on other platforms (.e.g. Solaris) it doesn't. Unless you know which platforms your application will be running on, always explicitly set it to the blocking IO mode as in the example above. Alternatively, you could query whether the socket is already set to a blocking IO mode with help of <code><a>the opt_get() method</a></code>.</p>
<p>Now let's look at the following two examples of connection handlers. The first using the connection socket to read and write the data and the second using <a>bucket brigades</a> to accomplish the same and allow for connection filters to do their work.</p>
<h3 id="Socket-based-Protocol-Module">Socket-based Protocol Module</h3>
<p>To demonstrate the workings of a protocol module, we'll take a look at the <code>MyApache2::EchoSocket</code> module, which simply echoes the data read back to the client. In this module we will use the implementation that works directly with the connection socket and therefore bypasses connection filters if any.</p>
<p>A protocol handler is configured using the <code>PerlProcessConnectionHandler</code> directive and we will use the <code>Listen</code> and <code><VirtualHost></code> directives to bind to the non-standard port <b>8010</b>:</p>
<pre><code> Listen 8010
<VirtualHost _default_:8010>
PerlModule MyApache2::EchoSocket
PerlProcessConnectionHandler MyApache2::EchoSocket
</VirtualHost></code></pre>
<p><code>MyApache2::EchoSocket</code> is then enabled when starting Apache:</p>
<pre><code> panic% httpd</code></pre>
<p>And we give it a whirl:</p>
<pre><code> panic% telnet localhost 8010
Trying 127.0.0.1...
Connected to localhost (127.0.0.1).
Escape character is '^]'.
Hello
Hello
fOo BaR
fOo BaR
Connection closed by foreign host.</code></pre>
<p>Here is the code:</p>
<pre><code> #file:MyApache2/EchoSocket.pm
#----------------------------
package MyApache2::EchoSocket;
use strict;
use warnings FATAL => 'all';
use Apache2::Connection ();
use APR::Socket ();
use Apache2::Const -compile => 'OK';
use APR::Const -compile => 'SO_NONBLOCK';
use constant BUFF_LEN => 1024;
sub handler {
my $c = shift;
my $sock = $c->client_socket;
# set the socket to the blocking mode
$sock->opt_set(APR::Const::SO_NONBLOCK => 0);
while ($sock->recv(my $buff, BUFF_LEN)) {
last if $buff =~ /^[\r\n]+$/;
$sock->send($buff);
}
Apache2::Const::OK;
}
1;</code></pre>
<p>The example handler starts with the standard <i>package</i> declaration and of course, <code>use strict;</code>. As with all <code>Perl*Handler</code>s, the subroutine name defaults to <i>handler</i>. However, in the case of a protocol handler, the first argument is not a <code>request_rec</code>, but a <code>conn_rec</code> blessed into the <code>Apache2::Connection</code> class. We have direct access to the client socket via <code>Apache2::Connection</code>'s <i>client_socket</i> method. This returns an object, blessed into the <code>APR::Socket</code> class. Before using the socket, we make sure that it's set to perform blocking IO, by using the <code>APR::Const::SO_NONBLOCK</code> constant, compiled earlier.</p>
<p>Inside the recv/send loop, the handler attempts to read <code>BUFF_LEN</code> bytes from the client socket into the <code>$buff</code> buffer. The handler breaks the loop if nothing was read (EOF) or if the buffer contains nothing but new line character(s), which is how we know to abort the connection in the interactive mode.</p>
<p>If the handler receives some data, it sends it unmodified back to the client with the <code>APR::Socket::send()</code> method. When the loop is finished the handler returns <code>Apache2::Const::OK</code>, telling Apache to terminate the connection. As mentioned earlier since this handler is working directly with the connection socket, no filters can be applied.</p>
<h3 id="Bucket-Brigades-based-Protocol-Module">Bucket Brigades-based Protocol Module</h3>
<p>Now let's look at the same module, but this time implemented by manipulating bucket brigades, and which runs its output through a connection output filter that turns all uppercase characters into their lowercase equivalents.</p>
<p>The following configuration defines a virtual host listening on port 8011 and which enables the <code>MyApache2::EchoBB</code> connection handler, which will run its output through <code>MyApache2::EchoBB::lowercase_filter</code> filter:</p>
<pre><code> Listen 8011
<VirtualHost _default_:8011>
PerlModule MyApache2::EchoBB
PerlProcessConnectionHandler MyApache2::EchoBB
PerlOutputFilterHandler MyApache2::EchoBB::lowercase_filter
</VirtualHost></code></pre>
<p>As before we start the httpd server:</p>
<pre><code> panic% httpd</code></pre>
<p>And try the new connection handler in action:</p>
<pre><code> panic% telnet localhost 8011
Trying 127.0.0.1...
Connected to localhost (127.0.0.1).
Escape character is '^]'.
Hello
hello
fOo BaR
foo bar
Connection closed by foreign host.</code></pre>
<p>As you can see the response part this time was all in lower case, because of the output filter.</p>
<p>And here is the implementation of the connection and the filter handlers.</p>
<pre><code> #file:MyApache2/EchoBB.pm
#------------------------
package MyApache2::EchoBB;
use strict;
use warnings FATAL => 'all';
use Apache2::Connection ();
use APR::Socket ();
use APR::Bucket ();
use APR::Brigade ();
use APR::Error ();
use APR::Status ();
use APR::Const -compile => qw(SUCCESS SO_NONBLOCK);
use Apache2::Const -compile => qw(OK MODE_GETLINE);
sub handler {
my $c = shift;
$c->client_socket->opt_set(APR::Const::SO_NONBLOCK => 0);
my $bb_in = APR::Brigade->new($c->pool, $c->bucket_alloc);
my $bb_out = APR::Brigade->new($c->pool, $c->bucket_alloc);
my $last = 0;
while (1) {
my $rc = $c->input_filters->get_brigade($bb_in,
Apache2::Const::MODE_GETLINE);
last if APR::Status::is_EOF($rc);
die APR::Error::strerror($rc) unless $rc == APR::Const::SUCCESS;
while (!$bb_in->is_empty) {
my $b = $bb_in->first;
$b->remove;
if ($b->is_eos) {
$bb_out->insert_tail($b);
last;
}
if ($b->read(my $data)) {
$last++ if $data =~ /^[\r\n]+$/;
# could do some transformation on data here
$b = APR::Bucket->new($bb_out->bucket_alloc, $data);
}
$bb_out->insert_tail($b);
}
my $fb = APR::Bucket::flush_create($c->bucket_alloc);
$bb_out->insert_tail($fb);
$c->output_filters->pass_brigade($bb_out);
last if $last;
}
$bb_in->destroy;
$bb_out->destroy;
Apache2::Const::OK;
}
use base qw(Apache2::Filter);
use constant BUFF_LEN => 1024;
sub lowercase_filter : FilterConnectionHandler {
my $filter = shift;
while ($filter->read(my $buffer, BUFF_LEN)) {
$filter->print(lc $buffer);
}
return Apache2::Const::OK;
}
1;</code></pre>
<p>For the purpose of explaining how this connection handler works, we are going to simplify the handler. The whole handler can be represented by the following pseudo-code:</p>
<pre><code> while ($bb_in = get_brigade()) {
while ($b_in = $bb_in->get_bucket()) {
$b_in->read(my $data);
# do something with data
$b_out = new_bucket($data);
$bb_out->insert_tail($b_out);
}
$bb_out->insert_tail($flush_bucket);
pass_brigade($bb_out);
}</code></pre>
<p>The handler receives the incoming data via bucket bridges, one at a time in a loop. It then process each bridge, by retrieving the buckets contained in it, reading the data in, then creating new buckets using the received data, and attaching them to the outgoing brigade. When all the buckets from the incoming bucket brigade were transformed and attached to the outgoing bucket brigade, a flush bucket is created and added as the last bucket, so when the outgoing bucket brigade is passed out to the outgoing connection filters, it won't be buffered but sent to the client right away.</p>
<p>It's possible to make the flushing code simpler, by using a dedicated method <code><a>fflush()</a></code> that does just that -- flushing of the bucket brigade. It replaces 3 lines of code:</p>
<pre><code> my $fb = APR::Bucket::flush_create($c->bucket_alloc);
$bb_out->insert_tail($fb);
$c->output_filters->pass_brigade($bb_out);</code></pre>
<p>with just one line:</p>
<pre><code> $c->output_filters->fflush($bb_out);</code></pre>
<p>If you look at the complete handler, the loop is terminated when one of the following conditions occurs: an error happens, the end of stream status code (<code>EOF</code>) has been received (no more input at the connection) or when the received data contains nothing but new line characters which we used to to tell the server to terminate the connection.</p>
<p>Now that you've learned how to move buckets from one brigade to another, let's see how the presented handler can be reimplemented using a single bucket brigade. Here is the modified code:</p>
<pre><code> sub handler {
my $c = shift;
$c->client_socket->opt_set(APR::Const::SO_NONBLOCK, 0);
my $bb = APR::Brigade->new($c->pool, $c->bucket_alloc);
while (1) {
my $rc = $c->input_filters->get_brigade($bb,
Apache2::Const::MODE_GETLINE);
last if APR::Status::is_EOF($rc);
die APR::Error::strerror($rc) unless $rc == APR::Const::SUCCESS;
for (my $b = $bb->first; $b; $b = $bb->next($b)) {
last if $b->is_eos;
if ($b->read(my $data)) {
last if $data =~ /^[\r\n]+$/;
my $nb = APR::Bucket->new($bb->bucket_alloc, $data);
# head->...->$nb->$b ->...->tail
$b->insert_before($nb);
$b->remove;
}
}
$c->output_filters->fflush($bb);
}
$bb->destroy;
Apache2::Const::OK;
}</code></pre>
<p>This code is shorter and simpler. Since it sends out the same bucket brigade it got from the incoming filters, it only needs to replace buckets that get modified, which is probably the only tricky part here. The code:</p>
<pre><code> # head->...->$nb->$b ->...->tail
$b->insert_before($nb);
$b->remove;</code></pre>
<p>inserts a new bucket in front of the currently processed bucket, so that when the latter removed the former takes place of the latter.</p>
<p>Notice that this handler could be much simpler, since we don't modify the data. We could simply pass the whole brigade unmodified without even looking at the buckets. But from this example you can see how to write a connection handler where you actually want to read and/or modify the data. To accomplish that modification simply add a code that transforms the data which has been read from the bucket before it's inserted to the outgoing brigade.</p>
<p>We will skip the filter discussion here, since we are going to talk in depth about filters in <a>the dedicated to filters tutorial</a>. But all you need to know at this stage is that the data sent from the connection handler is filtered by the outgoing filter and which transforms it to be all lowercase.</p>
<p>And here is the simplified version of this handler, which doesn't attempt to do any transformation, but simply passes the data though:</p>
<pre><code> sub handler {
my $c = shift;
$c->client_socket->opt_set(APR::Const::SO_NONBLOCK => 0);
my $bb = APR::Brigade->new($c->pool, $c->bucket_alloc);
while (1) {
my $rc = $c->input_filters->get_brigade($bb,
Apache2::Const::MODE_GETLINE);
last if APR::Status::is_EOF($rc);
die APR::Error::strerror($rc) unless $rc == APR::Const::SUCCESS;
$c->output_filters->fflush($bb);
}
$bb->destroy;
Apache2::Const::OK;
}</code></pre>
<p>Since the simplified handler no longer has the condition:</p>
<pre><code> $last++ if $data =~ /^[\r\n]+$/;</code></pre>
<p>which was used to know when to break from the external <code>while(1)</code> loop, it will not work in the interactive mode, because when telnet is used we always end the line with <code>/[\r\n]/</code>, which will always send data back to the protocol handler and the condition:</p>
<pre><code> last if $bb->is_empty;</code></pre>
<p>will never be true. However, this latter version works fine when the client is a script and when it stops sending data, our shorter handler breaks out of the loop.</p>
<p>So let's do one more tweak and make the last version work in the interactive telnet mode without manipulating each bucket separately. This time we will use <code><a>flatten()</a></code> to slurp all the data from all the buckets, which saves us the explicit loop over the buckets in the brigade. The handler now becomes:</p>
<pre><code> sub handler {
my $c = shift;
$c->client_socket->opt_set(APR::Const::SO_NONBLOCK => 0);
my $bb = APR::Brigade->new($c->pool, $c->bucket_alloc);
while (1) {
my $rc = $c->input_filters->get_brigade($bb,
Apache2::Const::MODE_GETLINE);
last if APR::Status::is_EOF($rc);
die APR::Error::strerror($rc) unless $rc == APR::Const::SUCCESS;
next unless $bb->flatten(my $data);
$bb->cleanup;
last if $data =~ /^[\r\n]+$/;
# could transform data here
my $b = APR::Bucket->new($bb->bucket_alloc, $data);
$bb->insert_tail($b);
$c->output_filters->fflush($bb);
}
$bb->destroy;
Apache2::Const::OK;
}</code></pre>
<p>Notice, that once we slurped the data in the buckets, we had to strip the brigade of its buckets, since we re-used the same brigade to send the data out. We used <code><a>cleanup()</a></code> to get rid of the buckets.</p>
<h1 id="Examples">Examples</h1>
<p>Following are some practical examples.</p>
<p>META: If you have written an interesting, but not too complicated module, which others can learn from, please submit a pod to the <a>mailing list</a> so we can include it here.</p>
<h2 id="Command-Server">Command Server</h2>
<p>The <code>MyApache2::CommandServer</code> example is based on the example in the "TCP Servers with IO::Socket" section of the <i>perlipc</i> manpage. Of course, we don't need <code>IO::Socket</code> since Apache takes care of those details for us. The rest of that example can still be used to illustrate implementing a simple text protocol. In this case, one where a command is sent by the client to be executed on the server side, with results sent back to the client.</p>
<p>The <code>MyApache2::CommandServer</code> handler will support four commands: <code>motd</code>, <code>date</code>, <code>who</code> and <code>quit</code>. These are probably not commands which can be exploited, but should we add such commands, we'll want to limit access based on ip address/hostname, authentication and authorization. Protocol handlers need to take care of these tasks themselves, since we bypass the HTTP protocol handler.</p>
<p>Here is the whole module:</p>
<pre><code> package MyApache2::CommandServer;
use strict;
use warnings FATAL => 'all';
use Apache2::Connection ();
use Apache2::RequestRec ();
use Apache2::RequestUtil ();
use Apache2::HookRun ();
use Apache2::Access ();
use APR::Socket ();
use Apache2::Const -compile => qw(OK DONE DECLINED);
my @cmds = qw(motd date who quit);
my %commands = map { $_, \&{$_} } @cmds;
sub handler {
my $c = shift;
my $socket = $c->client_socket;
if ((my $rc = login($c)) != Apache2::Const::OK) {
$socket->send("Access Denied\n");
return $rc;
}
$socket->send("Welcome to " . __PACKAGE__ .
"\nAvailable commands: @cmds\n");
while (1) {
my $cmd;
next unless $cmd = getline($socket);
if (my $sub = $commands{$cmd}) {
last unless $sub->($socket) == Apache2::Const::OK;
}
else {
$socket->send("Commands: @cmds\n");
}
}
return Apache2::Const::OK;
}
sub login {
my $c = shift;
my $r = Apache2::RequestRec->new($c);
$r->location_merge(__PACKAGE__);
for my $method (qw(run_access_checker run_check_user_id
run_auth_checker)) {
my $rc = $r->$method();
if ($rc != Apache2::Const::OK and $rc != Apache2::Const::DECLINED) {
return $rc;
}
last unless $r->some_auth_required;
unless ($r->user) {
my $socket = $c->client_socket;
my $username = prompt($socket, "Login");
my $password = prompt($socket, "Password");
$r->set_basic_credentials($username, $password);
}
}
return Apache2::Const::OK;
}
sub getline {
my $socket = shift;
my $line;
$socket->recv($line, 1024);
return unless $line;
$line =~ s/[\r\n]*$//;
return $line;
}
sub prompt {
my ($socket, $msg) = @_;
$socket->send("$msg: ");
getline($socket);
}
sub motd {
my $socket = shift;
open my $fh, '/etc/motd' or return;
local $/;
$socket->send(scalar <$fh>);
close $fh;
return Apache2::Const::OK;
}
sub date {
my $socket = shift;
$socket->send(scalar(localtime) . "\n");
return Apache2::Const::OK;
}
sub who {
my $socket = shift;
# make -T happy
local $ENV{PATH} = "/bin:/usr/bin";
$socket->send(scalar `who`);
return Apache2::Const::OK;
}
sub quit { Apache2::Const::DONE }
1;
__END__</code></pre>
<p>Next, let's explain what this module does in details.</p>
<p>As with all <code>PerlProcessConnectionHandlers</code>, we are passed an <code>Apache2::Connection</code> object as the first argument. Again, we will be directly accessing the client socket via the <i>client_socket</i> method. The <i>login</i> subroutine is called to check if access by this client should be allowed. This routine makes up for what we lost with the core HTTP protocol handler bypassed.</p>
<p>First we call the <code>Apache2::RequestRec</code> <code>new()</code> method, which returns a <i>request_rec</i> object, just like that, which is passed at request time to <a>HTTP protocol</a> <code>Perl*Handlers</code> and returned by the subrequest API methods, <i>lookup_uri</i> and <i>lookup_file</i>. However, this "fake request" does not run handlers for any of the phases, it simply returns an object which we can use to do that ourselves.</p>
<p>The <code>location_merge()</code> method is passed the <code>location</code> for this request, it will look up the <code><Location></code> section that matches the given name and merge it with the default server configuration. For example, should we only wish to allow access to this server from certain locations:</p>
<pre><code> <Location MyApache2::CommandServer>
Order Deny,Allow
Deny from all
Allow from 10.*
</Location></code></pre>
<p>The <code>location_merge()</code> method only looks up and merges the configuration, we still need to apply it. This is done in <i>for</i> loop, iterating over three methods: <code>run_access_checker()</code>, <code>run_check_user_id()</code> and <code>run_auth_checker()</code>. These methods will call directly into the Apache functions that invoke module handlers for these phases and will return an integer status code, such as <code>Apache2::Const::OK</code>, <code>Apache2::Const::DECLINED</code> or <code>Apache2::Const::FORBIDDEN</code>. If <i>run_access_check</i> returns something other than <code>Apache2::Const::OK</code> or <code>Apache2::Const::DECLINED</code>, that status will be propagated up to the handler routine and then back up to Apache. Otherwise, the access check passed and the loop will break unless <code>some_auth_required()</code> returns true. This would be false given the previous configuration example, but would be true in the presence of a <code>require</code> directive, such as:</p>
<pre><code> <Location MyApache2::CommandServer>
Order Deny,Allow
Deny from all
Allow from 10.*
Require user dougm
</Location></code></pre>
<p>Given this configuration, <code>some_auth_required()</code> will return true. The <code>user()</code> method is then called, which will return false if we have not yet authenticated. A <code>prompt()</code> utility is called to read the username and password, which are then injected into the <code>headers_in()</code> table using the <code>set_basic_credentials()</code> method. The <i>Authenticate</i> field in this table is set to a <i>base64</i> encoded value of the username:password pair, exactly the same format a browser would send for <i>Basic authentication</i>. Next time through the loop <i>run_check_user_id</i> is called, which will in turn invoke any authentication handlers, such as <i>mod_auth</i>. When <i>mod_auth</i> calls the <code>ap_get_basic_auth_pw()</code> API function (as all <code>Basic</code> auth modules do), it will get back the username and password we injected. If we fail authentication a <code>401</code> status code is returned which we propagate up. Otherwise, authorization handlers are run via <code>run_auth_checker()</code>. Authorization handlers normally need the <i>user</i> field of the <code>request_rec</code> for its checks and that field was filled in when <i>mod_auth</i> called <code>ap_get_basic_auth_pw()</code>.</p>
<p>Provided login is a success, a welcome message is printed and main request loop entered. Inside the loop the <code>getline()</code> function returns just one line of data, with newline characters stripped. If the string sent by the client is in our command table, the command is then invoked, otherwise a usage message is sent. If the command does not return <code>Apache2::Const::OK</code>, we break out of the loop.</p>
<p>Let's use this configuration:</p>
<pre><code> Listen 8085
<VirtualHost _default_:8085>
PerlProcessConnectionHandler MyApache2::CommandServer
<Location MyApache2::CommandServer>
Order Deny,Allow
Allow from 127.0.0.1
Require user dougm
Satisfy any
AuthUserFile /tmp/basic-auth
</Location>
</VirtualHost></code></pre>
<p>Since we are using <code>mod_auth</code> directives here, you need to make sure that it's available and loaded for this example to work as explained.</p>
<p>The auth file can be created with the help of <code>htpasswd</code> utility coming bundled with the Apache server. For example to create a file <i>/tmp/basic-auth</i> and add a password entry for user <i>dougm</i> with password <i>foobar</i> we do:</p>
<pre><code> % htpasswd -bc /tmp/basic-auth dougm foobar</code></pre>
<p>Now we are ready to try the command server:</p>
<pre><code> % telnet localhost 8085
Trying 127.0.0.1...
Connected to localhost (127.0.0.1).
Escape character is '^]'.
Login: dougm
Password: foobar
Welcome to MyApache2::CommandServer
Available commands: motd date who quit
motd
Have a lot of fun...
date
Mon Mar 12 19:20:10 PST 2001
who
dougm tty1 Mar 12 00:49
dougm pts/0 Mar 12 11:23
dougm pts/1 Mar 12 14:08
dougm pts/2 Mar 12 17:09
quit
Connection closed by foreign host.</code></pre>
<h1 id="CPAN-Modules">CPAN Modules</h1>
<p>Some of the CPAN modules that implement mod_perl 2.0 protocols:</p>
<dl>
<dt id="Apache::SMTP---An-SMTP-server"><code>Apache::SMTP</code> - An SMTP server</dt>
<dd>
<p>http://search.cpan.org/dist/Apache-SMTP/</p>
</dd>
</dl>
<h1 id="Maintainers">Maintainers</h1>
<p>Maintainer is the person(s) you should contact with updates, corrections and patches.</p>
<ul>
<li><p>Stas Bekman [http://stason.org/]</p>
</li>
</ul>
<h1 id="Authors">Authors</h1>
<ul>
<li><p></p>
</li>
</ul>
<p>Only the major authors are listed above. For contributors see the Changes file.</p>
</body>
</html>
|