File: HttpParser.java

package info (click to toggle)
jetty9 9.4.50-4%2Bdeb11u2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 54,024 kB
  • sloc: java: 441,941; xml: 25,241; javascript: 1,039; sh: 910; jsp: 268; sql: 40; makefile: 16
file content (2049 lines) | stat: -rw-r--r-- 78,631 bytes parent folder | download | duplicates (5)
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
//
//  ========================================================================
//  Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.http;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;

import org.eclipse.jetty.http.HttpTokens.EndOfContent;
import org.eclipse.jetty.util.ArrayTernaryTrie;
import org.eclipse.jetty.util.ArrayTrie;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.Trie;
import org.eclipse.jetty.util.Utf8StringBuilder;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

import static org.eclipse.jetty.http.HttpComplianceSection.MULTIPLE_CONTENT_LENGTHS;
import static org.eclipse.jetty.http.HttpComplianceSection.TRANSFER_ENCODING_WITH_CONTENT_LENGTH;

/**
 * A Parser for 1.0 and 1.1 as defined by RFC7230
 * <p>
 * This parser parses HTTP client and server messages from buffers
 * passed in the {@link #parseNext(ByteBuffer)} method.  The parsed
 * elements of the HTTP message are passed as event calls to the
 * {@link HttpHandler} instance the parser is constructed with.
 * If the passed handler is a {@link RequestHandler} then server side
 * parsing is performed and if it is a {@link ResponseHandler}, then
 * client side parsing is done.
 * </p>
 * <p>
 * The contract of the {@link HttpHandler} API is that if a call returns
 * true then the call to {@link #parseNext(ByteBuffer)} will return as
 * soon as possible also with a true response.  Typically this indicates
 * that the parsing has reached a stage where the caller should process
 * the events accumulated by the handler.    It is the preferred calling
 * style that handling such as calling a servlet to process a request,
 * should be done after a true return from {@link #parseNext(ByteBuffer)}
 * rather than from within the scope of a call like
 * {@link RequestHandler#messageComplete()}
 * </p>
 * <p>
 * For performance, the parse is heavily dependent on the
 * {@link Trie#getBest(ByteBuffer, int, int)} method to look ahead in a
 * single pass for both the structure ( : and CRLF ) and semantic (which
 * header and value) of a header.  Specifically the static {@link HttpHeader#CACHE}
 * is used to lookup common combinations of headers and values
 * (eg. "Connection: close"), or just header names (eg. "Connection:" ).
 * For headers who's value is not known statically (eg. Host, COOKIE) then a
 * per parser dynamic Trie of {@link HttpFields} from previous parsed messages
 * is used to help the parsing of subsequent messages.
 * </p>
 * <p>
 * The parser can work in varying compliance modes:
 * <dl>
 * <dt>RFC7230</dt><dd>(default) Compliance with RFC7230</dd>
 * <dt>RFC2616</dt><dd>Wrapped headers and HTTP/0.9 supported</dd>
 * <dt>LEGACY</dt><dd>(aka STRICT) Adherence to Servlet Specification requirement for
 * exact case of header names, bypassing the header caches, which are case insensitive,
 * otherwise equivalent to RFC2616</dd>
 * </dl>
 *
 * @see <a href="http://tools.ietf.org/html/rfc7230">RFC 7230</a>
 */
public class HttpParser
{
    public static final Logger LOG = Log.getLogger(HttpParser.class);
    @Deprecated
    public static final String __STRICT = "org.eclipse.jetty.http.HttpParser.STRICT";
    public static final int INITIAL_URI_LENGTH = 256;
    private static final int MAX_CHUNK_LENGTH = Integer.MAX_VALUE / 16 - 16;

    /**
     * Cache of common {@link HttpField}s including: <UL>
     * <LI>Common static combinations such as:<UL>
     * <li>Connection: close
     * <li>Accept-Encoding: gzip
     * <li>Content-Length: 0
     * </ul>
     * <li>Combinations of Content-Type header for common mime types by common charsets
     * <li>Most common headers with null values so that a lookup will at least
     * determine the header name even if the name:value combination is not cached
     * </ul>
     */
    public static final Trie<HttpField> CACHE = new ArrayTrie<>(2048);
    private static final Trie<HttpField> NO_CACHE = Trie.empty(true);

    // States
    public enum FieldState
    {
        FIELD,
        IN_NAME,
        VALUE,
        IN_VALUE,
        WS_AFTER_NAME,
    }

    // States
    public enum State
    {
        START,
        METHOD,
        RESPONSE_VERSION,
        SPACE1,
        STATUS,
        URI,
        SPACE2,
        REQUEST_VERSION,
        REASON,
        PROXY,
        HEADER,
        CONTENT,
        EOF_CONTENT,
        CHUNKED_CONTENT,
        CHUNK_SIZE,
        CHUNK_PARAMS,
        CHUNK,
        CONTENT_END,
        TRAILER,
        END,
        CLOSE,  // The associated stream/endpoint should be closed
        CLOSED  // The associated stream/endpoint is at EOF
    }

    private static final EnumSet<State> __idleStates = EnumSet.of(State.START, State.END, State.CLOSE, State.CLOSED);
    private static final EnumSet<State> __completeStates = EnumSet.of(State.END, State.CLOSE, State.CLOSED);
    private static final EnumSet<State> __terminatedStates = EnumSet.of(State.CLOSE, State.CLOSED);

    private final boolean debug = LOG.isDebugEnabled(); // Cache debug to help branch prediction
    private final HttpHandler _handler;
    private final RequestHandler _requestHandler;
    private final ResponseHandler _responseHandler;
    private final ComplianceHandler _complianceHandler;
    private final int _maxHeaderBytes;
    private final HttpCompliance _compliance;
    private final EnumSet<HttpComplianceSection> _compliances;
    private final Utf8StringBuilder _uri = new Utf8StringBuilder(INITIAL_URI_LENGTH);
    private HttpField _field;
    private HttpHeader _header;
    private String _headerString;
    private String _valueString;
    private int _responseStatus;
    private int _headerBytes;
    private boolean _host;
    private boolean _headerComplete;

    private volatile State _state = State.START;
    private volatile FieldState _fieldState = FieldState.FIELD;
    private volatile boolean _eof;
    private HttpMethod _method;
    private String _methodString;
    private HttpVersion _version;
    private EndOfContent _endOfContent;
    private boolean _hasContentLength;
    private boolean _hasTransferEncoding;
    private long _contentLength = -1;
    private long _contentPosition;
    private int _chunkLength;
    private int _chunkPosition;
    private boolean _headResponse;
    private boolean _cr;
    private ByteBuffer _contentChunk;
    private Trie<HttpField> _fieldCache;

    private int _length;
    private final StringBuilder _string = new StringBuilder();

    static
    {
        CACHE.put(new HttpField(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE));
        CACHE.put(new HttpField(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE));
        CACHE.put(new HttpField(HttpHeader.CONNECTION, HttpHeaderValue.UPGRADE));
        CACHE.put(new HttpField(HttpHeader.ACCEPT_ENCODING, "gzip"));
        CACHE.put(new HttpField(HttpHeader.ACCEPT_ENCODING, "gzip, deflate"));
        CACHE.put(new HttpField(HttpHeader.ACCEPT_ENCODING, "gzip, deflate, br"));
        CACHE.put(new HttpField(HttpHeader.ACCEPT_ENCODING, "gzip,deflate,sdch"));
        CACHE.put(new HttpField(HttpHeader.ACCEPT_LANGUAGE, "en-US,en;q=0.5"));
        CACHE.put(new HttpField(HttpHeader.ACCEPT_LANGUAGE, "en-GB,en-US;q=0.8,en;q=0.6"));
        CACHE.put(new HttpField(HttpHeader.ACCEPT_LANGUAGE, "en-AU,en;q=0.9,it-IT;q=0.8,it;q=0.7,en-GB;q=0.6,en-US;q=0.5"));
        CACHE.put(new HttpField(HttpHeader.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.3"));
        CACHE.put(new HttpField(HttpHeader.ACCEPT, "*/*"));
        CACHE.put(new HttpField(HttpHeader.ACCEPT, "image/png,image/*;q=0.8,*/*;q=0.5"));
        CACHE.put(new HttpField(HttpHeader.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
        CACHE.put(new HttpField(HttpHeader.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"));
        CACHE.put(new HttpField(HttpHeader.ACCEPT_RANGES, HttpHeaderValue.BYTES));
        CACHE.put(new HttpField(HttpHeader.PRAGMA, "no-cache"));
        CACHE.put(new HttpField(HttpHeader.CACHE_CONTROL, "private, no-cache, no-cache=Set-Cookie, proxy-revalidate"));
        CACHE.put(new HttpField(HttpHeader.CACHE_CONTROL, "no-cache"));
        CACHE.put(new HttpField(HttpHeader.CACHE_CONTROL, "max-age=0"));
        CACHE.put(new HttpField(HttpHeader.CONTENT_LENGTH, "0"));
        CACHE.put(new HttpField(HttpHeader.CONTENT_ENCODING, "gzip"));
        CACHE.put(new HttpField(HttpHeader.CONTENT_ENCODING, "deflate"));
        CACHE.put(new HttpField(HttpHeader.TRANSFER_ENCODING, "chunked"));
        CACHE.put(new HttpField(HttpHeader.EXPIRES, "Fri, 01 Jan 1990 00:00:00 GMT"));

        // Add common Content types as fields
        for (String type : new String[]{
            "text/plain", "text/html", "text/xml", "text/json", "application/json", "application/x-www-form-urlencoded"
        })
        {
            HttpField field = new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, type);
            CACHE.put(field);

            for (String charset : new String[]{"utf-8", "iso-8859-1"})
            {
                CACHE.put(new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, type + ";charset=" + charset));
                CACHE.put(new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, type + "; charset=" + charset));
                CACHE.put(new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, type + ";charset=" + charset.toUpperCase(Locale.ENGLISH)));
                CACHE.put(new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, type + "; charset=" + charset.toUpperCase(Locale.ENGLISH)));
            }
        }

        // Add headers with null values so HttpParser can avoid looking up name again for unknown values
        for (HttpHeader h : HttpHeader.values())
        {
            if (!h.isPseudo() && !CACHE.put(new HttpField(h, (String)null)))
                throw new IllegalStateException("CACHE FULL");
        }
    }

    private static HttpCompliance compliance()
    {
        boolean strict = Boolean.getBoolean(__STRICT);
        if (strict)
        {
            LOG.warn("Deprecated property used: " + __STRICT);
            return HttpCompliance.LEGACY;
        }
        return HttpCompliance.RFC7230;
    }

    public HttpParser(RequestHandler handler)
    {
        this(handler, -1, compliance());
    }

    public HttpParser(ResponseHandler handler)
    {
        this(handler, -1, compliance());
    }

    public HttpParser(RequestHandler handler, int maxHeaderBytes)
    {
        this(handler, maxHeaderBytes, compliance());
    }

    public HttpParser(ResponseHandler handler, int maxHeaderBytes)
    {
        this(handler, maxHeaderBytes, compliance());
    }

    @Deprecated
    public HttpParser(RequestHandler handler, int maxHeaderBytes, boolean strict)
    {
        this(handler, maxHeaderBytes, strict ? HttpCompliance.LEGACY : compliance());
    }

    @Deprecated
    public HttpParser(ResponseHandler handler, int maxHeaderBytes, boolean strict)
    {
        this(handler, maxHeaderBytes, strict ? HttpCompliance.LEGACY : compliance());
    }

    public HttpParser(RequestHandler handler, HttpCompliance compliance)
    {
        this(handler, -1, compliance);
    }

    public HttpParser(RequestHandler handler, int maxHeaderBytes, HttpCompliance compliance)
    {
        this(handler, null, maxHeaderBytes, compliance == null ? compliance() : compliance);
    }

    public HttpParser(ResponseHandler handler, int maxHeaderBytes, HttpCompliance compliance)
    {
        this(null, handler, maxHeaderBytes, compliance == null ? compliance() : compliance);
    }

    private HttpParser(RequestHandler requestHandler, ResponseHandler responseHandler, int maxHeaderBytes, HttpCompliance compliance)
    {
        _handler = requestHandler != null ? requestHandler : responseHandler;
        _requestHandler = requestHandler;
        _responseHandler = responseHandler;
        _maxHeaderBytes = maxHeaderBytes;
        _compliance = compliance;
        _compliances = compliance.sections();
        _complianceHandler = (ComplianceHandler)(_handler instanceof ComplianceHandler ? _handler : null);
    }

    public HttpHandler getHandler()
    {
        return _handler;
    }

    public HttpCompliance getHttpCompliance()
    {
        return _compliance;
    }

    /**
     * Check RFC compliance violation
     *
     * @param violation The compliance section violation
     * @return True if the current compliance level is set so as to Not allow this violation
     */
    protected boolean complianceViolation(HttpComplianceSection violation)
    {
        return complianceViolation(violation, null);
    }

    /**
     * Check RFC compliance violation
     *
     * @param violation The compliance section violation
     * @param reason The reason for the violation
     * @return True if the current compliance level is set so as to Not allow this violation
     */
    protected boolean complianceViolation(HttpComplianceSection violation, String reason)
    {
        if (_compliances.contains(violation))
            return true;
        if (reason == null)
            reason = violation.description;
        if (_complianceHandler != null)
            _complianceHandler.onComplianceViolation(_compliance, violation, reason);

        return false;
    }

    protected void handleViolation(HttpComplianceSection section, String reason)
    {
        if (_complianceHandler != null)
            _complianceHandler.onComplianceViolation(_compliance, section, reason);
    }

    protected String caseInsensitiveHeader(String orig, String normative)
    {
        if (_compliances.contains(HttpComplianceSection.FIELD_NAME_CASE_INSENSITIVE))
            return normative;
        if (!orig.equals(normative))
            handleViolation(HttpComplianceSection.FIELD_NAME_CASE_INSENSITIVE, orig);
        return orig;
    }

    public long getContentLength()
    {
        return _contentLength;
    }

    public long getContentRead()
    {
        return _contentPosition;
    }

    public int getHeaderLength()
    {
        return _headerBytes;
    }

    /**
     * Set if a HEAD response is expected
     *
     * @param head true if head response is expected
     */
    public void setHeadResponse(boolean head)
    {
        _headResponse = head;
    }

    protected void setResponseStatus(int status)
    {
        _responseStatus = status;
    }

    public State getState()
    {
        return _state;
    }

    public boolean inContentState()
    {
        return _state.ordinal() >= State.CONTENT.ordinal() && _state.ordinal() < State.END.ordinal();
    }

    public boolean inHeaderState()
    {
        return _state.ordinal() < State.CONTENT.ordinal();
    }

    public boolean isChunking()
    {
        return _endOfContent == EndOfContent.CHUNKED_CONTENT;
    }

    public boolean isStart()
    {
        return isState(State.START);
    }

    public boolean isClose()
    {
        return isState(State.CLOSE);
    }

    public boolean isClosed()
    {
        return isState(State.CLOSED);
    }

    public boolean isIdle()
    {
        return __idleStates.contains(_state);
    }

    public boolean isComplete()
    {
        return __completeStates.contains(_state);
    }

    public boolean isTerminated()
    {
        return __terminatedStates.contains(_state);
    }

    public boolean isState(State state)
    {
        return _state == state;
    }

    private HttpTokens.Token next(ByteBuffer buffer)
    {
        byte ch = buffer.get();

        HttpTokens.Token t = HttpTokens.TOKENS[0xff & ch];

        switch (t.getType())
        {
            case CNTL:
                throw new IllegalCharacterException(_state, t, buffer);

            case LF:
                _cr = false;
                break;

            case CR:
                if (_cr)
                    throw new BadMessageException("Bad EOL");

                _cr = true;
                if (buffer.hasRemaining())
                {
                    // Don't count the CRs and LFs of the chunked encoding.
                    if (_maxHeaderBytes > 0 && (_state == State.HEADER || _state == State.TRAILER))
                        _headerBytes++;
                    return next(buffer);
                }

                return null;

            case ALPHA:
            case DIGIT:
            case TCHAR:
            case VCHAR:
            case HTAB:
            case SPACE:
            case OTEXT:
            case COLON:
                if (_cr)
                    throw new BadMessageException("Bad EOL");
                break;

            default:
                break;
        }

        return t;
    }

    /* Quick lookahead for the start state looking for a request method or an HTTP version,
     * otherwise skip white space until something else to parse.
     */
    private void quickStart(ByteBuffer buffer)
    {
        if (_requestHandler != null)
        {
            _method = HttpMethod.lookAheadGet(buffer);
            if (_method != null)
            {
                _methodString = _method.asString();
                buffer.position(buffer.position() + _methodString.length() + 1);

                setState(State.SPACE1);
                return;
            }
        }
        else if (_responseHandler != null)
        {
            _version = HttpVersion.lookAheadGet(buffer);
            if (_version != null)
            {
                buffer.position(buffer.position() + _version.asString().length() + 1);
                setState(State.SPACE1);
                return;
            }
        }

        // Quick start look
        while (_state == State.START && buffer.hasRemaining())
        {
            HttpTokens.Token t = next(buffer);
            if (t == null)
                break;

            switch (t.getType())
            {
                case ALPHA:
                case DIGIT:
                case TCHAR:
                case VCHAR:
                {
                    _string.setLength(0);
                    _string.append(t.getChar());
                    setState(_requestHandler != null ? State.METHOD : State.RESPONSE_VERSION);
                    return;
                }
                case OTEXT:
                case SPACE:
                case HTAB:
                    throw new IllegalCharacterException(_state, t, buffer);

                default:
                    break;
            }

            // count this white space as a header byte to avoid DOS
            if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes)
            {
                LOG.warn("padding is too large >" + _maxHeaderBytes);
                throw new BadMessageException(HttpStatus.BAD_REQUEST_400);
            }
        }
    }

    private void setString(String s)
    {
        _string.setLength(0);
        _string.append(s);
        _length = s.length();
    }

    private String takeString()
    {
        _string.setLength(_length);
        String s = _string.toString();
        _string.setLength(0);
        _length = -1;
        return s;
    }

    private boolean handleHeaderContentMessage()
    {
        boolean handleHeader = _handler.headerComplete();
        _headerComplete = true;
        if (handleHeader)
            return true;
        setState(State.CONTENT_END);
        return handleContentMessage();
    }

    private boolean handleContentMessage()
    {
        boolean handleContent = _handler.contentComplete();
        if (handleContent)
            return true;
        setState(State.END);
        return _handler.messageComplete();
    }

    /* Parse a request or response line
     */
    private boolean parseLine(ByteBuffer buffer)
    {
        boolean handle = false;

        // Process headers
        while (_state.ordinal() < State.HEADER.ordinal() && buffer.hasRemaining() && !handle)
        {
            // process each character
            HttpTokens.Token t = next(buffer);
            if (t == null)
                break;

            if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes)
            {
                if (_state == State.URI)
                {
                    LOG.warn("URI is too large >" + _maxHeaderBytes);
                    throw new BadMessageException(HttpStatus.URI_TOO_LONG_414);
                }
                else
                {
                    if (_requestHandler != null)
                        LOG.warn("request is too large >" + _maxHeaderBytes);
                    else
                        LOG.warn("response is too large >" + _maxHeaderBytes);
                    throw new BadMessageException(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE_431);
                }
            }

            switch (_state)
            {
                case METHOD:
                    switch (t.getType())
                    {
                        case SPACE:
                            _length = _string.length();
                            _methodString = takeString();

                            if (_compliances.contains(HttpComplianceSection.METHOD_CASE_SENSITIVE))
                            {
                                HttpMethod method = HttpMethod.CACHE.get(_methodString);
                                if (method != null)
                                    _methodString = method.asString();
                            }
                            else
                            {
                                HttpMethod method = HttpMethod.INSENSITIVE_CACHE.get(_methodString);

                                if (method != null)
                                {
                                    if (!method.asString().equals(_methodString))
                                        handleViolation(HttpComplianceSection.METHOD_CASE_SENSITIVE, _methodString);
                                    _methodString = method.asString();
                                }
                            }

                            setState(State.SPACE1);
                            break;

                        case LF:
                            throw new BadMessageException("No URI");

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                            _string.append(t.getChar());
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case RESPONSE_VERSION:
                    switch (t.getType())
                    {
                        case SPACE:
                            _length = _string.length();
                            String version = takeString();
                            _version = HttpVersion.CACHE.get(version);
                            checkVersion();
                            setState(State.SPACE1);
                            break;

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        case VCHAR:
                        case COLON:
                            _string.append(t.getChar());
                            break;
                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case SPACE1:
                    switch (t.getType())
                    {
                        case SPACE:
                            break;

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        case VCHAR:
                        case COLON:
                            if (_responseHandler != null)
                            {
                                if (t.getType() != HttpTokens.Type.DIGIT)
                                    throw new IllegalCharacterException(_state, t, buffer);
                                setState(State.STATUS);
                                setResponseStatus(t.getByte() - '0');
                            }
                            else
                            {
                                _uri.reset();
                                setState(State.URI);
                                // quick scan for space or EoBuffer
                                if (buffer.hasArray())
                                {
                                    byte[] array = buffer.array();
                                    int p = buffer.arrayOffset() + buffer.position();
                                    int l = buffer.arrayOffset() + buffer.limit();
                                    int i = p;
                                    while (i < l && array[i] > HttpTokens.SPACE)
                                    {
                                        i++;
                                    }

                                    int len = i - p;
                                    _headerBytes += len;

                                    if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes)
                                    {
                                        LOG.warn("URI is too large >" + _maxHeaderBytes);
                                        throw new BadMessageException(HttpStatus.URI_TOO_LONG_414);
                                    }
                                    _uri.append(array, p - 1, len + 1);
                                    buffer.position(i - buffer.arrayOffset());
                                }
                                else
                                    _uri.append(t.getByte());
                            }
                            break;

                        default:
                            throw new BadMessageException(HttpStatus.BAD_REQUEST_400, _requestHandler != null ? "No URI" : "No Status");
                    }
                    break;

                case STATUS:
                    switch (t.getType())
                    {
                        case SPACE:
                            setState(State.SPACE2);
                            break;

                        case DIGIT:
                            _responseStatus = _responseStatus * 10 + (t.getByte() - '0');
                            if (_responseStatus >= 1000)
                                throw new BadMessageException("Bad status");
                            break;

                        case LF:
                            setState(State.HEADER);
                            _responseHandler.startResponse(_version, _responseStatus, null);
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case URI:
                    switch (t.getType())
                    {
                        case SPACE:
                            setState(State.SPACE2);
                            break;

                        case LF:
                            // HTTP/0.9
                            if (complianceViolation(HttpComplianceSection.NO_HTTP_0_9, "No request version"))
                                throw new BadMessageException(HttpStatus.HTTP_VERSION_NOT_SUPPORTED_505, "HTTP/0.9 not supported");
                            _requestHandler.startRequest(_methodString, _uri.toString(), HttpVersion.HTTP_0_9);
                            setState(State.CONTENT);
                            _endOfContent = EndOfContent.NO_CONTENT;
                            BufferUtil.clear(buffer);
                            handle = handleHeaderContentMessage();
                            break;

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        case VCHAR:
                        case COLON:
                        case OTEXT:
                            _uri.append(t.getByte());
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case SPACE2:
                    switch (t.getType())
                    {
                        case SPACE:
                            break;

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        case VCHAR:
                        case COLON:
                            _string.setLength(0);
                            _string.append(t.getChar());
                            if (_responseHandler != null)
                            {
                                _length = 1;
                                setState(State.REASON);
                            }
                            else
                            {
                                setState(State.REQUEST_VERSION);

                                // try quick look ahead for HTTP Version
                                HttpVersion version;
                                if (buffer.position() > 0 && buffer.hasArray())
                                    version = HttpVersion.lookAheadGet(buffer.array(), buffer.arrayOffset() + buffer.position() - 1, buffer.arrayOffset() + buffer.limit());
                                else
                                    version = HttpVersion.CACHE.getBest(buffer, 0, buffer.remaining());

                                if (version != null)
                                {
                                    int pos = buffer.position() + version.asString().length() - 1;
                                    if (pos < buffer.limit())
                                    {
                                        byte n = buffer.get(pos);
                                        if (n == HttpTokens.CARRIAGE_RETURN)
                                        {
                                            _cr = true;
                                            _version = version;
                                            checkVersion();
                                            _string.setLength(0);
                                            buffer.position(pos + 1);
                                        }
                                        else if (n == HttpTokens.LINE_FEED)
                                        {
                                            _version = version;
                                            checkVersion();
                                            _string.setLength(0);
                                            buffer.position(pos);
                                        }
                                    }
                                }
                            }
                            break;

                        case LF:
                            if (_responseHandler != null)
                            {
                                setState(State.HEADER);
                                _responseHandler.startResponse(_version, _responseStatus, null);
                            }
                            else
                            {
                                // HTTP/0.9
                                if (complianceViolation(HttpComplianceSection.NO_HTTP_0_9, "No request version"))
                                    throw new BadMessageException("HTTP/0.9 not supported");

                                _requestHandler.startRequest(_methodString, _uri.toString(), HttpVersion.HTTP_0_9);
                                setState(State.CONTENT);
                                _endOfContent = EndOfContent.NO_CONTENT;
                                BufferUtil.clear(buffer);
                                handle = handleHeaderContentMessage();
                            }
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case REQUEST_VERSION:
                    switch (t.getType())
                    {
                        case LF:
                            if (_version == null)
                            {
                                _length = _string.length();
                                _version = HttpVersion.CACHE.get(takeString());
                            }
                            checkVersion();

                            setState(State.HEADER);

                            _requestHandler.startRequest(_methodString, _uri.toString(), _version);
                            continue;

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        case VCHAR:
                        case COLON:
                            _string.append(t.getChar());
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case REASON:
                    switch (t.getType())
                    {
                        case LF:
                            String reason = takeString();
                            setState(State.HEADER);
                            _responseHandler.startResponse(_version, _responseStatus, reason);
                            continue;

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        case VCHAR:
                        case COLON:
                        case OTEXT: // TODO should this be UTF8
                            _string.append(t.getChar());
                            _length = _string.length();
                            break;

                        case SPACE:
                        case HTAB:
                            _string.append(t.getChar());
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                default:
                    throw new IllegalStateException(_state.toString());
            }
        }

        return handle;
    }

    private void checkVersion()
    {
        if (_version == null)
            throw new BadMessageException(HttpStatus.HTTP_VERSION_NOT_SUPPORTED_505, "Unknown Version");

        if (_version.getVersion() < 10 || _version.getVersion() > 20)
            throw new BadMessageException(HttpStatus.HTTP_VERSION_NOT_SUPPORTED_505, "Unsupported Version");
    }

    private void parsedHeader()
    {
        // handler last header if any.  Delayed to here just in case there was a continuation line (above)
        if (_headerString != null || _valueString != null)
        {
            // Handle known headers
            if (_header != null)
            {
                boolean addToFieldCache = false;
                switch (_header)
                {
                    case CONTENT_LENGTH:
                        if (_hasTransferEncoding && complianceViolation(TRANSFER_ENCODING_WITH_CONTENT_LENGTH))
                            throw new BadMessageException(HttpStatus.BAD_REQUEST_400, "Transfer-Encoding and Content-Length");
                        long contentLength = convertContentLength(_valueString);
                        if (_hasContentLength)
                        {
                            if (complianceViolation(MULTIPLE_CONTENT_LENGTHS))
                                throw new BadMessageException(HttpStatus.BAD_REQUEST_400, MULTIPLE_CONTENT_LENGTHS.description);
                            if (contentLength != _contentLength)
                                throw new BadMessageException(HttpStatus.BAD_REQUEST_400, MULTIPLE_CONTENT_LENGTHS.getDescription());
                        }
                        _hasContentLength = true;

                        if (_endOfContent != EndOfContent.CHUNKED_CONTENT)
                        {
                            _contentLength = contentLength;
                            _endOfContent = EndOfContent.CONTENT_LENGTH;
                        }
                        break;

                    case TRANSFER_ENCODING:
                        _hasTransferEncoding = true;

                        if (_hasContentLength && complianceViolation(TRANSFER_ENCODING_WITH_CONTENT_LENGTH))
                            throw new BadMessageException(HttpStatus.BAD_REQUEST_400, "Transfer-Encoding and Content-Length");

                        // we encountered another Transfer-Encoding header, but chunked was already set
                        if (_endOfContent == EndOfContent.CHUNKED_CONTENT)
                            throw new BadMessageException(HttpStatus.BAD_REQUEST_400, "Bad Transfer-Encoding, chunked not last");

                        if (HttpHeaderValue.CHUNKED.is(_valueString))
                        {
                            _endOfContent = EndOfContent.CHUNKED_CONTENT;
                            _contentLength = -1;
                        }
                        else
                        {
                            List<String> values = new QuotedCSV(_valueString).getValues();
                            int chunked = -1;
                            int len = values.size();
                            for (int i = 0; i < len; i++)
                            {
                                if (HttpHeaderValue.CHUNKED.is(values.get(i)))
                                {
                                    if (chunked != -1)
                                        throw new BadMessageException(HttpStatus.BAD_REQUEST_400, "Bad Transfer-Encoding, multiple chunked tokens");
                                    chunked = i;
                                    // declared chunked
                                    _endOfContent = EndOfContent.CHUNKED_CONTENT;
                                    _contentLength = -1;
                                }
                                // we have a non-chunked token after a declared chunked token
                                else if (_endOfContent == EndOfContent.CHUNKED_CONTENT)
                                {
                                    throw new BadMessageException(HttpStatus.BAD_REQUEST_400, "Bad Transfer-Encoding, chunked not last");
                                }
                            }
                        }
                        break;

                    case HOST:
                        _host = true;
                        if (!(_field instanceof HostPortHttpField) && _valueString != null && !_valueString.isEmpty())
                        {
                            _field = new HostPortHttpField(_header,
                                _compliances.contains(HttpComplianceSection.FIELD_NAME_CASE_INSENSITIVE) ? _header.asString() : _headerString,
                                _valueString);
                            addToFieldCache = true;
                        }
                        break;

                    case CONNECTION:
                        // Don't cache headers if not persistent
                        if (_field == null)
                            _field = new HttpField(_header, caseInsensitiveHeader(_headerString, _header.asString()), _valueString);
                        if (_handler.getHeaderCacheSize() > 0 && _field.contains(HttpHeaderValue.CLOSE.asString()))
                            _fieldCache = NO_CACHE;
                        break;

                    case AUTHORIZATION:
                    case ACCEPT:
                    case ACCEPT_CHARSET:
                    case ACCEPT_ENCODING:
                    case ACCEPT_LANGUAGE:
                    case COOKIE:
                    case CACHE_CONTROL:
                    case USER_AGENT:
                        addToFieldCache = _field == null;
                        break;

                    default:
                        break;
                }

                // Cache field?
                if (addToFieldCache && _header != null && _valueString != null)
                {
                    if (_fieldCache == null)
                    {
                        _fieldCache = (_handler.getHeaderCacheSize() > 0 && (_version != null && _version == HttpVersion.HTTP_1_1))
                            ? new ArrayTernaryTrie<>(_handler.getHeaderCacheSize())
                            : NO_CACHE;
                    }

                    if (!_fieldCache.isFull())
                    {
                        if (_field == null)
                            _field = new HttpField(_header, caseInsensitiveHeader(_headerString, _header.asString()), _valueString);
                        _fieldCache.put(_field);
                    }
                }
            }
            _handler.parsedHeader(_field != null ? _field : new HttpField(_header, _headerString, _valueString));
        }

        _headerString = _valueString = null;
        _header = null;
        _field = null;
    }

    private void parsedTrailer()
    {
        // handler last header if any.  Delayed to here just in case there was a continuation line (above)
        if (_headerString != null || _valueString != null)
            _handler.parsedTrailer(_field != null ? _field : new HttpField(_header, _headerString, _valueString));

        _headerString = _valueString = null;
        _header = null;
        _field = null;
    }

    private long convertContentLength(String valueString)
    {
        if (valueString == null || valueString.length() == 0)
            throw new BadMessageException("Invalid Content-Length Value", new NumberFormatException());

        long value = 0;
        int length = valueString.length();

        for (int i = 0; i < length; i++)
        {
            char c = valueString.charAt(i);
            if (c < '0' || c > '9')
                throw new BadMessageException("Invalid Content-Length Value", new NumberFormatException());

            value = Math.addExact(Math.multiplyExact(value, 10L), c - '0');
        }
        return value;
    }

    /*
     * Parse the message headers and return true if the handler has signalled for a return
     */
    protected boolean parseFields(ByteBuffer buffer)
    {
        // Process headers
        while ((_state == State.HEADER || _state == State.TRAILER) && buffer.hasRemaining())
        {
            // process each character
            HttpTokens.Token t = next(buffer);
            if (t == null)
                break;

            if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes)
            {
                boolean header = _state == State.HEADER;
                LOG.warn("{} is too large {}>{}", header ? "Header" : "Trailer", _headerBytes, _maxHeaderBytes);
                throw new BadMessageException(header
                    ? HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE_431
                    : HttpStatus.PAYLOAD_TOO_LARGE_413);
            }

            switch (_fieldState)
            {
                case FIELD:
                    switch (t.getType())
                    {
                        case COLON:
                        case SPACE:
                        case HTAB:
                        {
                            if (complianceViolation(HttpComplianceSection.NO_FIELD_FOLDING, _headerString))
                                throw new BadMessageException(HttpStatus.BAD_REQUEST_400, "Header Folding");

                            // header value without name - continuation?
                            if (StringUtil.isEmpty(_valueString))
                            {
                                _string.setLength(0);
                                _length = 0;
                            }
                            else
                            {
                                setString(_valueString);
                                _string.append(' ');
                                _length++;
                                _valueString = null;
                            }
                            setState(FieldState.VALUE);
                            break;
                        }

                        case LF:
                        {
                            // process previous header
                            if (_state == State.HEADER)
                                parsedHeader();
                            else
                                parsedTrailer();

                            _contentPosition = 0;

                            // End of headers or trailers?
                            if (_state == State.TRAILER)
                            {
                                setState(State.END);
                                return _handler.messageComplete();
                            }

                            // We found Transfer-Encoding headers, but none declared the 'chunked' token
                            if (_hasTransferEncoding && _endOfContent != EndOfContent.CHUNKED_CONTENT)
                            {
                                if (_responseHandler == null || _endOfContent != EndOfContent.EOF_CONTENT)
                                {
                                    // Transfer-Encoding chunked not specified
                                    // https://tools.ietf.org/html/rfc7230#section-3.3.1
                                    throw new BadMessageException(HttpStatus.BAD_REQUEST_400, "Bad Transfer-Encoding, chunked not last");
                                }
                            }

                            // Was there a required host header?
                            if (!_host && _version == HttpVersion.HTTP_1_1 && _requestHandler != null)
                            {
                                throw new BadMessageException(HttpStatus.BAD_REQUEST_400, "No Host");
                            }

                            // is it a response that cannot have a body?
                            if (_responseHandler != null && // response
                                (_responseStatus == 304 || // not-modified response
                                    _responseStatus == 204 || // no-content response
                                    _responseStatus < 200)) // 1xx response
                                _endOfContent = EndOfContent.NO_CONTENT; // ignore any other headers set

                                // else if we don't know framing
                            else if (_endOfContent == EndOfContent.UNKNOWN_CONTENT)
                            {
                                if (_responseStatus == 0 || // request
                                    _responseStatus == 304 || // not-modified response
                                    _responseStatus == 204 || // no-content response
                                    _responseStatus < 200) // 1xx response
                                    _endOfContent = EndOfContent.NO_CONTENT;
                                else
                                    _endOfContent = EndOfContent.EOF_CONTENT;
                            }

                            // How is the message ended?
                            switch (_endOfContent)
                            {
                                case EOF_CONTENT:
                                {
                                    setState(State.EOF_CONTENT);
                                    boolean handle = _handler.headerComplete();
                                    _headerComplete = true;
                                    return handle;
                                }
                                case CHUNKED_CONTENT:
                                {
                                    setState(State.CHUNKED_CONTENT);
                                    boolean handle = _handler.headerComplete();
                                    _headerComplete = true;
                                    return handle;
                                }
                                default:
                                {
                                    setState(State.CONTENT);
                                    boolean handle = _handler.headerComplete();
                                    _headerComplete = true;
                                    return handle;
                                }
                            }
                        }

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        {
                            // process previous header
                            if (_state == State.HEADER)
                                parsedHeader();
                            else
                                parsedTrailer();

                            // handle new header
                            if (buffer.hasRemaining())
                            {
                                // Try a look ahead for the known header name and value.
                                HttpField cachedField = _fieldCache == null ? null : _fieldCache.getBest(buffer, -1, buffer.remaining());
                                if (cachedField == null)
                                    cachedField = CACHE.getBest(buffer, -1, buffer.remaining());

                                if (cachedField != null)
                                {
                                    String n = cachedField.getName();
                                    String v = cachedField.getValue();

                                    if (!_compliances.contains(HttpComplianceSection.FIELD_NAME_CASE_INSENSITIVE))
                                    {
                                        // Have to get the fields exactly from the buffer to match case
                                        String en = BufferUtil.toString(buffer, buffer.position() - 1, n.length(), StandardCharsets.US_ASCII);
                                        if (!n.equals(en))
                                        {
                                            handleViolation(HttpComplianceSection.FIELD_NAME_CASE_INSENSITIVE, en);
                                            n = en;
                                            cachedField = new HttpField(cachedField.getHeader(), n, v);
                                        }
                                    }

                                    if (v != null && !_compliances.contains(HttpComplianceSection.CASE_INSENSITIVE_FIELD_VALUE_CACHE))
                                    {
                                        String ev = BufferUtil.toString(buffer, buffer.position() + n.length() + 1, v.length(), StandardCharsets.ISO_8859_1);
                                        if (!v.equals(ev))
                                        {
                                            handleViolation(HttpComplianceSection.CASE_INSENSITIVE_FIELD_VALUE_CACHE, ev + "!=" + v);
                                            v = ev;
                                            cachedField = new HttpField(cachedField.getHeader(), n, v);
                                        }
                                    }

                                    _header = cachedField.getHeader();
                                    _headerString = n;

                                    if (v == null)
                                    {
                                        // Header only
                                        setState(FieldState.VALUE);
                                        _string.setLength(0);
                                        _length = 0;
                                        buffer.position(buffer.position() + n.length() + 1);
                                        break;
                                    }

                                    // Header and value
                                    int pos = buffer.position() + n.length() + v.length() + 1;
                                    byte peek = buffer.get(pos);
                                    if (peek == HttpTokens.CARRIAGE_RETURN || peek == HttpTokens.LINE_FEED)
                                    {
                                        _field = cachedField;
                                        _valueString = v;
                                        setState(FieldState.IN_VALUE);

                                        if (peek == HttpTokens.CARRIAGE_RETURN)
                                        {
                                            _cr = true;
                                            buffer.position(pos + 1);
                                        }
                                        else
                                            buffer.position(pos);
                                        break;
                                    }
                                    setState(FieldState.IN_VALUE);
                                    setString(v);
                                    buffer.position(pos);
                                    break;
                                }
                            }

                            // New header
                            setState(FieldState.IN_NAME);
                            _string.setLength(0);
                            _string.append(t.getChar());
                            _length = 1;
                            break;
                        }

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case IN_NAME:
                    switch (t.getType())
                    {
                        case SPACE:
                        case HTAB:
                            //Ignore trailing whitespaces ?
                            if (!complianceViolation(HttpComplianceSection.NO_WS_AFTER_FIELD_NAME, null))
                            {
                                _headerString = takeString();
                                _header = HttpHeader.CACHE.get(_headerString);
                                _length = -1;
                                setState(FieldState.WS_AFTER_NAME);
                                break;
                            }
                            throw new IllegalCharacterException(_state, t, buffer);

                        case COLON:
                            _headerString = takeString();
                            _header = HttpHeader.CACHE.get(_headerString);
                            _length = -1;
                            setState(FieldState.VALUE);
                            break;

                        case LF:
                            _headerString = takeString();
                            _header = HttpHeader.CACHE.get(_headerString);
                            _string.setLength(0);
                            _valueString = "";
                            _length = -1;

                            if (!complianceViolation(HttpComplianceSection.FIELD_COLON, _headerString))
                            {
                                setState(FieldState.FIELD);
                                break;
                            }
                            throw new IllegalCharacterException(_state, t, buffer);

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                            _string.append(t.getChar());
                            _length = _string.length();
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case WS_AFTER_NAME:

                    switch (t.getType())
                    {
                        case SPACE:
                        case HTAB:
                            break;

                        case COLON:
                            setState(FieldState.VALUE);
                            break;

                        case LF:
                            if (!complianceViolation(HttpComplianceSection.FIELD_COLON, _headerString))
                            {
                                setState(FieldState.FIELD);
                                break;
                            }
                            throw new IllegalCharacterException(_state, t, buffer);

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case VALUE:
                    switch (t.getType())
                    {
                        case LF:
                            _string.setLength(0);
                            _valueString = "";
                            _length = -1;

                            setState(FieldState.FIELD);
                            break;

                        case SPACE:
                        case HTAB:
                            break;

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        case VCHAR:
                        case COLON:
                        case OTEXT: // TODO review? should this be a utf8 string?
                            _string.append(t.getChar());
                            _length = _string.length();
                            setState(FieldState.IN_VALUE);
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case IN_VALUE:
                    switch (t.getType())
                    {
                        case LF:
                            if (_length > 0)
                            {
                                _valueString = takeString();
                                _length = -1;
                            }
                            setState(FieldState.FIELD);
                            break;

                        case SPACE:
                        case HTAB:
                            _string.append(t.getChar());
                            break;

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        case VCHAR:
                        case COLON:
                        case OTEXT: // TODO review? should this be a utf8 string?
                            _string.append(t.getChar());
                            _length = _string.length();
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                default:
                    throw new IllegalStateException(_state.toString());
            }
        }

        return false;
    }

    /**
     * Parse until next Event.
     *
     * @param buffer the buffer to parse
     * @return True if an {@link RequestHandler} method was called and it returned true;
     */
    public boolean parseNext(ByteBuffer buffer)
    {
        if (debug)
            LOG.debug("parseNext s={} {}", _state, BufferUtil.toDetailString(buffer));
        try
        {
            // Start a request/response
            if (_state == State.START)
            {
                _version = null;
                _method = null;
                _methodString = null;
                _endOfContent = EndOfContent.UNKNOWN_CONTENT;
                _header = null;
                quickStart(buffer);
            }

            // Request/response line
            if (_state.ordinal() < State.HEADER.ordinal())
            {
                if (parseLine(buffer))
                    return true;
            }

            // parse headers
            if (_state == State.HEADER)
            {
                if (parseFields(buffer))
                    return true;
            }

            // parse content
            if (_state.ordinal() >= State.CONTENT.ordinal() && _state.ordinal() < State.TRAILER.ordinal())
            {
                // Handle HEAD response
                if (_responseStatus > 0 && _headResponse)
                {
                    if (_state != State.CONTENT_END)
                    {
                        setState(State.CONTENT_END);
                        return handleContentMessage();
                    }
                    else
                    {
                        setState(State.END);
                        return _handler.messageComplete();
                    }
                }
                else
                {
                    if (parseContent(buffer))
                        return true;
                }
            }

            // parse headers
            if (_state == State.TRAILER)
            {
                if (parseFields(buffer))
                    return true;
            }

            // handle end states
            if (_state == State.END)
            {
                // Eat CR or LF white space, but not SP.
                int whiteSpace = 0;
                while (buffer.remaining() > 0)
                {
                    byte b = buffer.get(buffer.position());
                    if (b != HttpTokens.CARRIAGE_RETURN && b != HttpTokens.LINE_FEED)
                        break;
                    buffer.get();
                    ++whiteSpace;
                }
                if (debug && whiteSpace > 0)
                    LOG.debug("Discarded {} CR or LF characters", whiteSpace);
            }
            else if (isTerminated())
            {
                BufferUtil.clear(buffer);
            }

            // Handle EOF
            if (isAtEOF() && !buffer.hasRemaining())
            {
                switch (_state)
                {
                    case CLOSED:
                        break;

                    case END:
                    case CLOSE:
                        setState(State.CLOSED);
                        break;

                    case EOF_CONTENT:
                    case TRAILER:
                        if (_fieldState == FieldState.FIELD)
                        {
                            // Be forgiving of missing last CRLF
                            setState(State.CONTENT_END);
                            boolean handle = handleContentMessage();
                            if (handle && _state == State.CONTENT_END)
                                return true;
                            setState(State.CLOSED);
                            return handle;
                        }
                        setState(State.CLOSED);
                        _handler.earlyEOF();
                        break;

                    case START:
                    case CONTENT:
                    case CHUNKED_CONTENT:
                    case CHUNK_SIZE:
                    case CHUNK_PARAMS:
                    case CHUNK:
                        setState(State.CLOSED);
                        _handler.earlyEOF();
                        break;

                    default:
                        if (debug)
                            LOG.debug("{} EOF in {}", this, _state);
                        setState(State.CLOSED);
                        _handler.badMessage(new BadMessageException(HttpStatus.BAD_REQUEST_400));
                        break;
                }
            }
        }
        catch (BadMessageException x)
        {
            BufferUtil.clear(buffer);
            badMessage(x);
        }
        catch (Throwable x)
        {
            BufferUtil.clear(buffer);
            badMessage(new BadMessageException(HttpStatus.BAD_REQUEST_400, _requestHandler != null ? "Bad Request" : "Bad Response", x));
        }
        return false;
    }

    protected void badMessage(BadMessageException x)
    {
        if (debug)
            LOG.debug("Parse exception: " + this + " for " + _handler, x);
        setState(State.CLOSE);
        if (_headerComplete)
            _handler.earlyEOF();
        else
            _handler.badMessage(x);
    }

    protected boolean parseContent(ByteBuffer buffer)
    {
        int remaining = buffer.remaining();
        if (remaining == 0)
        {
            switch (_state)
            {
                case CONTENT:
                    long content = _contentLength - _contentPosition;
                    if (_endOfContent == EndOfContent.NO_CONTENT || content == 0)
                    {
                        setState(State.CONTENT_END);
                        return handleContentMessage();
                    }
                    break;
                case CONTENT_END:
                    setState(_endOfContent == EndOfContent.EOF_CONTENT ? State.CLOSED : State.END);
                    return _handler.messageComplete();
                default:
                    // No bytes to parse, return immediately.
                    return false;
            }
        }

        // Handle content.
        while (_state.ordinal() < State.TRAILER.ordinal() && remaining > 0)
        {
            switch (_state)
            {
                case EOF_CONTENT:
                    _contentChunk = buffer.asReadOnlyBuffer();
                    _contentPosition += remaining;
                    buffer.position(buffer.position() + remaining);
                    if (_handler.content(_contentChunk))
                        return true;
                    break;

                case CONTENT:
                {
                    long content = _contentLength - _contentPosition;
                    if (_endOfContent == EndOfContent.NO_CONTENT || content == 0)
                    {
                        setState(State.CONTENT_END);
                        return handleContentMessage();
                    }
                    else
                    {
                        _contentChunk = buffer.asReadOnlyBuffer();

                        // limit content by expected size
                        if (remaining > content)
                        {
                            // We can cast remaining to an int as we know that it is smaller than
                            // or equal to length which is already an int.
                            _contentChunk.limit(_contentChunk.position() + (int)content);
                        }

                        _contentPosition += _contentChunk.remaining();
                        buffer.position(buffer.position() + _contentChunk.remaining());

                        if (_handler.content(_contentChunk))
                            return true;

                        if (_contentPosition == _contentLength)
                        {
                            setState(State.CONTENT_END);
                            return handleContentMessage();
                        }
                    }
                    break;
                }

                case CHUNKED_CONTENT:
                {
                    HttpTokens.Token t = next(buffer);
                    if (t == null)
                        break;
                    switch (t.getType())
                    {
                        case LF:
                            break;

                        case DIGIT:
                            _chunkLength = t.getHexDigit();
                            _chunkPosition = 0;
                            setState(State.CHUNK_SIZE);
                            break;

                        case ALPHA:
                            if (t.isHexDigit())
                            {
                                _chunkLength = t.getHexDigit();
                                _chunkPosition = 0;
                                setState(State.CHUNK_SIZE);
                                break;
                            }
                            throw new IllegalCharacterException(_state, t, buffer);

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;
                }

                case CHUNK_SIZE:
                {
                    HttpTokens.Token t = next(buffer);
                    if (t == null)
                        break;

                    switch (t.getType())
                    {
                        case LF:
                            if (_chunkLength == 0)
                            {
                                setState(State.TRAILER);
                                if (_handler.contentComplete())
                                    return true;
                            }
                            else
                                setState(State.CHUNK);
                            break;

                        case SPACE:
                            setState(State.CHUNK_PARAMS);
                            break;

                        default:
                            if (t.isHexDigit())
                            {
                                if (_chunkLength > MAX_CHUNK_LENGTH)
                                    throw new BadMessageException(HttpStatus.PAYLOAD_TOO_LARGE_413);
                                _chunkLength = _chunkLength * 16 + t.getHexDigit();
                            }
                            else
                            {
                                setState(State.CHUNK_PARAMS);
                            }
                    }
                    break;
                }

                case CHUNK_PARAMS:
                {
                    HttpTokens.Token t = next(buffer);
                    if (t == null)
                        break;

                    switch (t.getType())
                    {
                        case LF:
                            if (_chunkLength == 0)
                            {
                                setState(State.TRAILER);
                                if (_handler.contentComplete())
                                    return true;
                            }
                            else
                                setState(State.CHUNK);
                            break;
                        default:
                            break; // TODO review
                    }
                    break;
                }

                case CHUNK:
                {
                    int chunk = _chunkLength - _chunkPosition;
                    if (chunk == 0)
                    {
                        setState(State.CHUNKED_CONTENT);
                    }
                    else
                    {
                        _contentChunk = buffer.asReadOnlyBuffer();

                        if (remaining > chunk)
                            _contentChunk.limit(_contentChunk.position() + chunk);
                        chunk = _contentChunk.remaining();

                        _contentPosition += chunk;
                        _chunkPosition += chunk;
                        buffer.position(buffer.position() + chunk);
                        if (_handler.content(_contentChunk))
                            return true;
                    }
                    break;
                }

                case CONTENT_END:
                {
                    setState(_endOfContent == EndOfContent.EOF_CONTENT ? State.CLOSED : State.END);
                    return _handler.messageComplete();
                }

                default:
                    break;
            }

            remaining = buffer.remaining();
        }
        return false;
    }

    public boolean isAtEOF()
    {
        return _eof;
    }

    /**
     * Signal that the associated data source is at EOF
     */
    public void atEOF()
    {
        if (debug)
            LOG.debug("atEOF {}", this);
        _eof = true;
    }

    /**
     * Request that the associated data source be closed
     */
    public void close()
    {
        if (debug)
            LOG.debug("close {}", this);
        setState(State.CLOSE);
    }

    public void reset()
    {
        if (debug)
            LOG.debug("reset {}", this);

        // reset state
        if (_state == State.CLOSE || _state == State.CLOSED)
            return;

        setState(State.START);
        _endOfContent = EndOfContent.UNKNOWN_CONTENT;
        _contentLength = -1;
        _hasContentLength = false;
        _hasTransferEncoding = false;
        _contentPosition = 0;
        _responseStatus = 0;
        _contentChunk = null;
        _headerBytes = 0;
        _host = false;
        _headerComplete = false;
    }

    protected void setState(State state)
    {
        if (debug)
            LOG.debug("{} --> {}", _state, state);
        _state = state;
    }

    protected void setState(FieldState state)
    {
        if (debug)
            LOG.debug("{}:{} --> {}", _state, _field != null ? _field : _headerString != null ? _headerString : _string, state);
        _fieldState = state;
    }

    public Trie<HttpField> getFieldCache()
    {
        return _fieldCache;
    }

    @Override
    public String toString()
    {
        return String.format("%s{s=%s,%d of %d}",
            getClass().getSimpleName(),
            _state,
            getContentRead(),
            getContentLength());
    }

    /* Event Handler interface
     * These methods return true if the caller should process the events
     * so far received (eg return from parseNext and call HttpChannel.handle).
     * If multiple callbacks are called in sequence (eg
     * headerComplete then messageComplete) from the same point in the parsing
     * then it is sufficient for the caller to process the events only once.
     */
    public interface HttpHandler
    {
        boolean content(ByteBuffer item);

        boolean headerComplete();

        boolean contentComplete();

        boolean messageComplete();

        /**
         * This is the method called by parser when an HTTP Header name and value is found
         *
         * @param field The field parsed
         */
        void parsedHeader(HttpField field);

        /**
         * This is the method called by parser when an HTTP Trailer name and value is found
         *
         * @param field The field parsed
         */
        default void parsedTrailer(HttpField field)
        {
        }

        /**
         * Called to signal that an EOF was received unexpectedly
         * during the parsing of an HTTP message
         */
        void earlyEOF();

        /**
         * Called to signal that a bad HTTP message has been received.
         *
         * @param failure the failure with the bad message information
         */
        default void badMessage(BadMessageException failure)
        {
            badMessage(failure.getCode(), failure.getReason());
        }

        /**
         * @deprecated use {@link #badMessage(BadMessageException)} instead
         */
        @Deprecated
        default void badMessage(int status, String reason)
        {
        }

        /**
         * @return the size in bytes of the per parser header cache
         */
        int getHeaderCacheSize();
    }

    public interface RequestHandler extends HttpHandler
    {
        /**
         * This is the method called by parser when the HTTP request line is parsed
         *
         * @param method The method
         * @param uri The raw bytes of the URI.  These are copied into a ByteBuffer that will not be changed until this parser is reset and reused.
         * @param version the http version in use
         * @return true if handling parsing should return.
         */
        boolean startRequest(String method, String uri, HttpVersion version);
    }

    public interface ResponseHandler extends HttpHandler
    {
        /**
         * This is the method called by parser when the HTTP request line is parsed
         *
         * @param version the http version in use
         * @param status the response status
         * @param reason the response reason phrase
         * @return true if handling parsing should return
         */
        boolean startResponse(HttpVersion version, int status, String reason);
    }

    public interface ComplianceHandler extends HttpHandler
    {
        @Deprecated
        default void onComplianceViolation(HttpCompliance compliance, HttpCompliance required, String reason)
        {
        }

        default void onComplianceViolation(HttpCompliance compliance, HttpComplianceSection violation, String details)
        {
            onComplianceViolation(compliance, HttpCompliance.requiredCompliance(violation), details);
        }
    }

    private static class IllegalCharacterException extends BadMessageException
    {
        private IllegalCharacterException(State state, HttpTokens.Token token, ByteBuffer buffer)
        {
            super(400, String.format("Illegal character %s", token));
            if (LOG.isDebugEnabled())
                LOG.debug(String.format("Illegal character %s in state=%s for buffer %s", token, state, BufferUtil.toDetailString(buffer)));
        }
    }
}