File: jk_ajp_common.c

package info (click to toggle)
libapache-mod-jk 1%3A1.2.18-3etch2
  • links: PTS
  • area: main
  • in suites: etch
  • size: 5,008 kB
  • ctags: 2,664
  • sloc: ansic: 20,014; sh: 8,661; xml: 7,304; perl: 617; makefile: 321; awk: 59
file content (2268 lines) | stat: -rw-r--r-- 72,734 bytes parent folder | download | duplicates (2)
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
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
/*
 *  Copyright 1999-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/***************************************************************************
 * Description: common stuff for bi-directional protocols ajp13/ajp14.     *
 * Author:      Gal Shachor <shachor@il.ibm.com>                           *
 * Author:      Henri Gomez <hgomez@apache.org>                            *
 * Version:     $Revision: 422996 $                                          *
 ***************************************************************************/


#include "jk_global.h"
#include "jk_util.h"
#include "jk_ajp13.h"
#include "jk_ajp14.h"
#include "jk_ajp_common.h"
#include "jk_connect.h"
#ifdef AS400
#include "util_ebcdic.h"
#endif
#if defined(NETWARE) && defined(__NOVELL_LIBC__)
#include "novsock2.h"
#endif

/* Sleep for 100ms */
void jk_sleep_def(void)
{
#ifdef OS2
    DosSleep(100);
#elif defined(BEOS)
    snooze(100 * 1000);
#elif defined(NETWARE)
    delay(100);
#elif defined(WIN32)
    Sleep(100);
#else
    struct timeval tv;
    tv.tv_usec = 100 * 1000;
    tv.tv_sec = 0;
    select(0, NULL, NULL, NULL, &tv);
#endif
}

const char *response_trans_headers[] = {
    "Content-Type",
    "Content-Language",
    "Content-Length",
    "Date",
    "Last-Modified",
    "Location",
    "Set-Cookie",
    "Set-Cookie2",
    "Servlet-Engine",
    "Status",
    "WWW-Authenticate"
};

static const char *long_res_header_for_sc(int sc)
{
    const char *rc = NULL;
    sc = sc & 0X00FF;
    if (sc <= SC_RES_HEADERS_NUM && sc > 0) {
        rc = response_trans_headers[sc - 1];
    }

    return rc;
}

#define UNKNOWN_METHOD (-1)

static int sc_for_req_method(const char *method, size_t len)
{
    /* Note: the following code was generated by the "shilka" tool from
       the "cocom" parsing/compilation toolkit. It is an optimized lookup
       based on analysis of the input keywords. Postprocessing was done
       on the shilka output, but the basic structure and analysis is
       from there. Should new HTTP methods be added, then manual insertion
       into this code is fine, or simply re-running the shilka tool on
       the appropriate input. */

    /* Note: it is also quite reasonable to just use our method_registry,
       but I'm assuming (probably incorrectly) we want more speed here
       (based on the optimizations the previous code was doing). */

    switch (len)
    {
    case 3:
        switch (method[0])
        {
        case 'A':
            return (method[1] == 'C'
                    && method[2] == 'L'
                    ? SC_M_ACL : UNKNOWN_METHOD);
        case 'P':
            return (method[1] == 'U'
                    && method[2] == 'T'
                    ? SC_M_PUT : UNKNOWN_METHOD);
        case 'G':
            return (method[1] == 'E'
                    && method[2] == 'T'
                    ? SC_M_GET : UNKNOWN_METHOD);
        default:
            return UNKNOWN_METHOD;
        }

    case 4:
        switch (method[0])
        {
        case 'H':
            return (method[1] == 'E'
                    && method[2] == 'A'
                    && method[3] == 'D'
                    ? SC_M_HEAD : UNKNOWN_METHOD);
        case 'P':
            return (method[1] == 'O'
                    && method[2] == 'S'
                    && method[3] == 'T'
                    ? SC_M_POST : UNKNOWN_METHOD);
        case 'M':
            return (method[1] == 'O'
                    && method[2] == 'V'
                    && method[3] == 'E'
                    ? SC_M_MOVE : UNKNOWN_METHOD);
        case 'L':
            return (method[1] == 'O'
                    && method[2] == 'C'
                    && method[3] == 'K'
                    ? SC_M_LOCK : UNKNOWN_METHOD);
        case 'C':
            return (method[1] == 'O'
                    && method[2] == 'P'
                    && method[3] == 'Y'
                    ? SC_M_COPY : UNKNOWN_METHOD);
        default:
            return UNKNOWN_METHOD;
        }

    case 5:
        switch (method[2])
        {
        case 'R':
            return (memcmp(method, "MERGE", 5) == 0
                    ? SC_M_MERGE : UNKNOWN_METHOD);
        case 'C':
            return (memcmp(method, "MKCOL", 5) == 0
                    ? SC_M_MKCOL : UNKNOWN_METHOD);
        case 'B':
            return (memcmp(method, "LABEL", 5) == 0
                    ? SC_M_LABEL : UNKNOWN_METHOD);
        case 'A':
            return (memcmp(method, "TRACE", 5) == 0
                    ? SC_M_TRACE : UNKNOWN_METHOD);
        default:
            return UNKNOWN_METHOD;
        }

    case 6:
        switch (method[0])
        {
        case 'U':
            switch (method[5])
            {
            case 'K':
                return (memcmp(method, "UNLOCK", 6) == 0
                        ? SC_M_UNLOCK : UNKNOWN_METHOD);
            case 'E':
                return (memcmp(method, "UPDATE", 6) == 0
                        ? SC_M_UPDATE : UNKNOWN_METHOD);
            default:
                return UNKNOWN_METHOD;
            }
        case 'R':
            return (memcmp(method, "REPORT", 6) == 0
                    ? SC_M_REPORT : UNKNOWN_METHOD);
        case 'S':
            return (memcmp(method, "SEARCH", 6) == 0
                    ? SC_M_SEARCH : UNKNOWN_METHOD);
        case 'D':
            return (memcmp(method, "DELETE", 6) == 0
                    ? SC_M_DELETE : UNKNOWN_METHOD);
        default:
            return UNKNOWN_METHOD;
        }

    case 7:
        switch (method[1])
        {
        case 'P':
            return (memcmp(method, "OPTIONS", 7) == 0
                    ? SC_M_OPTIONS : UNKNOWN_METHOD);
        case 'H':
            return (memcmp(method, "CHECKIN", 7) == 0
                    ? SC_M_CHECKIN : UNKNOWN_METHOD);
        default:
            return UNKNOWN_METHOD;
        }

    case 8:
        switch (method[0])
        {
        case 'P':
            return (memcmp(method, "PROPFIND", 8) == 0
                    ? SC_M_PROPFIND : UNKNOWN_METHOD);
        case 'C':
            return (memcmp(method, "CHECKOUT", 8) == 0
                    ? SC_M_CHECKOUT : UNKNOWN_METHOD);
        default:
            return UNKNOWN_METHOD;
        }

    case 9:
        return (memcmp(method, "PROPPATCH", 9) == 0
                ? SC_M_PROPPATCH : UNKNOWN_METHOD);

    case 10:
        switch (method[0])
        {
        case 'U':
            return (memcmp(method, "UNCHECKOUT", 10) == 0
                    ? SC_M_UNCHECKOUT : UNKNOWN_METHOD);
        case 'M':
            return (memcmp(method, "MKACTIVITY", 10) == 0
                    ? SC_M_MKACTIVITY : UNKNOWN_METHOD);
        default:
            return UNKNOWN_METHOD;
        }

    case 11:
        return (memcmp(method, "MKWORKSPACE", 11) == 0
                ? SC_M_MKWORKSPACE : UNKNOWN_METHOD);

    case 15:
        return (memcmp(method, "VERSION-CONTROL", 15) == 0
                ? SC_M_VERSION_CONTROL : UNKNOWN_METHOD);

    case 16:
        return (memcmp(method, "BASELINE-CONTROL", 16) == 0
                ? SC_M_BASELINE_CONTROL : UNKNOWN_METHOD);

    default:
        return UNKNOWN_METHOD;
    }

    /* NOTREACHED */
}

static int sc_for_req_header(const char *header_name)
{
    char header[16];
    size_t len = strlen(header_name);
    const char *p = header_name;
    int i = 0;

    /* ACCEPT-LANGUAGE is the longest headeer
     * that is of interest.
     */
    if (len < 4 || len > 15)
        return UNKNOWN_METHOD;

    while (*p)
        header[i++] = toupper((unsigned char)*p++);
    header[i] = '\0';
    p = &header[1];

    switch (header[0]) {
        case 'A':
            if (memcmp(p, "CCEPT", 5) == 0) {
                if (!header[6])
                    return SC_ACCEPT;
                else if (header[6] == '-') {
                    p += 6;
                    if (memcmp(p, "CHARSET", 7) == 0)
                        return SC_ACCEPT_CHARSET;
                    else if (memcmp(p,  "ENCODING", 8) == 0)
                        return SC_ACCEPT_ENCODING;
                    else if (memcmp(p, "LANGUAGE", 8) == 0)
                        return SC_ACCEPT_LANGUAGE;
                    else
                        return UNKNOWN_METHOD;
                }
                else
                    return UNKNOWN_METHOD;
            }
            else if (memcmp(p, "UTHORIZATION", 12) == 0)
                return SC_AUTHORIZATION;
            else
                return UNKNOWN_METHOD;
        break;
        case 'C':
            if(memcmp(p, "OOKIE2", 6) == 0)
                return SC_COOKIE2;
            else if (memcmp(p, "OOKIE", 5) == 0)
                return SC_COOKIE;
            else if(memcmp(p, "ONNECTION", 9) == 0)
                return SC_CONNECTION;
            else if(memcmp(p, "ONTENT-TYPE", 11) == 0)
                return SC_CONTENT_TYPE;
            else if(memcmp(p, "ONTENT-LENGTH", 13) == 0)
                return SC_CONTENT_LENGTH;
            else
                return UNKNOWN_METHOD;
        break;
        case 'H':
            if(memcmp(p, "OST", 3) == 0)
                return SC_HOST;
            else
                return UNKNOWN_METHOD;
        break;
        case 'P':
            if(memcmp(p, "RAGMA", 5) == 0)
                return SC_PRAGMA;
            else
                return UNKNOWN_METHOD;
        break;
        case 'R':
            if(memcmp(p, "EFERER", 6) == 0)
                return SC_REFERER;
            else
                return UNKNOWN_METHOD;
        break;
        case 'U':
            if(memcmp(p, "SER-AGENT", 9) == 0)
                return SC_USER_AGENT;
            else
                return UNKNOWN_METHOD;
        break;
        default:
            return UNKNOWN_METHOD;
    }
    /* NOTREACHED */
}


/*
 * Message structure
 *
 *
AJPV13_REQUEST/AJPV14_REQUEST=
    request_prefix (1) (byte)
    method         (byte)
    protocol       (string)
    req_uri        (string)
    remote_addr    (string)
    remote_host    (string)
    server_name    (string)
    server_port    (short)
    is_ssl         (boolean)
    num_headers    (short)
    num_headers*(req_header_name header_value)

    ?context       (byte)(string)
    ?servlet_path  (byte)(string)
    ?remote_user   (byte)(string)
    ?auth_type     (byte)(string)
    ?query_string  (byte)(string)
    ?jvm_route     (byte)(string)
    ?ssl_cert      (byte)(string)
    ?ssl_cipher    (byte)(string)
    ?ssl_session   (byte)(string)
    ?ssl_key_size  (byte)(int)      via JkOptions +ForwardKeySize
    request_terminator (byte)
    ?body          content_length*(var binary)

 */

static int ajp_marshal_into_msgb(jk_msg_buf_t *msg,
                                 jk_ws_service_t *s,
                                 jk_logger_t *l, ajp_endpoint_t * ae)
{
    int method;
    unsigned int i;

    JK_TRACE_ENTER(l);

    if ((method = sc_for_req_method(s->method,
                                    strlen(s->method))) == UNKNOWN_METHOD)
        method = SC_M_JK_STORED;

    if (jk_b_append_byte(msg, JK_AJP13_FORWARD_REQUEST) ||
        jk_b_append_byte(msg, (unsigned char)method) ||
        jk_b_append_string(msg, s->protocol) ||
        jk_b_append_string(msg, s->req_uri) ||
        jk_b_append_string(msg, s->remote_addr) ||
        jk_b_append_string(msg, s->remote_host) ||
        jk_b_append_string(msg, s->server_name) ||
        jk_b_append_int(msg, (unsigned short)s->server_port) ||
        jk_b_append_byte(msg, (unsigned char)(s->is_ssl)) ||
        jk_b_append_int(msg, (unsigned short)(s->num_headers))) {

        jk_log(l, JK_LOG_ERROR,
               "failed appending the message begining");
        JK_TRACE_EXIT(l);
        return JK_FALSE;
    }

    for (i = 0; i < s->num_headers; i++) {
        int sc;

        if ((sc = sc_for_req_header(s->headers_names[i])) != UNKNOWN_METHOD) {
            if (jk_b_append_int(msg, (unsigned short)sc)) {
                jk_log(l, JK_LOG_ERROR,
                       "failed appending the header name");
                JK_TRACE_EXIT(l);
                return JK_FALSE;
            }
        }
        else {
            if (jk_b_append_string(msg, s->headers_names[i])) {
                jk_log(l, JK_LOG_ERROR,
                       "failed appending the header name");
                JK_TRACE_EXIT(l);
                return JK_FALSE;
            }
        }

        if (jk_b_append_string(msg, s->headers_values[i])) {
            jk_log(l, JK_LOG_ERROR,
                   "failed appending the header value");
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
    }

    if (s->secret) {
        if (jk_b_append_byte(msg, SC_A_SECRET) ||
            jk_b_append_string(msg, s->secret)) {
            jk_log(l, JK_LOG_ERROR,
                   "failed appending secret");
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
    }

    if (s->remote_user) {
        if (jk_b_append_byte(msg, SC_A_REMOTE_USER) ||
            jk_b_append_string(msg, s->remote_user)) {
            jk_log(l, JK_LOG_ERROR,
                   "failed appending the remote user");
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
    }
    if (s->auth_type) {
        if (jk_b_append_byte(msg, SC_A_AUTH_TYPE) ||
            jk_b_append_string(msg, s->auth_type)) {
            jk_log(l, JK_LOG_ERROR,
                   "failed appending the auth type");
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
    }
    if (s->query_string) {
        if (jk_b_append_byte(msg, SC_A_QUERY_STRING) ||
#ifdef AS400
            jk_b_append_asciistring(msg, s->query_string)) {
#else
            jk_b_append_string(msg, s->query_string)) {
#endif
            jk_log(l, JK_LOG_ERROR,
                   "failed appending the query string");
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
    }
    if (s->jvm_route) {
        if (jk_b_append_byte(msg, SC_A_JVM_ROUTE) ||
            jk_b_append_string(msg, s->jvm_route)) {
            jk_log(l, JK_LOG_ERROR,
                   "failed appending the jvm route");
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
    }
    if (s->ssl_cert_len) {
        if (jk_b_append_byte(msg, SC_A_SSL_CERT) ||
            jk_b_append_string(msg, s->ssl_cert)) {
            jk_log(l, JK_LOG_ERROR,
                   "failed appending the SSL certificates");
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
    }

    if (s->ssl_cipher) {
        if (jk_b_append_byte(msg, SC_A_SSL_CIPHER) ||
            jk_b_append_string(msg, s->ssl_cipher)) {
            jk_log(l, JK_LOG_ERROR,
                   "failed appending the SSL ciphers");
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
    }
    if (s->ssl_session) {
        if (jk_b_append_byte(msg, SC_A_SSL_SESSION) ||
            jk_b_append_string(msg, s->ssl_session)) {
            jk_log(l, JK_LOG_ERROR,
                   "failed appending the SSL session");
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
    }

    /*
     * ssl_key_size is required by Servlet 2.3 API
     * added support only in ajp14 mode
     * JFC removed: ae->proto == AJP14_PROTO
     */
    if (s->ssl_key_size != -1) {
        if (jk_b_append_byte(msg, SC_A_SSL_KEY_SIZE) ||
            jk_b_append_int(msg, (unsigned short)s->ssl_key_size)) {
            jk_log(l, JK_LOG_ERROR,
                   "failed appending the SSL key size");
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
    }

    /* If the method was unrecognized, encode it as an attribute */
    if (method == SC_M_JK_STORED) {
        if (JK_IS_DEBUG_LEVEL(l))
            jk_log(l, JK_LOG_DEBUG, "unknown method %s", s->method);
        if (jk_b_append_byte(msg, SC_A_STORED_METHOD) ||
            jk_b_append_string(msg, s->method)) {
            jk_log(l, JK_LOG_ERROR,
                   "failed appending the request method");
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
    }

    if (s->num_attributes > 0) {
        for (i = 0; i < s->num_attributes; i++) {
            if (jk_b_append_byte(msg, SC_A_REQ_ATTRIBUTE) ||
                jk_b_append_string(msg, s->attributes_names[i]) ||
                jk_b_append_string(msg, s->attributes_values[i])) {
                jk_log(l, JK_LOG_ERROR,
                       "failed appending attribute %s=%s",
                       s->attributes_names[i], s->attributes_values[i]);
                JK_TRACE_EXIT(l);
                return JK_FALSE;
            }
        }
    }

    if (jk_b_append_byte(msg, SC_A_ARE_DONE)) {
        jk_log(l, JK_LOG_ERROR,
               "failed appending the message end");
        JK_TRACE_EXIT(l);
        return JK_FALSE;
    }

    if (JK_IS_DEBUG_LEVEL(l))
        jk_log(l, JK_LOG_DEBUG, "ajp marshaling done");
    JK_TRACE_EXIT(l);
    return JK_TRUE;
}

/*
AJPV13_RESPONSE/AJPV14_RESPONSE:=
    response_prefix (2)
    status          (short)
    status_msg      (short)
    num_headers     (short)
    num_headers*(res_header_name header_value)
    *body_chunk
    terminator      boolean <! -- recycle connection or not  -->

req_header_name :=
    sc_req_header_name | (string)

res_header_name :=
    sc_res_header_name | (string)

header_value :=
    (string)

body_chunk :=
    length  (short)
    body    length*(var binary)

 */


static int ajp_unmarshal_response(jk_msg_buf_t *msg,
                                  jk_res_data_t * d,
                                  ajp_endpoint_t * ae, jk_logger_t *l)
{
    jk_pool_t *p = &ae->pool;

    d->status = jk_b_get_int(msg);
    JK_TRACE_ENTER(l);

    if (!d->status) {
        jk_log(l, JK_LOG_ERROR,
               "NULL status");
        JK_TRACE_EXIT(l);
        return JK_FALSE;
    }

    d->msg = (char *)jk_b_get_string(msg);
    if (d->msg) {
#if defined(AS400) || defined(_OSD_POSIX)
        jk_xlate_from_ascii(d->msg, strlen(d->msg));
#endif
    }

    if (JK_IS_DEBUG_LEVEL(l))
        jk_log(l, JK_LOG_DEBUG,
               "status = %d", d->status);

    d->num_headers = jk_b_get_int(msg);
    d->header_names = d->header_values = NULL;

    if (JK_IS_DEBUG_LEVEL(l))
        jk_log(l, JK_LOG_DEBUG,
               "Number of headers is = %d",
               d->num_headers);

    if (d->num_headers) {
        d->header_names = jk_pool_alloc(p, sizeof(char *) * d->num_headers);
        d->header_values = jk_pool_alloc(p, sizeof(char *) * d->num_headers);

        if (d->header_names && d->header_values) {
            unsigned int i;
            for (i = 0; i < d->num_headers; i++) {
                unsigned short name = jk_b_pget_int(msg, msg->pos);

                if ((name & 0XFF00) == 0XA000) {
                    jk_b_get_int(msg);
                    name = name & 0X00FF;
                    if (name <= SC_RES_HEADERS_NUM) {
                        d->header_names[i] =
                            (char *)long_res_header_for_sc(name);
                    }
                    else {
                        jk_log(l, JK_LOG_ERROR,
                               "No such sc (%d)", name);
                        JK_TRACE_EXIT(l);
                        return JK_FALSE;
                    }
                }
                else {
                    d->header_names[i] = (char *)jk_b_get_string(msg);
                    if (!d->header_names[i]) {
                        jk_log(l, JK_LOG_ERROR,
                               "NULL header name");
                        JK_TRACE_EXIT(l);
                        return JK_FALSE;
                    }
#if defined(AS400) || defined(_OSD_POSIX)
                    jk_xlate_from_ascii(d->header_names[i],
                                        strlen(d->header_names[i]));
#endif

                }

                d->header_values[i] = (char *)jk_b_get_string(msg);
                if (!d->header_values[i]) {
                    jk_log(l, JK_LOG_ERROR,
                           "NULL header value");
                    JK_TRACE_EXIT(l);
                    return JK_FALSE;
                }

#if defined(AS400) || defined(_OSD_POSIX)
                jk_xlate_from_ascii(d->header_values[i],
                                    strlen(d->header_values[i]));
#endif

                if (JK_IS_DEBUG_LEVEL(l))
                    jk_log(l, JK_LOG_DEBUG,
                           "Header[%d] [%s] = [%s]",
                           i, d->header_names[i], d->header_values[i]);
            }
        }
    }

    JK_TRACE_EXIT(l);
    return JK_TRUE;
}

/*
 * Reset the endpoint (clean buf and close socket)
 */

static void ajp_reset_endpoint(ajp_endpoint_t * ae, jk_logger_t *l)
{
    if (ae->sd > 0 && !ae->reuse) {
        jk_close_socket(ae->sd);
        if (JK_IS_DEBUG_LEVEL(l))
            jk_log(l, JK_LOG_DEBUG,
                   "reset socket with sd = %d", ae->sd);
        ae->sd = -1;
    }
    jk_reset_pool(&(ae->pool));
}

/*
 * Close the endpoint (close pool and close socket)
 */

void ajp_close_endpoint(ajp_endpoint_t * ae, jk_logger_t *l)
{
    JK_TRACE_ENTER(l);

    if (IS_VALID_SOCKET(ae->sd)) {
        jk_shutdown_socket(ae->sd);
        if (JK_IS_DEBUG_LEVEL(l))
            jk_log(l, JK_LOG_DEBUG,
                   "closed socket with sd = %d", ae->sd);
        ae->sd = JK_INVALID_SOCKET;
    }

    jk_close_pool(&(ae->pool));
    free(ae);
    JK_TRACE_EXIT(l);
}


/*
 * Try another connection from cache
 */

static void ajp_next_connection(ajp_endpoint_t *ae, jk_logger_t *l)
{
    int rc;
    ajp_worker_t *aw = ae->worker;
    int sock = ae->sd;

    /* Mark existing endpoint socket as closed */
    ae->sd = JK_INVALID_SOCKET;
    JK_ENTER_CS(&aw->cs, rc);
    if (rc) {
        unsigned int i;
        for (i = 0; i < aw->ep_cache_sz; i++) {
            /* Find cache slot with usable socket */
            if (aw->ep_cache[i] && IS_VALID_SOCKET(aw->ep_cache[i]->sd)) {
                ae->sd = aw->ep_cache[i]->sd;
                aw->ep_cache[i]->sd = JK_INVALID_SOCKET;
                break;
            }
        }
        JK_LEAVE_CS(&aw->cs, rc);
    }
    /* Close previous socket */
    if (IS_VALID_SOCKET(sock))
        jk_close_socket(sock);
}

/*
 * Wait input event on ajp_endpoint for timeout ms
 */
static int ajp_is_input_event(ajp_endpoint_t * ae, int timeout, jk_logger_t *l)
{
    fd_set rset;
    struct timeval tv;
    int rc;

    FD_ZERO(&rset);
    FD_SET(ae->sd, &rset);
    tv.tv_sec = timeout / 1000;
    tv.tv_usec = (timeout % 1000) * 1000;

    do {
        rc = select(ae->sd + 1, &rset, NULL, NULL, &tv);
    } while (rc < 0 && errno == EINTR);

    if (rc == 0) {
        /* Timeout. Set the errno to timeout */
#if defined(WIN32) || (defined(NETWARE) && defined(__NOVELL_LIBC__))
        errno = WSAETIMEDOUT - WSABASEERR;
#else
        errno = ETIMEDOUT;
#endif
        return JK_FALSE;
    }
    else if (rc < 0) {
        jk_log(l, JK_LOG_WARNING,
               "error during select err=%d", errno);
        return JK_FALSE;
    }
    else
        return JK_TRUE;
}


/*
 * Handle the CPING/CPONG initial query
 */
static int ajp_handle_cping_cpong(ajp_endpoint_t * ae, int timeout, jk_logger_t *l)
{
    int cmd;
    jk_msg_buf_t *msg;

    JK_TRACE_ENTER(l);
    msg = jk_b_new(&ae->pool);
    jk_b_set_buffer_size(msg, 16);      /* 16 is way too large but I'm lazy :-) */
    jk_b_reset(msg);
    jk_b_append_byte(msg, AJP13_CPING_REQUEST);

    /* Send CPing query */
    if (ajp_connection_tcp_send_message(ae, msg, l) != JK_TRUE) {
        jk_log(l, JK_LOG_INFO,
               "can't send cping query");
        JK_TRACE_EXIT(l);
        return JK_FALSE;
    }

    /* wait for Pong reply for timeout milliseconds
     */
    if (ajp_is_input_event(ae, timeout, l) == JK_FALSE) {
        jk_log(l, JK_LOG_INFO, "timeout in reply pong");
        JK_TRACE_EXIT(l);
        return JK_FALSE;
    }

    /* Read and check for Pong reply
     */
    if (ajp_connection_tcp_get_message(ae, msg, l) != JK_TRUE) {
        jk_log(l, JK_LOG_INFO,
               "awaited reply cpong, not received");
        JK_TRACE_EXIT(l);
        return JK_FALSE;
    }

    if ((cmd = jk_b_get_byte(msg)) != AJP13_CPONG_REPLY) {
        jk_log(l, JK_LOG_INFO,
               "awaited reply cpong, received %d instead",
               cmd);
        JK_TRACE_EXIT(l);
        return JK_FALSE;
    }

    JK_TRACE_EXIT(l);
    return JK_TRUE;
}

int ajp_connect_to_endpoint(ajp_endpoint_t * ae, jk_logger_t *l)
{
    char buf[32];
    int rc = JK_TRUE;

    JK_TRACE_ENTER(l);

    ae->sd = jk_open_socket(&ae->worker->worker_inet_addr,
                            ae->worker->keepalive,
                            ae->worker->socket_timeout,
                            ae->worker->socket_buf, l);
    if (IS_VALID_SOCKET(ae->sd)) {
        if (JK_IS_DEBUG_LEVEL(l)) {
            jk_log(l, JK_LOG_DEBUG,
                   "Connected socket %d to (%s)",
                   ae->sd,
                   jk_dump_hinfo(&ae->worker->worker_inet_addr, buf));
        }
        /* set last_access only if needed */
        if (ae->worker->cache_timeout > 0)
            ae->last_access = time(NULL);
        /* Check if we must execute a logon after the physical connect */
        if (ae->worker->logon != NULL) {
            rc = ae->worker->logon(ae, l);
            JK_TRACE_EXIT(l);
            return rc;
        }
        /* should we send a CPING to validate connection ? */
        if (ae->worker->connect_timeout > 0) {
            rc = ajp_handle_cping_cpong (ae,
                        ae->worker->connect_timeout, l);
            JK_TRACE_EXIT(l);
            return rc;
        }
        JK_TRACE_EXIT(l);
        return JK_TRUE;
    }

    jk_log(l, JK_LOG_INFO,
           "Failed opening socket to (%s) with (errno=%d)",
           jk_dump_hinfo(&ae->worker->worker_inet_addr, buf), errno);
    JK_TRACE_EXIT(l);
    return JK_FALSE;
}

/*
 * Send a message to endpoint, using corresponding PROTO HEADER
 */

int ajp_connection_tcp_send_message(ajp_endpoint_t * ae,
                                    jk_msg_buf_t *msg, jk_logger_t *l)
{
    int rc;

    JK_TRACE_ENTER(l);
    if (ae->proto == AJP13_PROTO) {
        jk_b_end(msg, AJP13_WS_HEADER);
        if (JK_IS_DEBUG_LEVEL(l))
            jk_dump_buff(l, JK_LOG_DEBUG, "sending to ajp13", msg);
    }
    else if (ae->proto == AJP14_PROTO) {
        jk_b_end(msg, AJP14_WS_HEADER);
        if (JK_IS_DEBUG_LEVEL(l))
            jk_dump_buff(l, JK_LOG_DEBUG, "sending to ajp14", msg);
    }
    else {
        jk_log(l, JK_LOG_ERROR,
               "unknown protocol %d, supported are AJP13/AJP14", ae->proto);
        JK_TRACE_EXIT(l);
        return JK_FATAL_ERROR;
    }

    if ((rc = jk_tcp_socket_sendfull(ae->sd, msg->buf,
                                     msg->len)) > 0) {
        ae->endpoint.wr += msg->len;
        JK_TRACE_EXIT(l);
        return JK_TRUE;
    }
    jk_log(l, JK_LOG_ERROR,
           "sendfull returned %d with errno=%d ", rc, errno);

    JK_TRACE_EXIT(l);
    return JK_FALSE;
}

/*
 * Receive a message from endpoint, checking PROTO HEADER
 */

int ajp_connection_tcp_get_message(ajp_endpoint_t * ae,
                                   jk_msg_buf_t *msg, jk_logger_t *l)
{
    unsigned char head[AJP_HEADER_LEN];
    int rc;
    int msglen;
    unsigned int header;
    char buf[32];

    JK_TRACE_ENTER(l);

    rc = jk_tcp_socket_recvfull(ae->sd, head, AJP_HEADER_LEN);

    if (rc < 0) {
        if (rc == JK_SOCKET_EOF) {
            jk_log(l, JK_LOG_INFO,
                   "Tomcat has forced a connection close for socket %d",
                   ae->sd);
            JK_TRACE_EXIT(l);
        }
        else {
            jk_log(l, JK_LOG_ERROR,
                   "Can't receive the response message from tomcat, "
                   "network problems or tomcat is down (%s), err=%d",
                   jk_dump_hinfo(&ae->worker->worker_inet_addr, buf), rc);
             JK_TRACE_EXIT(l);
        }
        return JK_FALSE;
    }
    ae->endpoint.rd += rc;
    header = ((unsigned int)head[0] << 8) | head[1];

    if (ae->proto == AJP13_PROTO) {
        if (header != AJP13_SW_HEADER) {

            if (header == AJP14_SW_HEADER) {
                jk_log(l, JK_LOG_ERROR,
                       "received AJP14 reply on an AJP13 connection from %s",
                       jk_dump_hinfo(&ae->worker->worker_inet_addr, buf));
            }
            else {
                jk_log(l, JK_LOG_ERROR,
                       "wrong message format 0x%04x from %s",
                       header, jk_dump_hinfo(&ae->worker->worker_inet_addr,
                                             buf));
            }
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
    }
    else if (ae->proto == AJP14_PROTO) {
        if (header != AJP14_SW_HEADER) {

            if (header == AJP13_SW_HEADER) {
                jk_log(l, JK_LOG_ERROR,
                       "received AJP13 reply on an AJP14 connection from %s",
                       jk_dump_hinfo(&ae->worker->worker_inet_addr, buf));
            }
            else {
                jk_log(l, JK_LOG_ERROR,
                       "wrong message format 0x%04x from %s",
                       header, jk_dump_hinfo(&ae->worker->worker_inet_addr,
                                             buf));
            }
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
    }

    msglen = ((head[2] & 0xff) << 8);
    msglen += (head[3] & 0xFF);

    if (msglen > msg->maxlen) {
        jk_log(l, JK_LOG_ERROR,
               "wrong message size %d %d from %s",
               msglen, msg->maxlen,
               jk_dump_hinfo(&ae->worker->worker_inet_addr, buf));
        JK_TRACE_EXIT(l);
        return JK_FALSE;
    }

    msg->len = msglen;
    msg->pos = 0;

    rc = jk_tcp_socket_recvfull(ae->sd, msg->buf, msglen);
    if (rc < 0) {
        jk_log(l, JK_LOG_ERROR,
               "ERROR: can't receive the response message from tomcat, "
               "network problems or tomcat (%s) is down %d",
               jk_dump_hinfo(&ae->worker->worker_inet_addr, buf), rc);
        JK_TRACE_EXIT(l);
        return JK_FALSE;
    }
    ae->endpoint.rd += rc;

    if (ae->proto == AJP13_PROTO) {
        if (JK_IS_DEBUG_LEVEL(l))
            jk_dump_buff(l, JK_LOG_DEBUG, "received from ajp13", msg);
    }
    else if (ae->proto == AJP14_PROTO) {
        if (JK_IS_DEBUG_LEVEL(l))
            jk_dump_buff(l, JK_LOG_DEBUG, "received from ajp14", msg);
    }
    JK_TRACE_EXIT(l);
    return JK_TRUE;
}

/*
 * Read all the data from the socket.
 *
 * Socket API doesn't guaranty that all the data will be kept in a
 * single read, so we must loop until all awaited data is received
 */

static int ajp_read_fully_from_server(jk_ws_service_t *s, jk_logger_t *l,
                                      unsigned char *buf, unsigned int len)
{
    unsigned int rdlen = 0;
    unsigned int padded_len = len;

    JK_TRACE_ENTER(l);
    if (s->is_chunked && s->no_more_chunks) {
        JK_TRACE_EXIT(l);
        return 0;
    }
    if (s->is_chunked) {
        /* Corner case: buf must be large enough to hold next
         * chunk size (if we're on or near a chunk border).
         * Pad the length to a reasonable value, otherwise the
         * read fails and the remaining chunks are tossed.
         */
        padded_len = (len < CHUNK_BUFFER_PAD) ? len : len - CHUNK_BUFFER_PAD;
    }

    while (rdlen < padded_len) {
        unsigned int this_time = 0;
        if (!s->read(s, buf + rdlen, len - rdlen, &this_time)) {
            /* Remote Client read failed. */
            JK_TRACE_EXIT(l);
            return JK_CLIENT_ERROR;
        }

        if (0 == this_time) {
            if (s->is_chunked) {
                s->no_more_chunks = 1;  /* read no more */
            }
            break;
        }
        rdlen += this_time;
    }

    return (int)rdlen;
}


/*
 * Read data from AJP13/AJP14 protocol
 * Returns -1 on error, else number of bytes read
 */

static int ajp_read_into_msg_buff(ajp_endpoint_t * ae,
                                  jk_ws_service_t *r,
                                  jk_msg_buf_t *msg, int len, jk_logger_t *l)
{
    unsigned char *read_buf = msg->buf;

    JK_TRACE_ENTER(l);
    jk_b_reset(msg);

    read_buf += AJP_HEADER_LEN; /* leave some space for the buffer headers */
    read_buf += AJP_HEADER_SZ_LEN;      /* leave some space for the read length */

    /* Pick the max size since we don't know the content_length */
    if (r->is_chunked && len == 0) {
        len = AJP13_MAX_SEND_BODY_SZ;
    }

    if ((len = ajp_read_fully_from_server(r, l, read_buf, len)) < 0) {
        jk_log(l, JK_LOG_INFO,
               "Receiving data from client failed. "
               "Connection aborted or network problems");
        JK_TRACE_EXIT(l);
        return JK_CLIENT_ERROR;
    }

    if (!r->is_chunked) {
        ae->left_bytes_to_send -= len;
    }

    if (len > 0) {
        /* Recipient recognizes empty packet as end of stream, not
           an empty body packet */
        if (0 != jk_b_append_int(msg, (unsigned short)len)) {
            jk_log(l, JK_LOG_INFO,
                   "Failed appending message length");
            JK_TRACE_EXIT(l);
            return JK_CLIENT_ERROR;
        }
    }

    msg->len += len;

    JK_TRACE_EXIT(l);
    return len;
}


/*
 * send request to Tomcat via Ajp13
 * - first try to find reuseable socket
 * - if no one available, try to connect
 * - send request, but send must be see as asynchronous,
 *   since send() call will return noerror about 95% of time
 *   Hopefully we'll get more information on next read.
 *
 * nb: reqmsg is the original request msg buffer
 *     repmsg is the reply msg buffer which could be scratched
 */
static int ajp_send_request(jk_endpoint_t *e,
                            jk_ws_service_t *s,
                            jk_logger_t *l,
                            ajp_endpoint_t * ae, ajp_operation_t * op)
{
    int err = 0;
    int postlen;

    JK_TRACE_ENTER(l);
    /* Up to now, we can recover */
    op->recoverable = JK_TRUE;

    /*
     * First try to reuse open connections...
     */
    while (IS_VALID_SOCKET(ae->sd)) {
        int rc = 0;
        err = 0;
        if (ae->worker->socket_timeout) {
            if (!jk_is_socket_connected(ae->sd)) {
                jk_log(l, JK_LOG_INFO,
                       "Socket %d is not connected any more (errno=%d)",
                       ae->sd, errno);
                jk_close_socket(ae->sd);
                ae->sd = JK_INVALID_SOCKET;
                err++;
            }
        }
        if (ae->worker->prepost_timeout != 0 && !err) {
            /* handle cping/cpong if prepost_timeout is set
             * If the socket is disconnected no need to handle
             * the cping/cpong
             */
            if (ajp_handle_cping_cpong(ae, ae->worker->prepost_timeout, l) ==
                JK_FALSE)
                err++;
        }

        /* If we got an error or can't send data, then try to get a pooled
         * connection and try again.  If we are succesful, break out of this
         * loop. */
        if (err ||
            ((rc = ajp_connection_tcp_send_message(ae, op->request, l)) != JK_TRUE)) {
            if (rc != JK_FATAL_ERROR) {
                jk_log(l, JK_LOG_INFO,
                       "Error sending request. Will try another pooled connection");
                ajp_next_connection(ae, l);
            }
            else {
                op->recoverable = JK_FALSE;
                jk_log(l, JK_LOG_INFO,
                       "Error sending request. Unrecoverable operation");
                JK_TRACE_EXIT(l);
                return JK_FALSE;
            }
        }
        else
            break;
    }

    /*
     * If we failed to reuse a connection, try to reconnect.
     */
    if (!IS_VALID_SOCKET(ae->sd)) {
        if (err) {
            /* XXX: If err is set, the tomcat is either dead or disconnected */
            jk_log(l, JK_LOG_INFO,
                   "All endpoints are disconnected or dead");
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
        /* Connect to the backend.
         * This can be either uninitalized connection or a reconnect.
         */
        if (ajp_connect_to_endpoint(ae, l) == JK_TRUE) {
            /*
             * After we are connected, each error that we are going to
             * have is probably unrecoverable
             */
            if (ajp_connection_tcp_send_message(ae, op->request, l) != JK_TRUE) {
                /* Close the socket if unable to send request */
                jk_close_socket(ae->sd);
                ae->sd = -1;
                jk_log(l, JK_LOG_INFO,
                       "Error sending request on a fresh connection");
                JK_TRACE_EXIT(l);
                return JK_FALSE;
            }
        }
        else {
            /* Close the socket if unable to connect */
            jk_close_socket(ae->sd);
            ae->sd = JK_INVALID_SOCKET;
            jk_log(l, JK_LOG_INFO,
                   "Error connecting to the backend server.");
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
    }

    /*
     * From now on an error means that we have an internal server error
     * or Tomcat crashed. In any case we cannot recover this.
     */

    if (JK_IS_DEBUG_LEVEL(l))
        jk_log(l, JK_LOG_DEBUG,
               "request body to send %d - request body to resend %d",
               ae->left_bytes_to_send, op->reply->len - AJP_HEADER_LEN);

    /*
     * POST recovery job is done here and will work when data to
     * POST are less than 8k, since it's the maximum size of op-post buffer.
     * We send here the first part of data which was sent previously to the
     * remote Tomcat
     */

    /* Did we have something to resend (ie the op-post has been feeded previously */

    postlen = op->post->len;
    if (postlen > AJP_HEADER_LEN) {
        if (ajp_connection_tcp_send_message(ae, op->post, l) != JK_TRUE) {
            /* Close the socket if unable to send request */
            jk_close_socket(ae->sd);
            ae->sd = JK_INVALID_SOCKET;
            jk_log(l, JK_LOG_ERROR, "Error resending request body (%d)",
                   postlen);
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
        else {
            if (JK_IS_DEBUG_LEVEL(l))
                jk_log(l, JK_LOG_DEBUG, "Resent the request body (%d)",
                       postlen);
        }
    }
    else if (s->reco_status == RECO_FILLED) {
        /* Recovery in LB MODE */
        postlen = s->reco_buf->len;

        if (postlen > AJP_HEADER_LEN) {
            if (ajp_connection_tcp_send_message(ae, s->reco_buf, l) != JK_TRUE) {
                /* Close the socket if unable to send request */
                jk_close_socket(ae->sd);
                ae->sd = -1;
                jk_log(l, JK_LOG_ERROR,
                       "Error resending request body (lb mode) (%d)",
                       postlen);
                JK_TRACE_EXIT(l);
                return JK_FALSE;
            }
        }
        else {
            if (JK_IS_DEBUG_LEVEL(l))
                jk_log(l, JK_LOG_DEBUG,
                       "Resent the request body (lb mode) (%d)", postlen);
        }
    }
    else {
        /* We never sent any POST data and we check if we have to send at
         * least one block of data (max 8k). These data will be kept in reply
         * for resend if the remote Tomcat is down, a fact we will learn only
         * doing a read (not yet)
         */
        /* || s->is_chunked - this can't be done here. The original protocol
           sends the first chunk of post data ( based on Content-Length ),
           and that's what the java side expects.
           Sending this data for chunked would break other ajp13 servers.

           Note that chunking will continue to work - using the normal read.
         */

        if (ae->left_bytes_to_send > 0) {
            int len = ae->left_bytes_to_send;
            if (len > AJP13_MAX_SEND_BODY_SZ) {
                len = AJP13_MAX_SEND_BODY_SZ;
            }
            if ((len = ajp_read_into_msg_buff(ae, s, op->post, len, l)) < 0) {
                /* the browser stop sending data, no need to recover */
                op->recoverable = JK_FALSE;
                JK_TRACE_EXIT(l);
                return len;
            }

            /* If a RECOVERY buffer is available in LB mode, fill it */
            if (s->reco_status == RECO_INITED) {
                jk_b_copy(op->post, s->reco_buf);
                s->reco_status = RECO_FILLED;
            }

            s->content_read = len;
            if (ajp_connection_tcp_send_message(ae, op->post, l) != JK_TRUE) {
                /* Close the socket if unable to send request */
                jk_close_socket(ae->sd);
                ae->sd = -1;
                jk_log(l, JK_LOG_ERROR, "Error sending request body");
                JK_TRACE_EXIT(l);
                return JK_FALSE;
            }
        }
    }
    JK_TRACE_EXIT(l);
    return (JK_TRUE);
}

/*
 * What to do with incoming data (dispatcher)
 */

static int ajp_process_callback(jk_msg_buf_t *msg,
                                jk_msg_buf_t *pmsg,
                                ajp_endpoint_t * ae,
                                jk_ws_service_t *r, jk_logger_t *l)
{
    int code = (int)jk_b_get_byte(msg);

    JK_TRACE_ENTER(l);
    switch (code) {
    case JK_AJP13_SEND_HEADERS:
        {
            jk_res_data_t res;
            if (!ajp_unmarshal_response(msg, &res, ae, l)) {
                jk_log(l, JK_LOG_ERROR,
                       "ajp_unmarshal_response failed");
                JK_TRACE_EXIT(l);
                return JK_AJP13_ERROR;
            }
            r->start_response(r, res.status, res.msg,
                              (const char *const *)res.header_names,
                              (const char *const *)res.header_values,
                              res.num_headers);
        }
        return JK_AJP13_SEND_HEADERS;

    case JK_AJP13_SEND_BODY_CHUNK:
        {
            unsigned int len = (unsigned int)jk_b_get_int(msg);
            /*
             * Do a sanity check on len to prevent write reading beyond buffer
             * boundaries and thus revealing possible sensitive memory
             * contents to the client.
             * len cannot be larger than msg->len - 3 because the ajp message
             * contains the magic byte for JK_AJP13_SEND_BODY_CHUNK (1 byte)
             * and the length of the chunk (2 bytes). The remaining part of
             * the message is the chunk.
             */
            if (len > (unsigned int)(msg->len - 3)) {
                jk_log(l, JK_LOG_ERROR,
                       "Chunk length too large. Length of AJP message is %i,"
                       " chunk length is %i.", msg->len, len);
                JK_TRACE_EXIT(l);
                return JK_INTERNAL_ERROR;
            }
            if (!r->write(r, msg->buf + msg->pos, len)) {
                jk_log(l, JK_LOG_INFO,
                       "Connection aborted or network problems");
                JK_TRACE_EXIT(l);
                return JK_CLIENT_ERROR;
            }
            if (r->flush && r->flush_packets)
                r->flush(r);
        }
        break;

    case JK_AJP13_GET_BODY_CHUNK:
        {
            int len = (int)jk_b_get_int(msg);

            if (len < 0) {
                len = 0;
            }
            if (len > AJP13_MAX_SEND_BODY_SZ) {
                len = AJP13_MAX_SEND_BODY_SZ;
            }
            if ((unsigned int)len > ae->left_bytes_to_send) {
                len = ae->left_bytes_to_send;
            }

            /* the right place to add file storage for upload */
            if ((len = ajp_read_into_msg_buff(ae, r, pmsg, len, l)) >= 0) {
                r->content_read += len;
                JK_TRACE_EXIT(l);
                return JK_AJP13_HAS_RESPONSE;
            }

            jk_log(l, JK_LOG_INFO,
                   "Connection aborted or network problems");

            JK_TRACE_EXIT(l);
            return JK_CLIENT_ERROR;
        }
        break;

    case JK_AJP13_END_RESPONSE:
        ae->reuse = (int)jk_b_get_byte(msg);
        if (!ae->reuse) {
            /*
                * Strange protocol error.
                */
            jk_log(l, JK_LOG_INFO, " Protocol error: Reuse is set to false");
        }
        /* Flush after the last write */
        if (r->flush && !r->flush_packets)
            r->flush(r);

        /* Reuse in all cases */
        ae->reuse = JK_TRUE;
        JK_TRACE_EXIT(l);
        return JK_AJP13_END_RESPONSE;
        break;

    default:
        jk_log(l, JK_LOG_ERROR,
               "Invalid code: %d", code);
        JK_TRACE_EXIT(l);
        return JK_AJP13_ERROR;
    }

    JK_TRACE_EXIT(l);
    return JK_AJP13_NO_RESPONSE;
}

/*
 * get replies from Tomcat via Ajp13/Ajp14
 * We will know only at read time if the remote host closed
 * the connection (half-closed state - FIN-WAIT2). In that case
 * we must close our side of the socket and abort emission.
 * We will need another connection to send the request
 * There is need of refactoring here since we mix
 * reply reception (tomcat -> apache) and request send (apache -> tomcat)
 * and everything using the same buffer (repmsg)
 * ajp13/ajp14 is async but handling read/send this way prevent nice recovery
 * In fact if tomcat link is broken during upload (browser -> apache -> tomcat)
 * we'll loose data and we'll have to abort the whole request.
 */
static int ajp_get_reply(jk_endpoint_t *e,
                         jk_ws_service_t *s,
                         jk_logger_t *l,
                         ajp_endpoint_t * p, ajp_operation_t * op)
{
    /* Don't get header from tomcat yet */
    int headeratclient = JK_FALSE;

    JK_TRACE_ENTER(l);

    /* Start read all reply message */
    while (1) {
        int rc = 0;

        /* If we set a reply timeout, check it something is available */
        if (p->worker->reply_timeout != 0) {
            if (ajp_is_input_event(p, p->worker->reply_timeout, l) ==
                JK_FALSE) {
                jk_log(l, JK_LOG_ERROR,
                       "Timeout with waiting reply from tomcat. "
                       "Tomcat is down, stopped or network problems.");
                if (headeratclient == JK_FALSE) {
                    if (p->worker->recovery_opts & RECOVER_ABORT_IF_TCGETREQUEST)
                        op->recoverable = JK_FALSE;
                }
                else {
                    if (p->worker->recovery_opts & RECOVER_ABORT_IF_TCSENDHEADER)
                        op->recoverable = JK_FALSE;
                }

                JK_TRACE_EXIT(l);
                return JK_FALSE;
            }
        }

        if (!ajp_connection_tcp_get_message(p, op->reply, l)) {
            /* we just can't recover, unset recover flag */
            if (headeratclient == JK_FALSE) {
                jk_log(l, JK_LOG_ERROR,
                       "Tomcat is down or refused connection. "
                       "No response has been sent to the client (yet)");
                /*
                 * communication with tomcat has been interrupted BEFORE
                 * headers have been sent to the client.
                 * DISCUSSION: As we suppose that tomcat has already started
                 * to process the query we think it's unrecoverable (and we
                 * should not retry or switch to another tomcat in the
                 * cluster).
                 */

                /*
                 * We mark it unrecoverable if recovery_opts set to RECOVER_ABORT_IF_TCGETREQUEST
                 */
                if (p->worker->recovery_opts & RECOVER_ABORT_IF_TCGETREQUEST)
                    op->recoverable = JK_FALSE;
                /*
                 * we want to display the webservers error page, therefore
                 * we return JK_FALSE
                 */
                JK_TRACE_EXIT(l);
                return JK_FALSE;
            }
            else {
                jk_log(l, JK_LOG_ERROR,
                       "Tomcat is down or network problems. "
                       "Part of the response has already been sent to the client");

                /* communication with tomcat has been interrupted AFTER
                 * headers have been sent to the client.
                 * headers (and maybe parts of the body) have already been
                 * sent, therefore the response is "complete" in a sense
                 * that nobody should append any data, especially no 500 error
                 * page of the webserver!
                 *
                 * BUT if you retrun JK_TRUE you have a 200 (OK) code in your
                 * in your apache access.log instead of a 500 (Error).
                 * Therefore return FALSE/FALSE
                 * return JK_TRUE;
                 */

                /*
                 * We mark it unrecoverable if recovery_opts set to RECOVER_ABORT_IF_TCSENDHEADER
                 */
                if (p->worker->recovery_opts & RECOVER_ABORT_IF_TCSENDHEADER)
                    op->recoverable = JK_FALSE;

                JK_TRACE_EXIT(l);
                return JK_FALSE;
            }
        }

        rc = ajp_process_callback(op->reply, op->post, p, s, l);

        /* no more data to be sent, fine we have finish here */
        if (JK_AJP13_END_RESPONSE == rc) {
            JK_TRACE_EXIT(l);
            return JK_TRUE;
        }
        else if (JK_AJP13_SEND_HEADERS == rc) {
            headeratclient = JK_TRUE;
        }
        else if (JK_AJP13_HAS_RESPONSE == rc) {
            /*
             * in upload-mode there is no second chance since
             * we may have allready sent part of the uploaded data
             * to Tomcat.
             * In this case if Tomcat connection is broken we must
             * abort request and indicate error.
             * A possible work-around could be to store the uploaded
             * data to file and replay for it
             */
            op->recoverable = JK_FALSE;
            rc = ajp_connection_tcp_send_message(p, op->post, l);
            if (rc < 0) {
                jk_log(l, JK_LOG_ERROR,
                       "Tomcat is down or network problems.", rc);
                JK_TRACE_EXIT(l);
                return JK_FALSE;
            }
        }
        else if (JK_FATAL_ERROR == rc) {
            /*
             * we won't be able to gracefully recover from this so
             * set recoverable to false and get out.
             */
            op->recoverable = JK_FALSE;
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
        else if (JK_CLIENT_ERROR == rc) {
            /*
             * Client has stop talking to us, so get out.
             * We assume this isn't our fault, so just a normal exit.
             * In most (all?)  cases, the ajp13_endpoint::reuse will still be
             * false here, so this will be functionally the same as an
             * un-recoverable error.  We just won't log it as such.
             */
            JK_TRACE_EXIT(l);
            return JK_CLIENT_ERROR;
        }
        else if (rc < 0) {
            JK_TRACE_EXIT(l);
            return (JK_FALSE);  /* XXX error */
        }
    }
    /* XXX: Not reached? */
    JK_TRACE_EXIT(l);
    return JK_FALSE;
}

/*
 * service is now splitted in ajp_send_request and ajp_get_reply
 * much more easier to do errors recovery
 *
 * We serve here the request, using AJP13/AJP14 (e->proto)
 *
 */
static int JK_METHOD ajp_service(jk_endpoint_t *e,
                                 jk_ws_service_t *s,
                                 jk_logger_t *l, int *is_error)
{
    int i, err;
    ajp_operation_t oper;
    ajp_operation_t *op = &oper;

    JK_TRACE_ENTER(l);

    if (is_error)
        *is_error = JK_HTTP_SERVER_ERROR;

    if (e && e->endpoint_private && s && is_error) {
        ajp_endpoint_t *p = e->endpoint_private;
        op->request = jk_b_new(&(p->pool));
        jk_b_set_buffer_size(op->request, DEF_BUFFER_SZ);
        jk_b_reset(op->request);

        op->reply = jk_b_new(&(p->pool));
        jk_b_set_buffer_size(op->reply, DEF_BUFFER_SZ);
        jk_b_reset(op->reply);

        op->post = jk_b_new(&(p->pool));
        jk_b_set_buffer_size(op->post, DEF_BUFFER_SZ);
        jk_b_reset(op->post);

        op->recoverable = JK_TRUE;
        op->uploadfd = -1;      /* not yet used, later ;) */

        p->left_bytes_to_send = s->content_length;
        p->reuse = JK_FALSE;

        s->secret = p->worker->secret;

        /*
         * We get here initial request (in reqmsg)
         */
        if (!ajp_marshal_into_msgb(op->request, s, l, p)) {
            *is_error = JK_REQUEST_TOO_LARGE;
            jk_log(l, JK_LOG_INFO,
                    "Creating AJP message failed, "
                    "without recovery");
            JK_TRACE_EXIT(l);
            return JK_CLIENT_ERROR;
        }

        if (JK_IS_DEBUG_LEVEL(l)) {
            jk_log(l, JK_LOG_DEBUG, "processing %s with %d retries",
                   p->worker->name, p->worker->worker.retries);
        }
        /*
         * JK_RETRIES could be replaced by the number of workers in
         * a load-balancing configuration
         */
        for (i = 0; i < p->worker->worker.retries; i++) {
            /*
             * We're using reqmsg which hold initial request
             * if Tomcat is stopped or restarted, we will pass reqmsg
             * to next valid tomcat.
             */
            err = ajp_send_request(e, s, l, p, op);
            if (err == JK_TRUE) {

                /* If we have the no recoverable error, it's probably because
                 * the sender (browser) stopped sending data before the end
                 * (certainly in a big post)
                 */
                if (!op->recoverable) {
                    *is_error = JK_HTTP_SERVER_ERROR;
                    jk_log(l, JK_LOG_ERROR,
                           "sending request to tomcat failed "
                           "without recovery in send loop %d", i);
                    JK_TRACE_EXIT(l);
                    return JK_FALSE;
                }

                /* Up to there we can recover */

                err = ajp_get_reply(e, s, l, p, op);
                if (err == JK_TRUE) {
                    *is_error = JK_HTTP_OK;
                    /* Done with the request */
                    JK_TRACE_EXIT(l);
                    return JK_TRUE;
                }

                if (err != JK_CLIENT_ERROR) {
                    /* if we can't get reply, check if no recover flag was set
                     * if is_recoverable_error is cleared, we have started
                     * receiving upload data and we must consider that
                     * operation is no more recoverable
                     */
                    if (!op->recoverable) {
                        *is_error = JK_HTTP_BAD_GATEWAY;
                        jk_log(l, JK_LOG_ERROR,
                               "receiving reply from tomcat failed "
                               "without recovery in send loop %d", i);
                        JK_TRACE_EXIT(l);
                        return JK_FALSE;
                    }
                    jk_log(l, JK_LOG_INFO,
                           "Receiving from tomcat failed, "
                           "recoverable operation attempt=%d", i);
                    /* Check for custom retries */
                    if (i >= JK_RETRIES) {
                        jk_sleep_def();
                    }
                }
                else {
                    *is_error = JK_HTTP_BAD_REQUEST;
                    jk_log(l, JK_LOG_INFO,
                           "Receiving from tomcat failed, "
                           "because of client error "
                           "without recovery in send loop %d", i);
                    JK_TRACE_EXIT(l);
                    return JK_CLIENT_ERROR;
                }
            }
            if (err == JK_CLIENT_ERROR) {
                *is_error = JK_HTTP_BAD_REQUEST;
                if (p->worker->recovery_opts & RECOVER_ABORT_IF_CLIENTERROR) {
                    /* Mark the endpoint for shutdown */
                    p->reuse = JK_FALSE;
                }
                jk_log(l, JK_LOG_INFO,
                       "Sending request to tomcat failed, "
                       "because of client error "
                       "without recovery in send loop %d", i);
                JK_TRACE_EXIT(l);
                return JK_CLIENT_ERROR;
            }
            else {
                jk_log(l, JK_LOG_INFO,
                       "Sending request to tomcat failed,  "
                       "recoverable operation attempt=%d", i + 1);
            }
            /* Get another connection from the pool and try again.
             * Note: All sockets are probably closed already.
             */
            ajp_next_connection(p, l);
        }
        *is_error = JK_HTTP_SERVER_BUSY;
        /* Log the error only once per failed request. */
        jk_log(l, JK_LOG_ERROR,
               "Error connecting to tomcat. Tomcat is probably not started "
               "or is listening on the wrong port. worker=%s failed",
               p->worker->name);

    }
    else {
        jk_log(l, JK_LOG_ERROR, "end of service with error");
    }

    JK_TRACE_EXIT(l);
    return JK_FALSE;
}

/*
 * Validate the worker (ajp13/ajp14)
 */

int ajp_validate(jk_worker_t *pThis,
                 jk_map_t *props,
                 jk_worker_env_t *we, jk_logger_t *l, int proto)
{
    int port;
    const char *host;

    JK_TRACE_ENTER(l);

    if (proto == AJP13_PROTO) {
        port = AJP13_DEF_PORT;
        host = AJP13_DEF_HOST;
    }
    else if (proto == AJP14_PROTO) {
        port = AJP14_DEF_PORT;
        host = AJP14_DEF_HOST;
    }
    else {
        jk_log(l, JK_LOG_ERROR,
               "unknown protocol %d", proto);
        JK_TRACE_EXIT(l);
        return JK_FALSE;
    }

    if (pThis && pThis->worker_private) {
        ajp_worker_t *p = pThis->worker_private;
        p->port = jk_get_worker_port(props, p->name, port);
        p->host = jk_get_worker_host(props, p->name, host);

        if (JK_IS_DEBUG_LEVEL(l))
            jk_log(l, JK_LOG_DEBUG,
                   "worker %s contact is '%s:%d'",
                   p->name, p->host, p->port);

        if (p->port > 1024) {
            if (jk_resolve(p->host, p->port, &p->worker_inet_addr)) {
                JK_TRACE_EXIT(l);
                return JK_TRUE;
            }
            jk_log(l, JK_LOG_ERROR,
                   "can't resolve tomcat address %s", host);
        }
        jk_log(l, JK_LOG_ERROR,
               "invalid host and port %s %d",
               ((p->host == NULL) ? "NULL" : p->host), p->port);
    }
    else {
        JK_LOG_NULL_PARAMS(l);
    }

    JK_TRACE_EXIT(l);
    return JK_FALSE;
}

static int ajp_create_endpoint_cache(ajp_worker_t *p, int proto, jk_logger_t *l)
{
    unsigned int i;
    time_t now = time(NULL);

    JK_TRACE_ENTER(l);
    p->ep_cache = (ajp_endpoint_t **)calloc(1, sizeof(ajp_endpoint_t *) *
                                            p->ep_cache_sz);
    if (!p->ep_cache) {
        JK_TRACE_EXIT(l);
        return JK_FALSE;
    }
    if (JK_IS_DEBUG_LEVEL(l))
        jk_log(l, JK_LOG_DEBUG,
                "setting connection pool size to %u with min %u",
                p->ep_cache_sz, p->ep_mincache_sz);
        for (i = 0; i < p->ep_cache_sz; i++) {
            p->ep_cache[i] = (ajp_endpoint_t *)calloc(1, sizeof(ajp_endpoint_t));
            if (!p->ep_cache[i]) {
                jk_log(l, JK_LOG_ERROR,
                        "allocating endpoint slot %d errno=%d",
                        i, errno);
                JK_TRACE_EXIT(l);
                return JK_FALSE;
            }
            p->ep_cache[i]->sd = JK_INVALID_SOCKET;
            p->ep_cache[i]->reuse = JK_FALSE;
            p->ep_cache[i]->last_access = now;
            jk_open_pool(&(p->ep_cache[i]->pool), p->ep_cache[i]->buf,
                         sizeof(p->ep_cache[i]->buf));
            p->ep_cache[i]->worker = p;
            p->ep_cache[i]->endpoint.endpoint_private = p->ep_cache[i];
            p->ep_cache[i]->proto = proto;
            p->ep_cache[i]->endpoint.service = ajp_service;
            p->ep_cache[i]->endpoint.done    = ajp_done;
        }

    JK_TRACE_EXIT(l);
    return JK_TRUE;
}

int ajp_init(jk_worker_t *pThis,
             jk_map_t *props, jk_worker_env_t *we, jk_logger_t *l, int proto)
{
    int rc = JK_FALSE;
    int cache;
    /*
     * start the connection cache
     */
    JK_TRACE_ENTER(l);

    cache = jk_get_worker_def_cache_size(proto);

    if (pThis && pThis->worker_private) {
        ajp_worker_t *p = pThis->worker_private;
        p->ep_cache_sz = jk_get_worker_cache_size(props, p->name, cache);
        p->ep_mincache_sz = jk_get_worker_cache_size_min(props, p->name,
                                                         cache / 2);
        p->socket_timeout =
            jk_get_worker_socket_timeout(props, p->name, AJP_DEF_SOCKET_TIMEOUT);

        p->socket_buf =
            jk_get_worker_socket_buffer(props, p->name, 8192);

        p->keepalive =
            jk_get_worker_socket_keepalive(props, p->name, JK_FALSE);

        p->cache_timeout =
            jk_get_worker_cache_timeout(props, p->name,
                                        AJP_DEF_CACHE_TIMEOUT);

        p->connect_timeout =
            jk_get_worker_connect_timeout(props, p->name,
                                          AJP_DEF_CONNECT_TIMEOUT);

        p->reply_timeout =
            jk_get_worker_reply_timeout(props, p->name,
                                        AJP_DEF_REPLY_TIMEOUT);

        p->prepost_timeout =
            jk_get_worker_prepost_timeout(props, p->name,
                                          AJP_DEF_PREPOST_TIMEOUT);

        p->recovery_opts =
            jk_get_worker_recovery_opts(props, p->name,
                                        AJP_DEF_RECOVERY_OPTS);

        pThis->retries =
            jk_get_worker_retries(props, p->name,
                                  JK_RETRIES);
        if (pThis->retries < 1) {
            jk_log(l, JK_LOG_INFO,
                   "number of retries must be grater then 1. Setting to default=%d",
                   JK_RETRIES);
            pThis->retries = JK_RETRIES;
        }

        if (JK_IS_DEBUG_LEVEL(l)) {

            jk_log(l, JK_LOG_DEBUG,
                   "setting endpoint options:",
                   p->keepalive);
            jk_log(l, JK_LOG_DEBUG,
                   "keepalive:        %d",
                   p->keepalive);

            jk_log(l, JK_LOG_DEBUG,
                   "timeout:          %d",
                   p->socket_timeout);

            jk_log(l, JK_LOG_DEBUG,
                   "buffer size:      %d",
                   p->socket_buf);

            jk_log(l, JK_LOG_DEBUG,
                   "pool timeout:     %d",
                   p->cache_timeout);

            jk_log(l, JK_LOG_DEBUG,
                   "connect timeout:  %d",
                   p->connect_timeout);

            jk_log(l, JK_LOG_DEBUG,
                   "reply timeout:    %d",
                   p->reply_timeout);

            jk_log(l, JK_LOG_DEBUG,
                   "prepost timeout:  %d",
                   p->prepost_timeout);

            jk_log(l, JK_LOG_DEBUG,
                   "recovery options: %d",
                   p->recovery_opts);

            jk_log(l, JK_LOG_DEBUG,
                   "retries:          %d",
                    pThis->retries);
        }
        /*
         *  Need to initialize secret here since we could return from inside
         *  of the following loop
         */

        p->secret = jk_get_worker_secret(props, p->name);
        /* Initialize cache slots */
        JK_INIT_CS(&(p->cs), rc);
        if (!rc) {
            jk_log(l, JK_LOG_ERROR,
                   "creating thread lock errno=%d",
                   errno);
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
        if (!ajp_create_endpoint_cache(p, proto, l)) {
            jk_log(l, JK_LOG_ERROR,
                   "allocating connection pool of size %u",
                   p->ep_cache_sz);
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }
        rc = JK_TRUE;
    }
    else {
        JK_LOG_NULL_PARAMS(l);
    }

    JK_TRACE_EXIT(l);
    return rc;
}

int ajp_destroy(jk_worker_t **pThis, jk_logger_t *l, int proto)
{
    JK_TRACE_ENTER(l);

    if (pThis && *pThis && (*pThis)->worker_private) {
        unsigned int i;
        ajp_worker_t *aw = (*pThis)->worker_private;

        if (JK_IS_DEBUG_LEVEL(l))
            jk_log(l, JK_LOG_DEBUG,
                   "up to %u endpoints to close",
                   aw->ep_cache_sz);

        for (i = 0; i < aw->ep_cache_sz; i++) {
            if (aw->ep_cache[i])
                ajp_close_endpoint(aw->ep_cache[i], l);
        }
        free(aw->ep_cache);
        JK_DELETE_CS(&(aw->cs), i);

        if (aw->login) {
             /* take care of removing previously allocated data */
            if (aw->login->servlet_engine_name)
                free(aw->login->servlet_engine_name);

            free(aw->login);
            aw->login = NULL;
        }

        free(aw);
        JK_TRACE_EXIT(l);
        return JK_TRUE;
    }

    JK_LOG_NULL_PARAMS(l);
    JK_TRACE_EXIT(l);
    return JK_FALSE;
}

int JK_METHOD ajp_done(jk_endpoint_t **e, jk_logger_t *l)
{
    JK_TRACE_ENTER(l);
    if (e && *e && (*e)->endpoint_private) {
        ajp_endpoint_t *p = (*e)->endpoint_private;
        int rc;
        ajp_worker_t *w = p->worker;

        JK_ENTER_CS(&w->cs, rc);
        if (rc) {
            int i, sock = JK_INVALID_SOCKET;

            if (p->sd > 0 && !p->reuse) {
                sock  = p->sd;
                p->sd = JK_INVALID_SOCKET;
            }
            for(i = w->ep_cache_sz - 1; i >= 0; i--) {
                if (w->ep_cache[i] == NULL) {
                    w->ep_cache[i] = p;
                    break;
                }
            }
            ajp_reset_endpoint(p, l);
            *e = NULL;
            /* set last_access only if needed */
            if (w->cache_timeout > 0)
                p->last_access = time(NULL);
            JK_LEAVE_CS(&w->cs, rc);
            if (IS_VALID_SOCKET(sock))
                jk_shutdown_socket(sock);
            if (i >= 0) {
                if (JK_IS_DEBUG_LEVEL(l))
                    jk_log(l, JK_LOG_DEBUG,
                            "recycling connection pool slot=%u for worker %s",
                            i, p->worker->name);
                JK_TRACE_EXIT(l);
                return JK_TRUE;
            }
            /* XXX: This should never hapen because
             * there is always free empty cache slot
             */
            jk_log(l, JK_LOG_ERROR,
                    "could not find empty connection pool slot from %u for worker %s",
                    w->ep_cache_sz, w->name);
            JK_TRACE_EXIT(l);
            return JK_FALSE;
        }

        jk_log(l, JK_LOG_ERROR,
               "locking thread with errno=%d", errno);
        JK_TRACE_EXIT(l);
        return JK_FALSE;
    }

    JK_LOG_NULL_PARAMS(l);
    JK_TRACE_EXIT(l);
    return JK_FALSE;
}

int ajp_get_endpoint(jk_worker_t *pThis,
                     jk_endpoint_t **je, jk_logger_t *l, int proto)
{
    JK_TRACE_ENTER(l);

    if (pThis && pThis->worker_private && je) {
        ajp_worker_t *aw = pThis->worker_private;
        ajp_endpoint_t *ae = NULL;
        time_t now = 0;
        int rc;
        /* Obtain current time only if needed */
        if (aw->cache_timeout > 0)
            now = time(NULL);
        *je = NULL;

        JK_ENTER_CS(&aw->cs, rc);
        if (rc) {
            unsigned int slot;
            for (slot = 0; slot < aw->ep_cache_sz; slot++) {
                if (aw->ep_cache[slot]) {
                    ae = aw->ep_cache[slot];
                    aw->ep_cache[slot] = NULL;
                    break;
                }
            }
            if (ae) {
                ae->last_access = now;
                *je = &ae->endpoint;
                JK_LEAVE_CS(&aw->cs, rc);
                if (JK_IS_DEBUG_LEVEL(l))
                    jk_log(l, JK_LOG_DEBUG,
                           "acquired connection pool slot=%u",
                           slot);
                JK_TRACE_EXIT(l);
                return JK_TRUE;
            }
            else {
                jk_log(l, JK_LOG_WARNING,
                        "Unable to get the free endpoint for worker %s from %u slots",
                        aw->name, aw->ep_cache_sz);
            }
            JK_LEAVE_CS(&aw->cs, rc);
        }
        else {
           jk_log(l, JK_LOG_ERROR,
                  "locking thread with errno=%d",
                  errno);
            JK_TRACE_EXIT(l);
            return JK_FALSE;

        }
        jk_log(l, JK_LOG_INFO,
               "can't find free endpoint");
    }
    else {
        JK_LOG_NULL_PARAMS(l);
    }

    JK_TRACE_EXIT(l);
    return JK_FALSE;
}

int JK_METHOD ajp_maintain(jk_worker_t *pThis, time_t now, jk_logger_t *l)
{
    JK_TRACE_ENTER(l);

    if (pThis && pThis->worker_private) {
        ajp_worker_t *aw = pThis->worker_private;
        int rc;
        /* Obtain current time only if needed */
        if (aw->cache_timeout < 1) {
            /* Nothing to do. */
            JK_TRACE_EXIT(l);
            return JK_TRUE;
        }
        JK_ENTER_CS(&aw->cs, rc);
        if (rc) {
            unsigned int i, n = 0, cnt = 0;
            /* Count opended slots */
            for (i = 0; i < aw->ep_cache_sz; i++) {
                if (aw->ep_cache[i] && IS_VALID_SOCKET(aw->ep_cache[i]->sd))
                    cnt++;
            }
            /* Handle worker cache and recycle timeouts */
            for (i = 0; i < aw->ep_cache_sz; i++) {
                /* Skip the closed sockets */
                if (aw->ep_cache[i] && IS_VALID_SOCKET(aw->ep_cache[i]->sd)) {
                    int elapsed = (int)difftime(now, aw->ep_cache[i]->last_access);
                    if ((aw->cache_timeout > 0) && (elapsed > aw->cache_timeout)) {
                        time_t rt = 0;
                        n++;
                        if (JK_IS_DEBUG_LEVEL(l))
                            rt = time(NULL);
                        aw->ep_cache[i]->reuse = JK_FALSE;
                        ajp_reset_endpoint(aw->ep_cache[i], l);
                        if (JK_IS_DEBUG_LEVEL(l))
                            jk_log(l, JK_LOG_DEBUG,
                                    "cleaning pool slot=%u elapsed %d in %d",
                                    i, elapsed, (int)(difftime(time(NULL), rt)));
                    }
                }
                if ((cnt - n) <= aw->ep_mincache_sz) {
                    if (JK_IS_DEBUG_LEVEL(l)) {
                        jk_log(l, JK_LOG_DEBUG,
                        "reached pool min size %u from %u cache slots",
                        aw->ep_mincache_sz, aw->ep_cache_sz);
                    }
                    break;
                }
            }
            if (JK_IS_DEBUG_LEVEL(l))
                jk_log(l, JK_LOG_DEBUG,
                        "recycled %u sockets in %d seconds from %u pool slots",
                        n, (int)(difftime(time(NULL), now)),
                        aw->ep_cache_sz);
            JK_LEAVE_CS(&aw->cs, rc);
            JK_TRACE_EXIT(l);
            return JK_TRUE;
        }
        else {
           jk_log(l, JK_LOG_ERROR,
                  "locking thread with errno=%d",
                  errno);
            JK_TRACE_EXIT(l);
            return JK_FALSE;

        }
    }
    else {
        JK_LOG_NULL_PARAMS(l);
    }

    JK_TRACE_EXIT(l);
    return JK_FALSE;
}