File: http.pod

package info (click to toggle)
libapache2-mod-perl2 2.0.13-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 12,016 kB
  • sloc: perl: 97,771; ansic: 14,493; makefile: 51; sh: 18
file content (2137 lines) | stat: -rw-r--r-- 66,120 bytes parent folder | download | duplicates (8)
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
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
=head1 NAME

HTTP Handlers

=head1 Description

This chapter explains how to implement the HTTP protocol handlers in
mod_perl.


=head1 HTTP Request Handler Skeleton

All HTTP Request handlers have the following structure:

  package MyApache2::MyHandlerName;

  # load modules that are going to be used
  use ...;

  # compile (or import) constants
  use Apache2::Const -compile => qw(OK);

  sub handler {
      my $r = shift;
      
      # handler code comes here
      
      return Apache2::Const::OK; # or another status constant
  }
  1;

First, the package is declared. Next, the modules that are going to be
used are loaded and constants compiled.

The handler itself coming next and usually it receives the only
argument: the
C<L<Apache2::RequestRec|docs::2.0::api::Apache2::RequestRec>> object.
If the handler is declared as L<a method handler
|docs::2.0::user::coding::coding/Method_Handlers>:

  sub handler : method {
      my ($class, $r) = @_;

the handler receives two arguments: the class name and the
C<L<Apache2::RequestRec|docs::2.0::api::Apache2::RequestRec>> object.

The handler ends with L<a return
code|docs::2.0::user::handlers::intro/Stacked_Handlers> and the file
is ended with C<1;> to return true when it gets loaded.






=head1 HTTP Request Cycle Phases

Those familiar with mod_perl 1.0 will find the HTTP request cycle in
mod_perl 2.0 to be almost identical to the mod_perl 1.0's model. The
different things are:

=over

=item *

a new directive C<L<PerlMapToStorageHandler|/PerlMapToStorageHandler>>
was added to match the new phase I<map_to_storage> added by Apache
2.0.

=item *

the C<PerlHandler> directive has been renamed to
C<PerlResponseHandler> to better match the corresponding Apache phase
name (I<response>).

=item *

the I<response> phase now includes filtering.

=back

The following diagram depicts the HTTP request life cycle and
highlights which handlers are available to mod_perl 2.0:

=for html
<img src="http_cycle.gif" width="600" height="560" 
 align="middle" alt="HTTP cycle"><br><br>

From the diagram it can be seen that an HTTP request is processed by
12 phases, executed in the following order:

=over

=item 1 PerlPostReadRequestHandler (PerlInitHandler)

=item 2 PerlTransHandler

=item 3 PerlMapToStorageHandler

=item 4 PerlHeaderParserHandler (PerlInitHandler)

=item 5 PerlAccessHandler

=item 6 PerlAuthenHandler

=item 7 PerlAuthzHandler

=item 8 PerlTypeHandler

=item 9 PerlFixupHandler

=item 10 PerlResponseHandler

=item 11 PerlLogHandler

=item 12 PerlCleanupHandler

=back

It's possible that the cycle will not be completed if any of the
phases terminates it, usually when an error happens. In that case
Apache skips to the logging phase (mod_perl executes all registered
C<PerlLogHandler> handlers) and finally the cleanup phase happens.

Notice that when the response handler is reading the input data it can
be filtered through request input filters, which are preceded by
connection input filters if any. Similarly the generated response is
first run through request output filters and eventually through
connection output filters before it's sent to the client. We will talk
about filters in detail later in L<the dedicated to filters
chapter|docs::2.0::user::handlers::filters>.

Before discussing each handler in detail remember that if you use
L<the stacked handlers
feature|docs::2.0::user::handlers::intro/Stacked_Handlers> all
handlers in the chain will be run as long as they return C<Apache2::Const::OK>
or C<Apache2::Const::DECLINED>. Because stacked handlers is a special case. So
don't be surprised if you've returned C<Apache2::Const::OK> and the next
handler was still executed. This is a feature, not a bug.

Now let's discuss each of the mentioned handlers in detail.













=head2 PerlPostReadRequestHandler

The I<post_read_request> phase is the first request phase and happens
immediately after the request has been read and HTTP headers were
parsed.

This phase is usually used to do processing that must happen once per
request. For example C<Apache2::Reload> is usually invoked at this
phase to reload modified Perl modules.

This phase is of type
C<L<RUN_ALL|docs::2.0::user::handlers::intro/item_RUN_ALL>>.

The handler's configuration scope is
C<L<SRV|docs::2.0::user::config::config/item_SRV>>, because at this
phase the request has not yet been associated with a particular
filename or directory.

B<Arguments>

See the L<HTTP Request Handler Skeleton|docs::2.0::user::handlers::http/HTTP_Request_Handler_Skeleton> for a description of handler arguments.

B<Return>

See L<Stacked Handlers|docs::2.0::user::handlers::intro/Stacked_Handlers> 
for a description of handler return codes.

B<Examples>

Now, let's look at an example. Consider the following registry script:

  #file:touch.pl
  #-------------
  use strict;
  use warnings;
  
  use Apache2::ServerUtil ();
  use Apache2::RequestIO ();
  use File::Spec::Functions qw(catfile);
  
  my $r = shift;
  $r->content_type('text/plain');
  
  my $conf_file = catfile Apache2::ServerUtil::server_root,
    "conf", "httpd.conf";
  
  printf "$conf_file is %0.2f minutes old\n", 60*24*(-M $conf_file);

This registry script is supposed to print when the last time
I<httpd.conf> has been modified, compared to the start of the request
process time. If you run this script several times you might be
surprised that it reports the same value all the time. Unless the
request happens to be served by a recently started child process which
will then report a different value. But most of the time the value
won't be reported correctly.

This happens because the C<-M> operator reports the difference between
file's modification time and the value of a special Perl variable
C<$^T>. When we run scripts from the command line, this variable is
always set to the time when the script gets invoked. Under mod_perl
this variable is getting preset once when the child process starts and
doesn't change since then, so all requests see the same time, when
operators like C<-M>, C<-C> and C<-A> are used.

Armed with this knowledge, in order to make our code behave similarly
to the command line programs we need to reset C<$^T> to the request's
start time, before C<-M> is used. We can change the script itself, but
what if we need to do the same change for several other scripts and
handlers? A simple C<PerlPostReadRequestHandler> handler, which will
be executed as the very first thing of each requests, comes handy
here:

  #file:MyApache2/TimeReset.pm
  #--------------------------
  package MyApache2::TimeReset;
  
  use strict;
  use warnings;
  
  use Apache2::RequestRec ();
  
  use Apache2::Const -compile => 'OK';
  
  sub handler {
      my $r = shift;
      $^T = $r->request_time;
      return Apache2::Const::OK;
  }
  1;

We could do:

  $^T = time();

But to make things more efficient we use C<$r-E<gt>request_time> since
the request object C<$r> already stores the request's start time, so
we get it without performing an additional system call.

To enable it just add to I<httpd.conf>:

  PerlPostReadRequestHandler MyApache2::TimeReset

either to the global section, or to the C<E<lt>VirtualHostE<gt>>
section if you want this handler to be run only for a specific virtual
host.






=head2 PerlTransHandler

The I<translate> phase is used to perform the manipulation of a
request's URI. If no custom handler is provided, the server's standard
translation rules (e.g., C<Alias> directives, mod_rewrite, etc.) will
be used. A C<PerlTransHandler> handler can alter the default
translation mechanism or completely override it. This is also a good
place to register new handlers for the following phases based on the
URI. C<L<PerlMapToStorageHandler|/PerlMapToStorageHandler>> is to be
used to override the URI to filename translation.

This phase is of type
C<L<RUN_FIRST|docs::2.0::user::handlers::intro/item_RUN_FIRST>>.

The handler's configuration scope is
C<L<SRV|docs::2.0::user::config::config/item_SRV>>, because at this
phase the request has not yet been associated with a particular
filename or directory.

B<Arguments>

See the L<HTTP Request Handler Skeleton|docs::2.0::user::handlers::http/HTTP_Request_Handler_Skeleton> for a description of handler arguments.

B<Return>

See L<Stacked Handlers|docs::2.0::user::handlers::intro/Stacked_Handlers> 
for a description of handler return codes.

B<Examples>

There are many useful things that can be performed at this
stage. Let's look at the example handler that rewrites request URIs,
similar to what mod_rewrite does. For example, if your web-site was
originally made of static pages, and now you have moved to a dynamic
page generation chances are that you don't want to change the old
URIs, because you don't want to break links for those who link to your
site. If the URI:

  http://example.com/news/20021031/09/index.html

is now handled by:

  http://example.com/perl/news.pl?date=20021031;id=09;page=index.html

the following handler can do the rewriting work transparent to
I<news.pl>, so you can still use the former URI mapping:

  #file:MyApache2/RewriteURI.pm
  #---------------------------
  package MyApache2::RewriteURI;
  
  use strict;
  use warnings;
  
  use Apache2::RequestRec ();
  
  use Apache2::Const -compile => qw(DECLINED);
  
  sub handler {
      my $r = shift;
  
      my ($date, $id, $page) = $r->uri =~ m|^/news/(\d+)/(\d+)/(.*)|;
      $r->uri("/perl/news.pl");
      $r->args("date=$date;id=$id;page=$page");
  
      return Apache2::Const::DECLINED;
  }
  1;

The handler matches the URI and assigns a new URI via C<$r-E<gt>uri()>
and the query string via C<$r-E<gt>args()>. It then returns
C<Apache2::Const::DECLINED>, so the next translation handler will get
invoked, if more rewrites and translations are needed.

Of course if you need to do a more complicated rewriting, this handler
can be easily adjusted to do so.

To configure this module simply add to I<httpd.conf>:

  PerlTransHandler +MyApache2::RewriteURI






=head2 PerlMapToStorageHandler

The I<map_to_storage> phase is used to perform the translation of a
request's URI into a corresponding filename. If no custom handler is
provided, the server will try to walk the filesystem trying to find
what file or directory corresponds to the request's URI. Since usually
mod_perl handler don't have corresponding files on the filesystem, you
will want to shortcut this phase and save quite a few CPU cycles.

This phase is of type
C<L<RUN_FIRST|docs::2.0::user::handlers::intro/item_RUN_FIRST>>.

The handler's configuration scope is
C<L<SRV|docs::2.0::user::config::config/item_SRV>>, because at this
phase the request has not yet been associated with a particular
filename or directory.

B<Arguments>

See the L<HTTP Request Handler Skeleton|docs::2.0::user::handlers::http/HTTP_Request_Handler_Skeleton> for a description of handler arguments.

B<Return>

See L<Stacked Handlers|docs::2.0::user::handlers::intro/Stacked_Handlers> 
for a description of handler return codes.

B<Examples>

For example if you don't want Apache to try to attempt to translate
URI into a filename, just add a handler:

  PerlMapToStorageHandler MyApache2::NoTranslation

using the following code:

  #file:MyApache2/NoTranslation.pm
  #------------------------------
  package MyApache2::NoTranslation;
  
  use strict;
  use warnings FATAL => 'all';
  
  use Apache2::Const -compile => qw(OK);
  
  sub handler {
      my $r = shift;
  
      # skip ap_directory_walk stat() calls
      return Apache2::Const::OK;
  }
  1;

But this can be done from F<httpd.conf> too!

  PerlMapToStorageHandler Apache2::Const::OK

If you haven't already compiled C<Apache2::Const::OK> elsewhere, you
should add:

  <Perl>
      use Apache2::Const -compile => qw(OK);
  </Perl>

Apache also uses this phase to handle C<TRACE> requests. So if you
shortcut it, C<TRACE> calls will be not handled. In case you need to
handle such, you may rewrite it as:

  #file:MyApache2/NoTranslation2.pm
  #-------------------------------
  package MyApache2::NoTranslation2;
  
  use strict;
  use warnings FATAL => 'all';
  
  use Apache2::RequestRec ();

  use Apache2::Const -compile => qw(DECLINED OK M_TRACE);
  
  sub handler {
      my $r = shift;
  
      return Apache2::Const::DECLINED
          if $r->method_number == Apache2::Const::M_TRACE;
  
      # skip ap_directory_walk stat() calls
      return Apache2::Const::OK;
  }
  1;

BTW, the HTTP TRACE method asks a web server to echo the contents of
the request back to the client for debugging purposes. i.e., the
complete request, including HTTP headers, is returned in the
entity-body of a TRACE response. Attackers may abuse HTTP TRACE
functionality to gain access to information in HTTP headers such as
cookies and authentication data. In the presence of other cross-domain
vulnerabilities in web browsers, sensitive header information could be
read from any domains that support the HTTP TRACE method.

Another way to prevent the core translation is to set
C<$r-E<gt>filename()> to some value, which can also be done in the
C<L<PerlTransHandler|/PerlTransHandler>>, if you are already using it.








=head2 PerlHeaderParserHandler

The I<header_parser> phase is the first phase to happen after the
request has been mapped to its C<E<lt>LocationE<gt>> (or an equivalent
container). At this phase the handler can examine the request headers
and to take a special action based on these. For example this phase
can be used to block evil clients targeting certain resources, while
little resources were wasted so far.

This phase is of type
C<L<RUN_ALL|docs::2.0::user::handlers::intro/item_RUN_ALL>>.

The handler's configuration scope is
C<L<DIR|docs::2.0::user::config::config/item_DIR>>.

B<Arguments>

See the L<HTTP Request Handler Skeleton|docs::2.0::user::handlers::http/HTTP_Request_Handler_Skeleton> for a description of handler arguments.

B<Return>

See L<Stacked Handlers|docs::2.0::user::handlers::intro/Stacked_Handlers> 
for a description of handler return codes.

B<Examples>

This phase is very similar to
C<L<PerlPostReadRequestHandler|/PerlPostReadRequestHandler>>, with the
only difference that it's run after the request has been mapped to the
resource. Both phases are useful for doing something once per request,
as early as possible. And usually you can take any
C<L<PerlPostReadRequestHandler|/PerlPostReadRequestHandler>> and turn
it into C<L<PerlHeaderParserHandler|/PerlHeaderParserHandler>> by
simply changing the directive name in I<httpd.conf> and moving it
inside the container where it should be executed. Moreover, because of
this similarity mod_perl provides a special directive
C<L<PerlInitHandler|/PerlInitHandler>> which if found outside resource
containers behaves as
C<L<PerlPostReadRequestHandler|/PerlPostReadRequestHandler>>,
otherwise as C<L<PerlHeaderParserHandler|/PerlHeaderParserHandler>>.

You already know that Apache handles the C<HEAD>, C<GET>, C<POST> and
several other HTTP methods. But did you know that you can invent your
own HTTP method as long as there is a client that supports it. If you
think of emails, they are very similar to HTTP messages: they have a
set of headers and a body, sometimes a multi-part body. Therefore we
can develop a handler that extends HTTP by adding a support for the
C<EMAIL> method.  We can enable this protocol extension and push the
real content handler during the
C<L<PerlHeaderParserHandler|/PerlHeaderParserHandler>> phase:

  <Location /email>
      PerlHeaderParserHandler MyApache2::SendEmail
  </Location>

and here is the C<MyApache2::SendEmail> handler:

  #file:MyApache2/SendEmail.pm
  #--------------------------
  package MyApache2::SendEmail;
  
  use strict;
  use warnings;
  
  use Apache2::RequestRec ();
  use Apache2::RequestIO ();
  use Apache2::RequestUtil ();
  use Apache2::ServerUtil ();
  use Apache2::ServerRec ();
  use Apache2::Process ();
  use APR::Table ();
  
  use Apache2::Const -compile => qw(DECLINED OK);
  
  use constant METHOD        => 'EMAIL';
  use constant SMTP_HOSTNAME => "localhost";
  
  sub handler {
      my $r = shift;
  
      return Apache2::Const::DECLINED unless $r->method eq METHOD;
  
      $r->server->method_register(METHOD);
      $r->handler("perl-script");
      $r->push_handlers(PerlResponseHandler => \&send_email_handler);
  
      return Apache2::Const::OK;
  }
  
  sub send_email_handler {
      my $r = shift;
  
      my %headers = map {$_ => $r->headers_in->get($_)} 
		qw(To From Subject);
      
	  my $content = content($r);
  
      my $status = send_email(\%headers, \$content);
  
      $r->content_type('text/plain');
      $r->print($status ? "ACK" : "NACK");
      return Apache2::Const::OK;
  }
  
  sub send_email {
      my ($rh_headers, $r_body) = @_;
  
      require MIME::Lite;
      MIME::Lite->send("smtp", SMTP_HOSTNAME, Timeout => 60);
  
      my $msg = MIME::Lite->new(%$rh_headers, Data => $$r_body);
      #warn $msg->as_string;
      $msg->send;
  }
  
  use APR::Brigade ();
  use APR::Bucket ();
  
  use Apache2::Const -compile => qw(MODE_READBYTES);
  use APR::Const    -compile => qw(SUCCESS BLOCK_READ);
  
  use constant IOBUFSIZE => 8192;
  
  sub content {
      my $r = shift;
  
      my $bb = APR::Brigade->new($r->pool, $r->connection->bucket_alloc);
  
      my $data = '';
      my $seen_eos = 0;
      do {
          $r->input_filters->get_brigade($bb, 
			  Apache2::Const::MODE_READBYTES,
              APR::Const::BLOCK_READ, IOBUFSIZE);
  
          for (my $b = $bb->first; $b; $b = $bb->next($b)) {
              if ($b->is_eos) {
                  $seen_eos++;
                  last;
              }
  
              if ($b->read(my $buf)) {
                  $data .= $buf;
              }
  
              $b->remove; # optimization to reuse memory
          }
      } while (!$seen_eos);
  
      $bb->destroy;
  
      return $data;
  }
  
  1;

Let's get the less interesting code out of the way. The function
content() grabs the request body. The function send_email() sends the
email over SMTP. You should adjust the constant C<SMTP_HOSTNAME> to
point to your outgoing SMTP server. You can replace this function with
your own if you prefer to use a different method to send email.

Now to the more interesting functions. The function C<handler()>
returns immediately and passes the control to the next handler if the
request method is not equal to C<EMAIL> (set in the C<METHOD>
constant):

      return Apache2::Const::DECLINED unless $r->method eq METHOD;

Next it tells Apache that this new method is a valid one and that the
C<perl-script> handler will do the processing.

      $r->server->method_register(METHOD);
      $r->handler("perl-script");

Finally it pushes the function C<send_email_handler()> to the
C<PerlResponseHandler> list of handlers:

      $r->push_handlers(PerlResponseHandler => \&send_email_handler);

The function terminates the header_parser phase by:

      return Apache2::Const::OK;

All other phases run as usual, so you can reuse any HTTP protocol
hooks, such as authentication and fixup phases. 

When the response phase starts C<send_email_handler()> is invoked,
assuming that no other response handlers were inserted before it.  The
response handler consists of three parts. Retrieve the email headers
C<To>, C<From> and C<Subject>, and the body of the message:

      my %headers = map {$_ => $r->headers_in->get($_)} 
	    qw(To From Subject);
      my $content = $r->content;

Then send the email:

      my $status = send_email(\%headers, \$content);

Finally return to the client a simple response acknowledging that
email has been sent and finish the response phase by returning
C<Apache2::Const::OK>:

      $r->content_type('text/plain');
      $r->print($status ? "ACK" : "NACK");
      return Apache2::Const::OK;

Of course you will want to add extra validations if you want to use
this code in production. This is just a proof of concept
implementation.

As already mentioned when you extend an HTTP protocol you need to have
a client that knows how to use the extension. So here is a simple
client that uses C<LWP::UserAgent> to issue an C<EMAIL> method request
over HTTP protocol:

  #file:send_http_email.pl
  #-----------------------
  #!/usr/bin/perl
  
  use strict;
  use warnings;
  
  require LWP::UserAgent;
  
  my $url = "http://localhost:8000/email/";
  
  my %headers = (
      From    => 'example@example.com',
      To      => 'example@example.com',
      Subject => '3 weeks in Tibet',
  );
  
  my $content = <<EOI;
  I didn't have an email software,
  but could use HTTP so I'm sending it over HTTP
  EOI
  
  my $headers = HTTP::Headers->new(%headers);
  my $req = HTTP::Request->new("EMAIL", $url, $headers, $content);
  my $res = LWP::UserAgent->new->request($req);
  print $res->is_success ? $res->content : "failed";

most of the code is just a custom data. The code that does something
consists of four lines at the very end. Create C<HTTP::Headers> and
C<HTTP::Request> object. Issue the request and get the
response. Finally print the response's content if it was successful or
just I<"failed"> if not.

Now save the client code in the file I<send_http_email.pl>, adjust the
I<To> field, make the file executable and execute it, after you have
restarted the server. You should receive an email shortly to the
address set in the I<To> field.





=head2 PerlInitHandler

When configured inside any container directive, except
C<E<lt>VirtualHostE<gt>>, this handler is an alias for
C<L<PerlHeaderParserHandler|/PerlHeaderParserHandler>> described
earlier.  Otherwise it acts as an alias for
C<L<PerlPostReadRequestHandler|/PerlPostReadRequestHandler>> described
earlier.

It is the first handler to be invoked when serving a request.

This phase is of type
C<L<RUN_ALL|docs::2.0::user::handlers::intro/item_RUN_ALL>>.

B<Arguments>

See the L<HTTP Request Handler Skeleton|docs::2.0::user::handlers::http/HTTP_Request_Handler_Skeleton> for a description of handler arguments.

B<Return>

See L<Stacked Handlers|docs::2.0::user::handlers::intro/Stacked_Handlers> 
for a description of handler return codes.

B<Examples>

The best example here would be to use
C<L<Apache2::Reload|docs::2.0::api::Apache2::Reload>> which takes the
benefit of this directive. Usually
C<L<Apache2::Reload|docs::2.0::api::Apache2::Reload>> is configured
as:

  PerlInitHandler Apache2::Reload
  PerlSetVar ReloadAll Off
  PerlSetVar ReloadModules "MyApache2::*"

which during the current HTTP request will monitor and reload all
C<MyApache2::*> modules that have been modified since the last HTTP
request. However if we move the global configuration into a
C<E<lt>LocationE<gt>> container:

  <Location /devel>
      PerlInitHandler Apache2::Reload
      PerlSetVar ReloadAll Off
      PerlSetVar ReloadModules "MyApache2::*"
      SetHandler perl-script
      PerlResponseHandler ModPerl::Registry
      Options +ExecCGI
  </Location>

C<L<Apache2::Reload|docs::2.0::api::Apache2::Reload>> will reload the
modified modules, only when a request to the I</devel> namespace is
issued, because C<L<PerlInitHandler|/PerlInitHandler>> plays the role
of C<L<PerlHeaderParserHandler|/PerlHeaderParserHandler>> here.





=head2 PerlAccessHandler

The I<access_checker> phase is the first of three handlers that are
involved in what's known as AAA: Authentication, Authorization, and
Access control.

This phase can be used to restrict access from a certain IP address,
time of the day or any other rule not connected to the user's
identity.

This phase is of type
C<L<RUN_ALL|docs::2.0::user::handlers::intro/item_RUN_ALL>>.

The handler's configuration scope is
C<L<DIR|docs::2.0::user::config::config/item_DIR>>.

B<Arguments>

See the L<HTTP Request Handler Skeleton|docs::2.0::user::handlers::http/HTTP_Request_Handler_Skeleton> for a description of handler arguments.

B<Return>

See L<Stacked Handlers|docs::2.0::user::handlers::intro/Stacked_Handlers> 
for a description of handler return codes.

B<Examples>

The concept behind access checker handler is very simple, return
C<Apache2::Const::FORBIDDEN> if the access is not allowed, otherwise
return C<Apache2::Const::OK>.

The following example handler denies requests made from IPs on the
blacklist.


  #file:MyApache2/BlockByIP.pm
  #--------------------------
  package MyApache2::BlockByIP;
  
  use strict;
  use warnings;
  
  use Apache2::RequestRec ();
  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 $r = shift;
  
      return exists $bad_ips{$r->connection->remote_ip}
          ? Apache2::Const::FORBIDDEN
          : Apache2::Const::OK;
  }
  
  1;

The handler retrieves the connection's IP address, looks it up in the
hash of blacklisted IPs and forbids the access if found. If the IP is
not blacklisted, the handler returns control to the next access
checker handler, which may still block the access based on a different
rule.

To enable the handler simply add it to the container that needs to be
protected. For example to protect an access to the registry scripts
executed from the base location I</perl> add:

  <Location /perl/>
      SetHandler perl-script
      PerlResponseHandler ModPerl::Registry
      PerlAccessHandler MyApache2::BlockByIP
      Options +ExecCGI
  </Location>

It's important to notice that C<PerlAccessHandler> can be configured
for any subsection of the site, no matter whether it's served by a
mod_perl response handler or not. For example to run the handler from
our example for all requests to the server simply add to
I<httpd.conf>:

  <Location />
      PerlAccessHandler MyApache2::BlockByIP
  </Location>






=head2 PerlAuthenHandler

The I<check_user_id> (I<authen>) phase is called whenever the
requested file or directory is password protected.  This, in turn,
requires that the directory be associated with C<AuthName>,
C<AuthType> and at least one C<require> directive.

This phase is usually used to verify a user's identification
credentials. If the credentials are verified to be correct, the
handler should return C<Apache2::Const::OK>.  Otherwise the handler
returns C<Apache2::Const::HTTP_UNAUTHORIZED> to indicate that the user
has not authenticated successfully.  When Apache sends the HTTP header
with this code, the browser will normally pop up a dialog box that
prompts the user for login information.

This phase is of type
C<L<RUN_FIRST|docs::2.0::user::handlers::intro/item_RUN_FIRST>>.

The handler's configuration scope is
C<L<DIR|docs::2.0::user::config::config/item_DIR>>.

B<Arguments>

See the L<HTTP Request Handler Skeleton|docs::2.0::user::handlers::http/HTTP_Request_Handler_Skeleton> for a description of handler arguments.

B<Return>

See L<Stacked Handlers|docs::2.0::user::handlers::intro/Stacked_Handlers> 
for a description of handler return codes.

B<Examples>

The following handler authenticates users by asking for a username and
a password and lets them in only if the length of a string made from
the supplied username and password and a single space equals to the
secret length, specified by the constant C<SECRET_LENGTH>.

  #file:MyApache2/SecretLengthAuth.pm
  #---------------------------------
  package MyApache2::SecretLengthAuth;
  
  use strict;
  use warnings;
  
  use Apache2::Access ();
  use Apache2::RequestUtil ();
  
  use Apache2::Const -compile => qw(OK DECLINED HTTP_UNAUTHORIZED);
  
  use constant SECRET_LENGTH => 14;
  
  sub handler {
      my $r = shift;
  
      my ($status, $password) = $r->get_basic_auth_pw;
      return $status unless $status == Apache2::Const::OK;
  
      return Apache2::Const::OK 
          if SECRET_LENGTH == length join " ", $r->user, $password;
  
      $r->note_basic_auth_failure;
      return Apache2::Const::HTTP_UNAUTHORIZED;
  }
  
  1;

First the handler retrieves the status of the authentication and the
password in plain text. The status will be set to
C<Apache2::Const::OK> only when the user has supplied the username and
the password credentials. If the status is different, we just let
Apache handle this situation for us, which will usually challenge the
client so it'll supply the credentials.

Note that C<get_basic_auth_pw()> does a few things behind the scenes,
which are important to understand if you plan on implementing your own
authentication mechanism that does not use C<get_basic_auth_pw()>.
First, is checks the value of the configured C<AuthType> for the
request, making sure it is C<Basic>.  Then it makes sure that the
Authorization (or Proxy-Authorization) header is formatted for
C<Basic> authentication.  Finally, after isolating the user and
password from the header, it populates the I<ap_auth_type> slot in the
request record with C<Basic>.  For the first and last parts of this
process, mod_perl offers an API. C<$r-E<gt>auth_type> returns the
configured authentication type for the current request - whatever was
set via the C<AuthType> configuration directive.
C<$r-E<gt>ap_auth_type> populates the I<ap_auth_type> slot in the
request record, which should be done after it has been confirmed that
the request is indeed using C<Basic> authentication.  (Note:
C<$r-E<gt>ap_auth_type> was C<$r-E<gt>connection-E<gt>auth_type> in
the mod_perl 1.0 API.)

Once we know that we have the username and the password supplied by
the client, we can proceed with the authentication. Our authentication
algorithm is unusual. Instead of validating the username/password pair
against a password file, we simply check that the string built from
these two items plus a single space is C<SECRET_LENGTH> long (14 in
our example). So for example the pair I<mod_perl/rules> authenticates
correctly, whereas I<secret/password> does not, because the latter
pair will make a string of 15 characters. Of course this is not a
strong authentication scheme and you shouldn't use it for serious
things, but it's fun to play with. Most authentication validations
simply verify the username/password against a database of valid pairs,
usually this requires the password to be encrypted first, since
storing passwords in clear is a bad idea.

Finally if our authentication fails the handler calls
note_basic_auth_failure() and returns
C<Apache2::Const::HTTP_UNAUTHORIZED>, which sets the proper HTTP
response headers that tell the client that its user that the
authentication has failed and the credentials should be supplied
again.

It's not enough to enable this handler for the authentication to
work. You have to tell Apache what authentication scheme to use
(C<Basic> or C<Digest>), which is specified by the C<AuthType>
directive, and you should also supply the C<AuthName> -- the
authentication realm, which is really just a string that the client
usually uses as a title in the pop-up box, where the username and the
password are inserted. Finally the C<Require> directive is needed to
specify which usernames are allowed to authenticate. If you set it to
C<valid-user> any username will do.

Here is the whole configuration section that requires users to
authenticate before they are allowed to run the registry scripts from
I</perl/>:

  <Location /perl/>
      SetHandler perl-script
      PerlResponseHandler ModPerl::Registry
      PerlAuthenHandler MyApache2::SecretLengthAuth
      Options +ExecCGI
  
      AuthType Basic
      AuthName "The Gate"
      Require valid-user
  </Location>

Just like C<PerlAccessHandler> and other mod_perl handlers,
C<PerlAuthenHandler> can be configured for any subsection of the site,
no matter whether it's served by a mod_perl response handler or
not. For example to use the authentication handler from the last
example for any requests to the site, simply use:

  <Location />
      PerlAuthenHandler MyApache2::SecretLengthAuth
      AuthType Basic
      AuthName "The Gate"
      Require valid-user
  </Location>







=head2 PerlAuthzHandler

The I<auth_checker> (I<authz>) phase is used for authorization
control. This phase requires a successful authentication from the
previous phase, because a username is needed in order to decide
whether a user is authorized to access the requested resource.

As this phase is tightly connected to the authentication phase, the
handlers registered for this phase are only called when the requested
resource is password protected, similar to the auth phase. The handler
is expected to return C<Apache2::Const::DECLINED> to defer the
decision, C<Apache2::Const::OK> to indicate its acceptance of the
user's authorization, or C<Apache2::Const::HTTP_UNAUTHORIZED> to
indicate that the user is not authorized to access the requested
document.

This phase is of type
C<L<RUN_FIRST|docs::2.0::user::handlers::intro/item_RUN_FIRST>>.

The handler's configuration scope is
C<L<DIR|docs::2.0::user::config::config/item_DIR>>.

B<Arguments>

See the L<HTTP Request Handler Skeleton|docs::2.0::user::handlers::http/HTTP_Request_Handler_Skeleton> for a description of handler arguments.

B<Return>

See L<Stacked Handlers|docs::2.0::user::handlers::intro/Stacked_Handlers> 
for a description of handler return codes.

B<Examples>

Here is the C<MyApache2::SecretResourceAuthz> handler which grants
access to certain resources only to certain users who have already
properly authenticated:

  #file:MyApache2/SecretResourceAuthz.pm
  #------------------------------------
  package MyApache2::SecretResourceAuthz;
  
  use strict;
  use warnings;
  
  use Apache2::Access ();
  use Apache2::RequestUtil ();
  
  use Apache2::Const -compile => qw(OK HTTP_UNAUTHORIZED);
  
  my %protected = (
      'admin'  => ['stas'],
      'report' => [qw(stas boss)],
  );
  
  sub handler {
      my $r = shift;
  
      my $user = $r->user;
      if ($user) {
          my ($section) = $r->uri =~ m|^/company/(\w+)/|;
          if (defined $section && exists $protected{$section}) {
              my $users = $protected{$section};
              return Apache2::Const::OK if grep { $_ eq $user } @$users;
          }
          else {
              return Apache2::Const::OK;
          }
      }
  
      $r->note_basic_auth_failure;
      return Apache2::Const::HTTP_UNAUTHORIZED;
  }
  
  1;

This authorization handler is very similar to the authentication
handler L<from the previous section|/PerlAuthenHandler>. Here we rely
on the previous phase to get users authenticated, and now as we have
the username we can make decisions whether to let the user access the
resource it has asked for or not. In our example we have a simple hash
which maps which users are allowed to access what resources. So for
example anything under I</company/admin/> can be accessed only by the
user I<stas>, I</company/report/> can be accessed by users I<stas> and
I<boss>, whereas any other resources under I</company/> can be
accessed by everybody who has reached so far. If for some reason we
don't get the username, we or the user is not authorized to access the
resource the handler does the same thing as it does when the
authentication fails, i.e, calls:

      $r->note_basic_auth_failure;
      return Apache2::Const::HTTP_UNAUTHORIZED;

The configuration is similar to the one in L<the previous
section|/PerlAuthenHandler>, this time we just add the 
C<PerlAuthzHandler> setting. The rest doesn't change.

  Alias /company/ /home/httpd/httpd-2.0/perl/
  <Location /company/>
      SetHandler perl-script
      PerlResponseHandler ModPerl::Registry
      PerlAuthenHandler MyApache2::SecretLengthAuth
      PerlAuthzHandler  MyApache2::SecretResourceAuthz
      Options +ExecCGI
  
      AuthType Basic
      AuthName "The Secret Gate"
      Require valid-user
  </Location>

And if you want to run the authentication and authorization for the
whole site, simply add:

  <Location />
      PerlAuthenHandler MyApache2::SecretLengthAuth
      PerlAuthzHandler  MyApache2::SecretResourceAuthz
      AuthType Basic
      AuthName "The Secret Gate"
      Require valid-user
  </Location>



=head2 PerlTypeHandler

The I<type_checker> phase is used to set the response MIME type
(C<Content-type>) and sometimes other bits of document type
information like the document language.

For example C<mod_autoindex>, which performs automatic directory
indexing, uses this phase to map the filename extensions to the
corresponding icons which will be later used in the listing of files.

Of course later phases may override the mime type set in this phase.

This phase is of type
C<L<RUN_FIRST|docs::2.0::user::handlers::intro/item_RUN_FIRST>>.

The handler's configuration scope is
C<L<DIR|docs::2.0::user::config::config/item_DIR>>.

B<Arguments>

See the L<HTTP Request Handler Skeleton|docs::2.0::user::handlers::http/HTTP_Request_Handler_Skeleton> for a description of handler arguments.

B<Return>

See L<Stacked Handlers|docs::2.0::user::handlers::intro/Stacked_Handlers> 
for a description of handler return codes.

B<Examples>

The most important thing to remember when overriding the default
I<type_checker> handler, which is usually the mod_mime handler, is
that you have to set the handler that will take care of the response
phase and the response callback function or the code won't
work. mod_mime does that based on C<SetHandler> and C<AddHandler>
directives, and file extensions. So if you want the content handler to
be run by mod_perl, set either:

  $r->handler('perl-script');
  $r->set_handlers(PerlResponseHandler => \&handler);

or:

  $r->handler('modperl');
  $r->set_handlers(PerlResponseHandler => \&handler);

depending on which type of response handler is wanted.

Writing a C<PerlTypeHandler> handler which sets the content-type value
and returns C<Apache2::Const::DECLINED> so that the default handler
will do the rest of the work, is not a good idea, because mod_mime
will probably override this and other settings.

Therefore it's the easiest to leave this stage alone and do any
desired settings in the I<fixups> phase.




=head2 PerlFixupHandler

The I<fixups> phase is happening just before the content handling
phase. It gives the last chance to do things before the response is
generated. For example in this phase C<mod_env> populates the
environment with variables configured with I<SetEnv> and I<PassEnv>
directives.

This phase is of type
C<L<RUN_ALL|docs::2.0::user::handlers::intro/item_RUN_ALL>>.

The handler's configuration scope is
C<L<DIR|docs::2.0::user::config::config/item_DIR>>.

B<Arguments>

See the L<HTTP Request Handler Skeleton|docs::2.0::user::handlers::http/HTTP_Request_Handler_Skeleton> for a description of handler arguments.

B<Return>

See L<Stacked Handlers|docs::2.0::user::handlers::intro/Stacked_Handlers> 
for a description of handler return codes.

B<Examples>

The following fixup handler example tells Apache at run time which
handler and callback should be used to process the request based on
the file extension of the request's URI.

  #file:MyApache2/FileExtDispatch.pm
  #--------------------------------
  package MyApache2::FileExtDispatch;
  
  use strict;
  use warnings;
  
  use Apache2::RequestIO ();
  use Apache2::RequestRec ();
  use Apache2::RequestUtil ();
  
  use Apache2::Const -compile => 'OK';
  
  use constant HANDLER  => 0;
  use constant CALLBACK => 1;
  
  my %exts = (
      cgi => ['perl-script',     \&cgi_handler],
      pl  => ['modperl',         \&pl_handler ],
      tt  => ['perl-script',     \&tt_handler ],
      txt => ['default-handler', undef        ],
  );
  
  sub handler {
      my $r = shift;
  
      my ($ext) = $r->uri =~ /\.(\w+)$/;
      $ext = 'txt' unless defined $ext and exists $exts{$ext};
  
      $r->handler($exts{$ext}->[HANDLER]);
  
      if (defined $exts{$ext}->[CALLBACK]) {
          $r->set_handlers(PerlResponseHandler => $exts{$ext}->[CALLBACK]);
      }
  
      return Apache2::Const::OK;
  }
  
  sub cgi_handler { content_handler($_[0], 'cgi') }
  sub pl_handler  { content_handler($_[0], 'pl')  }
  sub tt_handler  { content_handler($_[0], 'tt')  }
  
  sub content_handler {
      my ($r, $type) = @_;
  
      $r->content_type('text/plain');
      $r->print("A handler of type '$type' was called");
  
      return Apache2::Const::OK;
  }
  
  1;

In the example we have used the following mapping.

  my %exts = (
      cgi => ['perl-script',     \&cgi_handler],
      pl  => ['modperl',         \&pl_handler ],
      tt  => ['perl-script',     \&tt_handler ],
      txt => ['default-handler', undef        ],
  );

So that I<.cgi> requests will be handled by the C<perl-script> handler
and the C<cgi_handler()> callback, I<.pl> requests by C<modperl> and
C<pl_handler()>, I<.tt> (template toolkit) by C<perl-script> and the
C<tt_handler()>, finally I<.txt> request by the C<default-handler>
handler, which requires no callback.

Moreover the handler assumes that if the request's URI has no file
extension or it does, but it's not in its mapping, the
C<default-handler> will be used, as if the I<txt> extension was used.

After doing the mapping, the handler assigns the handler:

      $r->handler($exts{$ext}->[HANDLER]);

and the callback if needed:

      if (defined $exts{$ext}->[CALLBACK]) {
          $r->set_handlers(
			  PerlResponseHandler => $exts{$ext}->[CALLBACK]);
      }

In this simple example the callback functions don't do much but
calling the same content handler which simply prints the name of the
extension if handled by mod_perl, otherwise Apache will serve the
other files using the default handler. In real world you will use
callbacks to real content handlers that do real things.

Here is how this handler is configured:

  Alias /dispatch/ /home/httpd/httpd-2.0/htdocs/
  <Location /dispatch/>
      PerlFixupHandler MyApache2::FileExtDispatch
  </Location>

Notice that there is no need to specify anything, but the fixup
handler. It applies the rest of the settings dynamically at run-time.






=head2 PerlResponseHandler

The I<handler> (I<response>) phase is used for generating the
response. This is arguably the most important phase and most of the
existing Apache modules do most of their work at this phase.

This is the only phase that requires two directives under
mod_perl. For example:

  <Location /perl>
     SetHandler perl-script
     PerlResponseHandler MyApache2::WorldDomination
  </Location>

C<SetHandler> set to
C<L<perl-script|docs::2.0::user::config::config/C_perl_script_>> or
C<L<modperl|docs::2.0::user::config::config/C_modperl_>> tells Apache
that mod_perl is going to handle the response
generation. C<PerlResponseHandler> tells mod_perl which callback is
going to do the job.

This phase is of type
C<L<RUN_FIRST|docs::2.0::user::handlers::intro/item_RUN_FIRST>>.

The handler's configuration scope is
C<L<DIR|docs::2.0::user::config::config/item_DIR>>.

B<Arguments>

See the L<HTTP Request Handler Skeleton|docs::2.0::user::handlers::http/HTTP_Request_Handler_Skeleton> for a description of handler arguments.

B<Return>

See L<Stacked Handlers|docs::2.0::user::handlers::intro/Stacked_Handlers> 
for a description of handler return codes.

B<Examples>

Most of the C<Apache::> modules on CPAN are dealing with this
phase. In fact most of the developers spend the majority of their time
working on handlers that generate response content.

Let's write a simple response handler, that just generates some
content. This time let's do something more interesting than printing
I<"Hello world">. Let's write a handler that prints itself:

  #file:MyApache2/Deparse.pm
  #------------------------
  package MyApache2::Deparse;
  
  use strict;
  use warnings;
  
  use Apache2::RequestRec ();
  use Apache2::RequestIO ();
  use B::Deparse ();
  
  use Apache2::Const -compile => 'OK';
  
  sub handler {
      my $r = shift;
  
      $r->content_type('text/plain');
      $r->print('sub handler ', B::Deparse->new->coderef2text(\&handler));
  
      return Apache2::Const::OK;
  }
  1;

To enable this handler add to I<httpd.conf>:

  <Location /deparse>
      SetHandler modperl
      PerlResponseHandler MyApache2::Deparse
  </Location>

Now when the server is restarted and we issue a request to
I<http://localhost/deparse> we get the following response:

  sub handler {
      package MyApache2::Deparse;
      use warnings;
      use strict 'refs';
      my $r = shift @_;
      $r->content_type('text/plain');
      $r->print('sub handler ', 'B::Deparse'->new->coderef2text(\&handler));
      return 0;
  }

If you compare it to the source code, it's pretty much the same
code. C<B::Deparse> is fun to play with!







=head2 PerlLogHandler

The I<log_transaction> phase happens no matter how the previous phases
have ended up. If one of the earlier phases has aborted a request,
e.g., failed authentication or 404 (file not found) errors, the rest of
the phases up to and including the response phases are skipped. But
this phase is always executed.

By this phase all the information about the request and the response
is known, therefore the logging handlers usually record this
information in various ways (e.g., logging to a flat file or a
database).

This phase is of type
C<L<RUN_ALL|docs::2.0::user::handlers::intro/item_RUN_ALL>>.

The handler's configuration scope is
C<L<DIR|docs::2.0::user::config::config/item_DIR>>.

B<Arguments>

See the L<HTTP Request Handler Skeleton|docs::2.0::user::handlers::http/HTTP_Request_Handler_Skeleton> for a description of handler arguments.

B<Return>

See L<Stacked Handlers|docs::2.0::user::handlers::intro/Stacked_Handlers> 
for a description of handler return codes.

B<Examples>

Imagine a situation where you have to log requests into individual
files, one per user. Assuming that all requests start with
I</~username/>, so it's easy to categorize requests by the
username. Here is the log handler that does that:

  #file:MyApache2/LogPerUser.pm
  #---------------------------
  package MyApache2::LogPerUser;
  
  use strict;
  use warnings;
  
  use Apache2::RequestRec ();
  use Apache2::Connection ();
  
  use Fcntl qw(:flock);
  use File::Spec::Functions qw(catfile);
  
  use Apache2::Const -compile => qw(OK DECLINED);
  
  sub handler {
      my $r = shift;
  
      my ($username) = $r->uri =~ m|^/~([^/]+)|;
      return Apache2::Const::DECLINED unless defined $username;
  
      my $entry = sprintf qq(%s [%s] "%s" %d %d\n),
          $r->connection->remote_ip, scalar(localtime),
          $r->uri, $r->status, $r->bytes_sent;
  
      my $log_path = catfile Apache2::ServerUtil::server_root,
          "logs", "$username.log";
      open my $fh, ">>$log_path" or die "can't open $log_path: $!";
      flock $fh, LOCK_EX;
      print $fh $entry;
      close $fh;
  
      return Apache2::Const::OK;
  }
  1;

First the handler tries to figure out what username the request is
issued for, if it fails to match the URI, it simply returns
C<Apache2::Const::DECLINED>, letting other log handlers to do the
logging. Though it could return C<Apache2::Const::OK> since all other
log handlers will be run anyway.

Next it builds the log entry, similar to the default I<access_log>
entry. It's comprised of remote IP, the current time, the uri, the
return status and how many bytes were sent to the client as a response
body.

Finally the handler appends this entry to the log file for the user
the request was issued for. Usually it's safe to append short strings
to the file without being afraid of messing up the file, when two
files attempt to write at the same time, but just to be on the safe
side the handler exclusively locks the file before performing the
writing.

To configure the handler simply enable the module with the
C<PerlLogHandler> directive, for the desired URI namespace (starting
with : I</~> in our example):

  <LocationMatch "^/~">
      SetHandler perl-script
      PerlResponseHandler ModPerl::Registry
      PerlLogHandler MyApache2::LogPerUser
      Options +ExecCGI
  </LocationMatch>

After restarting the server and issuing requests to the following
URIs:

  http://localhost/~stas/test.pl
  http://localhost/~eric/test.pl
  http://localhost/~stas/date.pl

The C<MyApache2::LogPerUser> handler will append to I<logs/stas.log>:

  127.0.0.1 [Sat Aug 31 01:50:38 2002] "/~stas/test.pl" 200 8
  127.0.0.1 [Sat Aug 31 01:50:40 2002] "/~stas/date.pl" 200 44

and to I<logs/eric.log>:

  127.0.0.1 [Sat Aug 31 01:50:39 2002] "/~eric/test.pl" 200 8

It's important to notice that C<PerlLogHandler> can be configured for
any subsection of the site, no matter whether it's served by a
mod_perl response handler or not. For example to run the handler from
our example for all requests to the server, simply add to
I<httpd.conf>:

  <Location />
      PerlLogHandler MyApache2::LogPerUser
  </Location>

Since the C<PerlLogHandler> phase is of type
C<L<RUN_ALL|docs::2.0::user::handlers::intro/item_RUN_ALL>>, all other
logging handlers will be called as well.







=head2 PerlCleanupHandler

There is no I<cleanup> Apache phase, it exists only inside mod_perl.
It is used to execute some code immediately after the request has been
served (the client went away) and before the request object is
destroyed.

There are several usages for this use phase. The obvious one is to run
a cleanup code, for example removing temporarily created files. The
less obvious is to use this phase instead of
C<L<PerlLogHandler|/PerlLogHandler>> if the logging operation is time
consuming. This approach allows one to free the client as soon as the
response is sent.

This phase is of type
C<L<RUN_ALL|docs::2.0::user::handlers::intro/item_RUN_ALL>>.

The handler's configuration scope is
C<L<DIR|docs::2.0::user::config::config/item_DIR>>.

B<Arguments>

See the L<HTTP Request Handler Skeleton|docs::2.0::user::handlers::http/HTTP_Request_Handler_Skeleton> for a description of handler arguments.

B<Return>

See L<Stacked Handlers|docs::2.0::user::handlers::intro/Stacked_Handlers> 
for a description of handler return codes.

B<Examples>

There are two ways to register and run cleanup handlers:

=over

=item 1 Using the C<PerlCleanupHandler> phase

  PerlCleanupHandler MyApache2::Cleanup

or:

  $r->push_handlers(PerlCleanupHandler => \&cleanup);

This method is identical to all other handlers.

In this technique the C<cleanup()> callback accepts C<$r> as its only
argument.

=item 2 Using C<cleanup_register()> acting on the request object's pool

Since a request object pool is destroyed at the end of each request,
we can use
C<L<cleanup_register|docs::2.0::api::APR::Pool/C_cleanup_register_>>
to register a cleanup callback which will be executed just before the
pool is destroyed. For example:

    $r->pool->cleanup_register(\&cleanup, $arg);

The important difference from using the C<PerlCleanupHandler> handler,
is that here you can pass an optional arbitrary argument to the
callback function, and no C<$r> argument is passed by
default. Therefore if you need to pass any data other than C<$r> you
may want to use this technique.

=back

Here is an example where the cleanup handler is used to delete a
temporary file. The response handler is running C<ls -l> and stores
the output in temporary file, which is then used by
C<$r-E<gt>sendfile> to send the file's contents. We use
C<push_handlers()> to push C<PerlCleanupHandler> to unlink the file at
the end of the request.

  #file:MyApache2/Cleanup1.pm
  #-------------------------
  package MyApache2::Cleanup1;
  
  use strict;
  use warnings FATAL => 'all';
  
  use File::Spec::Functions qw(catfile);
  
  use Apache2::RequestRec ();
  use Apache2::RequestIO ();
  use Apache2::RequestUtil ();
  
  use Apache2::Const -compile => qw(OK DECLINED);
  use APR::Const    -compile => 'SUCCESS';
  
  my $file = catfile "/tmp", "data";
  
  sub handler {
      my $r = shift;
  
      $r->content_type('text/plain');
  
      local @ENV{qw(PATH BASH_ENV)};
      qx(/bin/ls -l > $file);
  
      my $status = $r->sendfile($file);
      die "sendfile has failed" unless $status == APR::Const::SUCCESS;
  
      $r->push_handlers(PerlCleanupHandler => \&cleanup);
  
      return Apache2::Const::OK;
  }
  
  sub cleanup {
      my $r = shift;
  
      die "Can't find file: $file" unless -e $file;
      unlink $file or die "failed to unlink $file";
  
      return Apache2::Const::OK;
  }
  1;

Next we add the following configuration:

  <Location /cleanup1>
      SetHandler modperl
      PerlResponseHandler MyApache2::Cleanup1
  </Location>

Now when a request to I</cleanup1> is made, the contents of the
current directory will be printed and once the request is over the
temporary file is deleted.

This response handler has a problem of running in a multi-process
environment, since it uses the same file, and several processes may
try to read/write/delete that file at the same time, wrecking
havoc. We could have appended the process id C<$$> to the file's name,
but remember that mod_perl 2.0 code may run in the threaded
environment, meaning that there will be many threads running in the
same process and the C<$$> trick won't work any longer. Therefore one
really has to use this code to create unique, but predictable, file
names across threads and processes:

  sub unique_id {
      require Apache2::MPM;
      require APR::OS;
      return Apache2::MPM->is_threaded
          ? "$$." . ${ APR::OS::current_thread_id() }
          : $$;
  }

In the threaded environment it will return a string containing the
process ID, followed by a thread ID. In the non-threaded environment
only the process ID will be returned. However since it gives us a
predictable string, they may still be a non-satisfactory
solution. Therefore we need to use a random string. We can either
either Perl's C<rand>, some CPAN module or the APR's C<APR::UUID>:

 sub unique_id {
  require APR::UUID;
  return APR::UUID->new->format;
 }

Now the problem is how do we tell the cleanup handler what file should
be cleaned up? We could have stored it in the C<$r-E<gt>notes> table
in the response handler and then retrieve it in the cleanup
handler. However there is a better way - as mentioned earlier, we can
register a callback for request pool cleanup, and when using this
method we can pass an arbitrary argument to it. Therefore in our case
we choose to pass the file name, based on random string. Here is a
better version of the response and cleanup handlers, that uses this
technique:

 #file:  MyApache2/Cleanup2.pm
 #-------------------------
 package MyApache2::Cleanup2;
  
 use strict;
 use warnings FATAL => 'all';
  
 use File::Spec::Functions qw(catfile);
  
 use Apache2::RequestRec ();
 use Apache2::RequestIO ();
 use Apache2::RequestUtil ();
 use APR::UUID ();
 use APR::Pool ();
  
 use Apache2::Const -compile => qw(OK DECLINED);
 use APR::Const    -compile => 'SUCCESS';
  
 my $file_base = catfile "/tmp", "data-";
  
 sub handler {
         my $r = shift;
  
     $r->content_type('text/plain');
     my $file = $file_base . APR::UUID->new->format;
  
     local @ENV{qw(PATH BASH_ENV)};
     qx(/bin/ls -l > $file);
  
     my $status = $r->sendfile($file);
     die "sendfile has failed" unless $status == APR::Const::SUCCESS;
  
     $r->pool->cleanup_register(\&cleanup, $file);
  
     return Apache2::Const::OK;
 }
  
 sub cleanup {
     my $file = shift;
  
     die "Can't find file: $file" unless -e $file;
     unlink $file or die "failed to unlink $file";
  
     return Apache2::Const::OK;
 }
 1;

Similarly to the first handler, we add the configuration:

 <Location /cleanup2>
     SetHandler modperl
     PerlResponseHandler MyApache2::Cleanup2
 </Location>

And now when requesting I</cleanup2> we still get the same output --
the listing of the current directory -- but this time this code will
work correctly in the multi-processes/multi-threaded environment and
temporary files get cleaned up as well.


=head3 Possible Caveats

C<PerlCleanupHandler> may fail to be completed on server
shutdown/graceful restart since Apache will kill the registered
handlers via SIGTERM, before they had a chance to run or even in the
middle of its execution. See:
http://marc.theaimsgroup.com/?t=106387845200003&r=1&w=2
http://marc.theaimsgroup.com/?l=apache-modperl-dev&m=106427616108596&w=2







=head1 Miscellaneous Issues


=head2 Handling HEAD Requests

In order to avoid the overhead of sending the data to the client when
the request is of type HEAD in mod_perl 1.0 we L<used to return
early|docs::1.0::guide::porting/Generating_correct_HTTP_Headers> from
the handler:

 return Apache2::Const::OK if $r->header_only;

This logic should not be used in mod_perl 2.0, because Apache 2.0
automatically discards the response body for HEAD requests. It expects
the full body to generate the correct set of response headers, if you
don't send the body you may encounter problems.

(You can also read the comment in for C<ap_http_header_filter()> in
I<modules/http/http_protocol.c> in the Apache 2.0 source.)





=head2 C<Content-Length> Response Header

You may encounter some issues with the C-L (C<Content-Length>)
header. Some of them are discussed here.

=over

=item * The special case of C<Content-Length: 0>

Since Apache proclaims itself governor of the C-L header via the C-L
filter (ap_content_length_filter at F<httpd-2.0/server/protocol.c>),
for the most part C<GET> and C<HEAD> behave exactly the same.
However, when Apache sees a C<HEAD> request with a C-L header of zero
it takes special action and removes the C-L header.  This is done to
protect against handlers that called C<$r-E<gt>header_only> (L<which
was ok in 1.3 but is not in 2.0|/Handling_HEAD_Requests>).  Therefore,
C<GET> and C<HEAD> behave identically, except when the content
handler (and/or filters) end up sending no content.  For more details
refer to the lengthy comments in C<ap_http_header_filter()> in
F<httpd-2.0/modules/http/http_protocol.c>).

For more discussion on why it is important to get HEAD requests right,
see these threads from the mod_perl list:

 http://marc.theaimsgroup.com/?l=apache-modperl&m=108647669726915&w=2
 http://marc.theaimsgroup.com/?t=109122984600001&r=1&w=2

as well as this bug report from mozilla, which shows how C<HEAD>
requests are used in the wild:

 http://bugzilla.mozilla.org/show_bug.cgi?id=245447

=item * Not getting C<Content-Length> header with C<HEAD> requests

Even though the spec says that content handlers should send an
identical response for GET and HEAD requests, some folks try to
L<avoid the overhead of generating the response
body|/Handling_HEAD_Requests>, which Apache is going to discard anyway
for HEAD requests. The following discussion assumes that we deal with
a HEAD request.

When Apache sees EOS and no headers and no response body were sent,
C<ap_content_length_filter()> (F<httpd-2.0/server/protocol.c>) sets
C-L to 0. Later on C<ap_http_header_filter()>
(F<httpd-2.0/modules/http/http_protocol.c>) removes the C-L header for
the HEAD requests.

The workaround is to force the sending of the response headers, before
C<EOS> was sent (which happens when the response handler returns). The
simplest solution is to use rflush():

 if ($r->header_only) { # HEAD
     $body_len = calculate_body_len();
     $r->set_content_length($body_len);
     $r->rflush;
 }
 else {                 # GET
     # generate and send the body
 }

now if the handler sets the C-L header it'll be delivered to the
client unmodified.

=back



=head1 Misc Notes

These items will need to be extended and integrated in this or other
HTTP related documents:

=over

=item * front-end back-end setup: mod_proxy+X-Forwarded-For

apache-1.3:

frontend: mod_proxy_add_forward http://develooper.com/code/mpaf/

backend: mod_rpaf (reverse proxy add forward):
http://stderr.net/apache/rpaf/

apache-2.x:

frontend: mod_proxy

backend: mod_rpaf: http://stderr.net/apache/rpaf/

=back



=head1 Extending HTTP Protocol

Extending HTTP under mod_perl is a trivial task.  Look at L<the
example of adding a new method C<EMAIL>|/PerlHeaderParserHandler> for
details.


=head1 HTTP Status Codes

The Hypertext Transfer Protocol (HTTP) is an application-level
protocol for distributed, collaborative, hypermedia information
systems. It is a generic, stateless, protocol which can be used for
many tasks beyond its use for hypertext, such as name servers and
distributed object management systems, through extension of its
request methods, error codes and headers. A feature of HTTP is the
typing and negotiation of data representation, allowing systems to be
built independently of the data being transferred.

HTTP 1.0 is described in Requests For Comments (RFC) 1945. HTTP 1.1 is
the latest version of the specifications and as of this writing HTTP
1.1 is covered in RFC 2616.

When writing mod_perl applications, usually only a small subset of HTTP
response codes is used, but sometimes you need to know others as
well. We will give a short description of each code and you will find
the extended explanation in the appropriate RFC. (Section 9 in RFC
1945 and section 10 in RFC 2616). You can always find the latest link
to these RFCs at the Web Consortium site,
I<http://www.w3.org/Protocols/>.

While HTTP 1.1 is widely supported, HTTP 1.0 still remains the
mainstream standard. Therefore we will supply a summary of the both
versions including the corresponding Apache constants.

In mod_perl these constants can be accessed the 
C<L<Apache::Constants|docs::1.0::api::Apache::Constants>>
package (e.g., to access the HTTP_OK constant use
C<Apache::Constants::HTTP_OK>). See the 
C<L<Apache::Constants|docs::1.0::api::Apache::Constants>> manpage
for more information.

In mod_perl2 these constants can be accessed the 
C<L<Apache2::Const|docs::2.0::api::Apache2::Const>>
package (e.g., to access the HTTP_OK constant use
C<Apache2::Const::HTTP_OK>). See the 
C<L<Apache2::Const|docs::2.0::api::Apache2::Const>> manpage
for more information.

=head2 HTTP 1.0 Status Codes

=over 4

=item *

Successful 2xx: 

 200 HTTP_OK                    OK
 201 HTTP_CREATED               Created
 202 HTTP_ACCEPTED              Accepted
 204 HTTP_NO_CONTENT            No Content

=item *

Redirection 3xx:

 301 HTTP_MOVED_PERMANENTLY     Multiple Choices
 302 HTTP_MOVED_TEMPORARILY     Moved Permanently
 303 HTTP_SEE_OTHER             Moved Temporarily
 304 HTTP_NOT_MODIFIED          Not Modified

=item *

Client Error 4xx:

 400 HTTP_BAD_REQUEST           Bad Request
 401 HTTP_UNAUTHORIZED          Unauthorized
 403 HTTP_FORBIDDEN             Forbidden
 404 HTTP_NOT_FOUND             Not Found

=item *

Server Error 5xx:

 500 HTTP_INTERNAL_SERVER_ERROR Internal Server Error
 501 HTTP_NOT_IMPLEMENTED       Not Implemented
 502 HTTP_BAD_GATEWAY           Bad Gateway
 503 HTTP_SERVICE_UNAVAILABLE   Service UnavailableStatus Codes

=back

=head2 HTTP 1.1 Status Codes

=over 4

=item *

Informational 1xx:

 100 HTTP_CONTINUE                        Continue
 101 HTTP_SWITCHING_PROTOCOLS             Switching Protocols

=item *

Successful 2xx:

 200 HTTP_OK                              OK
 201 HTTP_CREATED                         Created
 202 HTTP_ACCEPTED                        Accepted
 203 HTTP_NON_AUTHORITATIVE               Non-Authoritative Information
 204 HTTP_NO_CONTENT                      No Content
 205 HTTP_RESET_CONTENT                   Reset Content
 206 HTTP_PARTIAL_CONTENT                 Partial Content

=item *

Redirection 3xx:

 300 HTTP_MULTIPLE_CHOICES                Multiple Choices
 301 HTTP_MOVED_PERMANENTLY               Moved Permanently
 302 HTTP_MOVED_TEMPORARILY               Found
 303 HTTP_SEE_OTHER                       See Other
 304 HTTP_NOT_MODIFIED                    Not Modified
 305 HTTP_USE_PROXY                       Use Proxy
 306                                      (Unused)
 307 HTTP_TEMPORARY_REDIRECT              Temporary Redirect

=item *

Client Error 4xx:

 400 HTTP_BAD_REQUEST                     Bad Request
 401 HTTP_UNAUTHORIZED                    Unauthorized
 402 HTTP_PAYMENT_REQUIRED                Payment Required
 403 HTTP_FORBIDDEN                       Forbidden
 404 HTTP_NOT_FOUND                       Not Found
 405 HTTP_METHOD_NOT_ALLOWED              Method Not Allowed
 406 HTTP_NOT_ACCEPTABLE                  Not Acceptable
 407 HTTP_PROXY_AUTHENTICATION_REQUIRED   Proxy Authentication Required
 408 HTTP_REQUEST_TIMEOUT                 Request Timeout
 409 HTTP_CONFLICT                        Conflict
 410 HTTP_GONE                            Gone
 411 HTTP_LENGTH REQUIRED                 Length Required
 412 HTTP_PRECONDITION_FAILED             Precondition Failed
 413 HTTP_REQUEST_ENTITY_TOO_LARGE        Request Entity Too Large
 414 HTTP_REQUEST_URI_TOO_LARGE           Request-URI Too Long
 415 HTTP_UNSUPPORTED_MEDIA_TYPE          Unsupported Media Type
 416 HTTP_RANGE_NOT_SATISFIABLE           Requested Range Not Satisfiable
 417 HTTP_EXPECTATION_FAILED              Expectation Failed

=item *

Server Error 5xx:

 500 HTTP_INTERNAL_SERVER_ERROR           Internal Server Error
 501 HTTP_NOT IMPLEMENTED                 Not Implemented
 502 HTTP_BAD_GATEWAY                     Bad Gateway
 503 HTTP_SERVICE_UNAVAILABLE             Service Unavailable
 504 HTTP_GATEWAY_TIME_OUT                Gateway Timeout
 505 HTTP_VERSION_NOT_SUPPORTED           HTTP Version Not Supported

=back

=head2 References

All the information related to web protocols can be found at the World
Wide Web Consortium site, I<http://www.w3.org/Protocols/>.

There are many mirrors of the RFCs all around the world. One of the
good starting points might be I<http://www.rfc-editor.org/>.

The Eagle Book provided much of the HTTP constants material shown here 
I<http://www.modperl.com/book/chapters/ch9.html#The_Apache_Constants_Class>

=head1 Maintainers

Maintainer is the person(s) you should contact with updates,
corrections and patches.

=over

=item *

L<The mod_perl development team and numerous
contributors|about::contributors::people>.


=back


=head1 Authors

=over

=item *

Stas Bekman [http://stason.org/]

=back

Only the major authors are listed above. For contributors see the
Changes file.



=cut