zenith-http1 0.1.0

Zenith HTTP/1.1 协议解析器(RFC 7230):零堆分配热路径、流式解析、CRLF 防注入
Documentation
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
//! HTTP/1.1 客户端编解码(反向代理上游转发专用)
//!
//! 本模块提供反向代理转发闭环的最小客户端能力:
//! - [`encode_request`]:将规范化请求编码为 HTTP/1.1 线格式(固定 `Connection: close`,
//!   v1 不做上游 keep-alive 复用)
//! - [`parse_response`]:**增量式**响应解析——数据不足返回 `Ok(None)`,
//!   完整响应返回 `Ok(Some((响应, 消费字节数)))`
//! - [`parse_response_eof`]:connection-close 语义兜底——无 `Content-Length` 且无
//!   `Transfer-Encoding` 时,由调用方读到 EOF 后调用,剩余字节全部视为 body
//!
//! 支持的三种 body 分帧(严格 RFC 7230 §3.3.3,与服务端 parser 同一套语义):
//! 1. `Transfer-Encoding: chunked` → 完整 chunked 解码(十六进制块大小、CRLF、
//!    零块终止、trailer 忽略)
//! 2. `Content-Length: N` → 恰好 N 字节
//! 3. 两者皆无 → connection-close(读到 EOF,由 [`parse_response_eof`] 兜底)
//!
//! # 安全保证(fail-closed)
//! - method/path/host/头名/头值含 `\r` 或 `\n` → [`encode_request`] 返回 `None`
//!   (CRLF 注入防护,绝不静默放行)
//! - 响应头区超过 [`MAX_HEADER_SECTION`](64 KiB,无论终止标记是否已找到)→ Err
//! - 响应头条数 / 单名 / 单值超 [`MAX_HEADER_COUNT`] / [`MAX_HEADER_NAME_LEN`] /
//!   [`MAX_HEADER_VALUE_LEN`] → Err(与服务端 parser 防线对称,M-4)
//! - Content-Length 与 Transfer-Encoding 共存 / 多个不同的 Content-Length → Err
//!   (请求走私防护)
//! - 非法状态行 / 非法头部 → Err,绝不截断放行

use std::fmt;

use crate::chunked::ChunkedDecoder;
use crate::types::Http1Error;

/// 响应头区硬上限(64 KiB,含 `\r\n\r\n` 终止标记),超限 fail-closed
pub const MAX_HEADER_SECTION: usize = 64 * 1024;

/// 响应头条数硬上限(与服务端 parser `max_header_count` 默认 256 对称,M-4)
pub const MAX_HEADER_COUNT: usize = 256;

/// 单个响应头名硬上限(与服务端 parser `max_header_name_len` 默认 64 对称,M-4)
pub const MAX_HEADER_NAME_LEN: usize = 64;

/// 单个响应头值硬上限(与服务端 parser `max_header_value_len` 默认 8192 对称,M-4)
pub const MAX_HEADER_VALUE_LEN: usize = 8192;

/// 上游响应 body 硬上限(64 MiB),超限 fail-closed
///
/// 反向代理场景下恶意上游可声明超大 Content-Length 或无限 chunked 流,
/// 无上限将导致内存耗尽(OOM)。调用方如需更小上限应在读取层先行截断
/// (如 zenith-proxy 的 `ForwardConfig::max_response_bytes`)。
pub const MAX_BODY_BYTES: u64 = 64 * 1024 * 1024;

/// 上游响应(代理解析结果)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientResponse {
    /// 状态码(三位数字)
    pub status: u16,
    /// 响应头(保留原始大小写与顺序)
    pub headers: Vec<(String, String)>,
    /// 响应体(chunked 已解码)
    pub body: Vec<u8>,
}

/// 代理客户端错误
#[derive(Debug)]
pub enum ClientError {
    /// 状态行格式非法
    InvalidStatusLine,
    /// 头部格式非法
    InvalidHeader(String),
    /// 头区超过 64 KiB 上限
    HeaderTooLarge,
    /// body 超过上限
    BodyTooLarge,
    /// chunked 编码错误
    InvalidChunked(String),
    /// 协议不一致(CL/TE 共存、多个不同 CL 等,请求走私前兆)
    ProtocolInconsistency(String),
    /// 响应不完整(EOF 先于完整响应到达,截断响应 fail-closed)
    Truncated,
}

impl fmt::Display for ClientError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidStatusLine => write!(f, "upstream status line invalid"),
            Self::InvalidHeader(m) => write!(f, "upstream header invalid: {m}"),
            Self::HeaderTooLarge => write!(f, "upstream header section too large"),
            Self::BodyTooLarge => write!(f, "upstream body too large"),
            Self::InvalidChunked(m) => write!(f, "upstream chunked encoding error: {m}"),
            Self::ProtocolInconsistency(m) => write!(f, "upstream protocol inconsistency: {m}"),
            Self::Truncated => write!(f, "upstream response truncated"),
        }
    }
}

impl std::error::Error for ClientError {}

/// 头名字符合法性(RFC 7230 token)
#[inline]
fn is_valid_token(s: &str) -> bool {
    !s.is_empty()
        && s.bytes().all(|b| {
            b.is_ascii_alphanumeric()
                || matches!(
                    b,
                    b'!' | b'#'
                        | b'$'
                        | b'%'
                        | b'&'
                        | b'\''
                        | b'*'
                        | b'+'
                        | b'-'
                        | b'.'
                        | b'^'
                        | b'_'
                        | b'`'
                        | b'|'
                        | b'~'
                )
        })
}

/// 是否含 CR/LF(CRLF 注入判定)
#[inline]
fn contains_crlf(s: &str) -> bool {
    s.contains('\r') || s.contains('\n')
}

/// 编码 HTTP/1.1 请求(代理转发上游)
///
/// 输出布局:请求行 + `Host` + 透传头 + `Content-Length` + `Connection: close` + 空行 + body。
///
/// # 参数
/// - `method`:请求方法(RFC 7230 token,如 `GET`)
/// - `path_with_query`:路径 + 可选查询串(`?` 已拼接)
/// - `host`:Host 头值(透传原始 Host)
/// - `headers`:透传头;调用方负责剔除 `host` / `connection` / `content-length` 旧值
/// - `body`:请求体(始终写 `Content-Length`,即使为 0)
///
/// # 返回
/// - `Some(bytes)`:编码后的线格式字节
/// - `None`:method/path/host/任一头名或头值含 `\r` / `\n`,或 method 非 token、
///   path/host 为空——**fail-closed 整体拒绝,绝不静默放行或改写**
pub fn encode_request(
    method: &str,
    path_with_query: &str,
    host: &str,
    headers: &[(String, String)],
    body: &[u8],
) -> Option<Vec<u8>> {
    // CRLF 注入防护:请求行三要素任一含 CR/LF 即整体拒绝(fail-closed)
    if !is_valid_token(method)
        || path_with_query.is_empty()
        || contains_crlf(path_with_query)
        || path_with_query.contains(' ')
        || host.is_empty()
        || contains_crlf(host)
    {
        return None;
    }
    // 透传头逐一校验:任一头名/头值含 CR/LF 即整体拒绝(不放行、不跳过、不改写)
    for (name, value) in headers {
        if !is_valid_token(name) || contains_crlf(value) {
            return None;
        }
    }

    // 预分配:请求行 + 头 + body 的估计容量,避免热路径反复扩容
    let mut out = Vec::with_capacity(method.len() + path_with_query.len() + host.len() + body.len() + 256);
    out.extend_from_slice(method.as_bytes());
    out.push(b' ');
    out.extend_from_slice(path_with_query.as_bytes());
    out.extend_from_slice(b" HTTP/1.1\r\nHost: ");
    out.extend_from_slice(host.as_bytes());
    out.extend_from_slice(b"\r\n");

    for (name, value) in headers {
        out.extend_from_slice(name.as_bytes());
        out.extend_from_slice(b": ");
        out.extend_from_slice(value.as_bytes());
        out.extend_from_slice(b"\r\n");
    }

    out.extend_from_slice(b"Content-Length: ");
    out.extend_from_slice(body.len().to_string().as_bytes());
    // v1 不做上游 keep-alive:固定 close,响应读到 EOF 即连接终止
    out.extend_from_slice(b"\r\nConnection: close\r\n\r\n");
    out.extend_from_slice(body);
    Some(out)
}

/// 在缓冲区中查找头区结束标记 `\r\n\r\n`,返回其起始下标
#[inline]
fn find_header_end(buf: &[u8]) -> Option<usize> {
    buf.windows(4).position(|w| w == b"\r\n\r\n")
}

/// 解析状态行 `HTTP/1.x <status> <reason>`(reason 可空)
fn parse_status_line(line: &[u8]) -> Result<u16, ClientError> {
    let s = std::str::from_utf8(line).map_err(|_| ClientError::InvalidStatusLine)?;
    let mut parts = s.splitn(3, ' ');
    let version = parts.next().ok_or(ClientError::InvalidStatusLine)?;
    // 仅接受 HTTP/1.x(本客户端只发 HTTP/1.1 请求,2/3 响应视为格式错误)
    let ver_ok = version.len() == 8
        && version.starts_with("HTTP/1.")
        && version.as_bytes()[7].is_ascii_digit();
    if !ver_ok {
        return Err(ClientError::InvalidStatusLine);
    }
    let status_str = parts.next().ok_or(ClientError::InvalidStatusLine)?;
    if status_str.len() != 3 || !status_str.bytes().all(|b| b.is_ascii_digit()) {
        return Err(ClientError::InvalidStatusLine);
    }
    status_str
        .parse::<u16>()
        .map_err(|_| ClientError::InvalidStatusLine)
}

/// 解析头区为 (status, headers)
///
/// H-4 修复:按 `\n` 切行后,非最后一行必须以 `\r` 结尾——否则为裸 LF(协议违规)。
/// 在代理转发场景下,恶意上游利用裸 LF 可注入额外头部;严格拒绝以阻断注入。
/// 最后一行无需 `\r`:head 截取自 `\r\n\r\n` 终止符之前,最后一段的 `\r` 属于终止符。
fn parse_head(head: &[u8]) -> Result<(u16, Vec<(String, String)>), ClientError> {
    let lines: Vec<&[u8]> = head.split(|&b| b == b'\n').collect();
    let total = lines.len();
    if total == 0 {
        return Err(ClientError::InvalidStatusLine);
    }
    let status_line = lines[0];
    let status_line = if total > 1 {
        match status_line.last() {
            Some(b'\r') => &status_line[..status_line.len() - 1],
            _ => {
                return Err(ClientError::InvalidHeader(
                    "bare LF in status line (protocol violation)".into(),
                ))
            }
        }
    } else {
        match status_line.last() {
            Some(b'\r') => &status_line[..status_line.len() - 1],
            _ => status_line,
        }
    };
    let status = parse_status_line(status_line)?;

    let mut headers: Vec<(String, String)> = Vec::new();
    for (i, raw) in lines.iter().enumerate().skip(1) {
        let line = if i < total - 1 {
            match raw.last() {
                Some(b'\r') => &raw[..raw.len() - 1],
                _ => {
                    return Err(ClientError::InvalidHeader(
                        "bare LF in header line (protocol violation)".into(),
                    ))
                }
            }
        } else {
            match raw.last() {
                Some(b'\r') => &raw[..raw.len() - 1],
                _ => raw,
            }
        };
        if line.is_empty() {
            continue;
        }
        let colon = line
            .iter()
            .position(|&b| b == b':')
            .ok_or_else(|| ClientError::InvalidHeader("missing colon".into()))?;
        let name = std::str::from_utf8(&line[..colon])
            .map_err(|_| ClientError::InvalidHeader("name not UTF-8".into()))?;
        if !is_valid_token(name) {
            return Err(ClientError::InvalidHeader(format!(
                "invalid header name: {name:?}"
            )));
        }
        // M-4:单名长度上限(与服务端 parser 防线对称,fail-closed)
        if name.len() > MAX_HEADER_NAME_LEN {
            return Err(ClientError::HeaderTooLarge);
        }
        let value_raw = &line[colon + 1..];
        // 去除首尾 OWS(空格 / 水平制表符)
        let mut start = 0;
        let mut end = value_raw.len();
        while start < end && matches!(value_raw[start], b' ' | b'\t') {
            start += 1;
        }
        while end > start && matches!(value_raw[end - 1], b' ' | b'\t') {
            end -= 1;
        }
        // M-4:单值长度上限(与服务端 parser 防线对称,fail-closed)
        if end - start > MAX_HEADER_VALUE_LEN {
            return Err(ClientError::HeaderTooLarge);
        }
        let value = std::str::from_utf8(&value_raw[start..end])
            .map_err(|_| ClientError::InvalidHeader("value not UTF-8".into()))?;
        headers.push((name.to_string(), value.to_string()));
        // M-4:条数上限(恶意上游海量头部耗尽内存的防线)
        if headers.len() > MAX_HEADER_COUNT {
            return Err(ClientError::HeaderTooLarge);
        }
    }
    Ok((status, headers))
}

/// body 分帧形态(RFC 7230 §3.3.3)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BodyFraming {
    /// 无 body(1xx / 204 / 304 状态码禁止携带 body)
    Bodiless,
    /// Transfer-Encoding: chunked
    Chunked,
    /// Content-Length: N
    Length(usize),
    /// 无长度头:connection-close 语义(读到 EOF)
    UntilEof,
}

/// 判定 body 分帧形态(含请求走私防护)
fn determine_framing(
    status: u16,
    headers: &[(String, String)],
) -> Result<BodyFraming, ClientError> {
    // 1xx / 204 / 304 MUST NOT 携带 body(RFC 7230 §3.3.1/§3.3.2)
    if matches!(status, 100..=199) || status == 204 || status == 304 {
        return Ok(BodyFraming::Bodiless);
    }

    let mut content_lengths: Vec<usize> = Vec::new();
    let mut chunked = false;
    for (name, value) in headers {
        if name.eq_ignore_ascii_case("content-length") {
            // u64 解析后转 usize,32/64 位平台均 fail-closed(拒绝超平台范围的值)
            let n: u64 = value
                .trim()
                .parse()
                .map_err(|_| ClientError::InvalidHeader("content-length not a number".into()))?;
            let n = usize::try_from(n)
                .map_err(|_| ClientError::BodyTooLarge)?;
            content_lengths.push(n);
        } else if name.eq_ignore_ascii_case("transfer-encoding") {
            // 逐 token 匹配(如 "gzip, chunked")
            for token in value.split(',') {
                if token.trim().eq_ignore_ascii_case("chunked") {
                    chunked = true;
                }
            }
        }
    }

    // CL/TE 共存 = 请求走私经典前兆,fail-closed
    if chunked && !content_lengths.is_empty() {
        return Err(ClientError::ProtocolInconsistency(
            "content-length with transfer-encoding".into(),
        ));
    }
    // 多个不同的 Content-Length 同样拒绝(相同值的重复头按 RFC 7230 §3.3.2 允许)
    if let Some(first) = content_lengths.first()
        && content_lengths.iter().any(|n| n != first)
    {
        return Err(ClientError::ProtocolInconsistency(
            "conflicting content-length headers".into(),
        ));
    }

    if chunked {
        Ok(BodyFraming::Chunked)
    } else if let Some(&len) = content_lengths.first() {
        Ok(BodyFraming::Length(len))
    } else {
        Ok(BodyFraming::UntilEof)
    }
}

/// 增量解析 HTTP/1.1 上游响应
///
/// # 返回
/// - `Ok(Some((response, consumed)))`:完整响应 + 消费字节数(调用方可据此处理粘包)
/// - `Ok(None)`:数据不足,调用方应继续读取后重试
/// - `Err(_)`:格式非法 / 超限 / 走私前兆,fail-closed
///
/// # 分帧语义
/// - `Content-Length` / `chunked`:数据齐全即完成,无需等待 EOF
/// - 无长度头:始终返回 `Ok(None)`,由调用方读到 EOF 后调用 [`parse_response_eof`]
pub fn parse_response(buf: &[u8]) -> Result<Option<(ClientResponse, usize)>, ClientError> {
    let head_end = match find_header_end(buf) {
        Some(pos) => pos,
        None => {
            // 头区未齐:超过硬上限 fail-closed,否则等待更多数据
            if buf.len() > MAX_HEADER_SECTION {
                return Err(ClientError::HeaderTooLarge);
            }
            return Ok(None);
        }
    };
    // M-4:找到终止标记后同样强制头区总字节上限(含 4 字节终止标记)
    if head_end.saturating_add(4) > MAX_HEADER_SECTION {
        return Err(ClientError::HeaderTooLarge);
    }
    let (status, headers) = parse_head(&buf[..head_end])?;
    let body_start = head_end.saturating_add(4);
    let body_bytes = &buf[body_start..];

    match determine_framing(status, &headers)? {
        BodyFraming::Bodiless => Ok(Some((
            ClientResponse {
                status,
                headers,
                body: Vec::new(),
            },
            body_start,
        ))),
        BodyFraming::Length(len) => {
            // body 硬上限:恶意上游声明超大 Content-Length → fail-closed(防 OOM)
            if len as u64 > MAX_BODY_BYTES {
                return Err(ClientError::BodyTooLarge);
            }
            // checked 算术:head_end + 4 + len 溢出按超限处理(fail-closed)
            let need = body_start.checked_add(len).ok_or(ClientError::BodyTooLarge)?;
            if buf.len() < need {
                return Ok(None);
            }
            Ok(Some((
                ClientResponse {
                    status,
                    headers,
                    body: buf[body_start..need].to_vec(),
                },
                need,
            )))
        }
        BodyFraming::Chunked => {
            // 复用服务端同款 ChunkedDecoder(语义一致);
            // 每次调用全量重喂 body 前缀(无状态增量解析,v1 以正确性优先)
            // 上限 MAX_BODY_BYTES:恶意上游无限 chunked 流 → fail-closed(防 OOM)
            let mut dec = ChunkedDecoder::new(MAX_BODY_BYTES);
            let (out, consumed) = dec.feed(body_bytes).map_err(|e| match e {
                Http1Error::BodyTooLarge => ClientError::BodyTooLarge,
                other => ClientError::InvalidChunked(other.to_string()),
            })?;
            if dec.is_done() {
                Ok(Some((
                    ClientResponse {
                        status,
                        headers,
                        body: out,
                    },
                    body_start.saturating_add(consumed),
                )))
            } else {
                Ok(None)
            }
        }
        // connection-close 语义:增量解析无法判定完成,等待 EOF 兜底
        BodyFraming::UntilEof => Ok(None),
    }
}

/// 有状态增量响应解析器
///
/// 解决 [`parse_response`] 在 chunked 分帧下 O(n²) 的性能问题:
/// 维持 `ChunkedDecoder` 跨调用,仅处理新增字节,总复杂度 O(n)。
///
/// # 用法
///
/// ```ignore
/// let mut parser = ResponseParser::new();
/// loop {
///     // 读取数据追加到 buf...
///     match parser.feed(&buf)? {
///         Some((resp, consumed)) => { /* 完整响应 */ break; }
///         None => { /* 等待更多数据 */ }
///     }
/// }
/// ```
#[derive(Debug)]
pub struct ResponseParser {
    /// 头部解析状态(仅首次调用时解析,之后复用)
    head: Option<ParsedHead>,
    /// Chunked decoder(仅 chunked 分帧时初始化)
    chunked_decoder: Option<ChunkedDecoder>,
    /// 已处理的 body 字节数(跳过已解析部分)
    body_processed: usize,
    /// 累积的 chunked 解码输出
    chunked_output: Vec<u8>,
}

#[derive(Debug, Clone)]
struct ParsedHead {
    status: u16,
    headers: Vec<(String, String)>,
    body_start: usize,
    framing: BodyFraming,
}

impl ResponseParser {
    /// 创建解析器
    #[inline]
    pub fn new() -> Self {
        Self {
            head: None,
            chunked_decoder: None,
            body_processed: 0,
            chunked_output: Vec::new(),
        }
    }

    /// 增量解析:输入当前全量缓冲,返回已完成的响应或等待更多数据
    ///
    /// 与 [`parse_response`] API 兼容:返回 `Ok(Some((resp, consumed)))` 表示
    /// 完整响应已就绪(`consumed` 为从头开始的消费字节数),`Ok(None)` 表示
    /// 等待更多数据。
    pub fn feed(&mut self, buf: &[u8]) -> Result<Option<(ClientResponse, usize)>, ClientError> {
        // Phase 1: 解析头部(仅首次调用)
        if self.head.is_none() {
            let head_end = match find_header_end(buf) {
                Some(pos) => pos,
                None => {
                    if buf.len() > MAX_HEADER_SECTION {
                        return Err(ClientError::HeaderTooLarge);
                    }
                    return Ok(None);
                }
            };
            if head_end.saturating_add(4) > MAX_HEADER_SECTION {
                return Err(ClientError::HeaderTooLarge);
            }
            let (status, headers) = parse_head(&buf[..head_end])?;
            let body_start = head_end.saturating_add(4);
            let framing = determine_framing(status, &headers)?;
            self.head = Some(ParsedHead {
                status,
                headers,
                body_start,
                framing,
            });
        }

        let head = self.head.as_ref().expect("head just parsed");
        let body_bytes = &buf[head.body_start..];

        match head.framing {
            BodyFraming::Bodiless => Ok(Some((
                ClientResponse {
                    status: head.status,
                    headers: head.headers.clone(),
                    body: Vec::new(),
                },
                head.body_start,
            ))),
            BodyFraming::Length(len) => {
                if len as u64 > MAX_BODY_BYTES {
                    return Err(ClientError::BodyTooLarge);
                }
                let need = head
                    .body_start
                    .checked_add(len)
                    .ok_or(ClientError::BodyTooLarge)?;
                if buf.len() < need {
                    return Ok(None);
                }
                Ok(Some((
                    ClientResponse {
                        status: head.status,
                        headers: head.headers.clone(),
                        body: buf[head.body_start..need].to_vec(),
                    },
                    need,
                )))
            }
            BodyFraming::Chunked => {
                // 初始化 decoder(仅首次)
                if self.chunked_decoder.is_none() {
                    self.chunked_decoder = Some(ChunkedDecoder::new(MAX_BODY_BYTES));
                }
                let decoder = self.chunked_decoder.as_mut().expect("just initialized");

                // 仅处理新增字节(从 body_processed 开始)
                let new_data = &body_bytes[self.body_processed..];
                if !new_data.is_empty() {
                    let (out, consumed) = decoder
                        .feed(new_data)
                        .map_err(|e| match e {
                            Http1Error::BodyTooLarge => ClientError::BodyTooLarge,
                            other => ClientError::InvalidChunked(other.to_string()),
                        })?;
                    self.body_processed += consumed;
                    self.chunked_output.extend_from_slice(&out);

                    if decoder.is_done() {
                        let total_consumed = head.body_start + self.body_processed;
                        let body = std::mem::take(&mut self.chunked_output);
                        return Ok(Some((
                            ClientResponse {
                                status: head.status,
                                headers: head.headers.clone(),
                                body,
                            },
                            total_consumed,
                        )));
                    }
                }
                Ok(None)
            }
            BodyFraming::UntilEof => Ok(None),
        }
    }
}

impl Default for ResponseParser {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// EOF 兜底解析(connection-close 语义)
///
/// 调用方读到 EOF 后调用:
/// - 无长度头:头区之后的全部字节视为 body
/// - `Content-Length` / `chunked`:委托 [`parse_response`],数据不齐 → [`ClientError::Truncated`]
///
/// # 错误
/// 头区未齐即 EOF、或声明的长度未读满即 EOF → Err(截断响应 fail-closed,绝不放行)
pub fn parse_response_eof(buf: &[u8]) -> Result<ClientResponse, ClientError> {
    let head_end = find_header_end(buf).ok_or(ClientError::Truncated)?;
    let (status, headers) = parse_head(&buf[..head_end])?;
    let body_start = head_end.saturating_add(4);

    match determine_framing(status, &headers)? {
        BodyFraming::UntilEof => Ok(ClientResponse {
            status,
            headers,
            body: buf[body_start..].to_vec(),
        }),
        // 有明确分帧的响应必须完整到达,否则视为截断
        _ => match parse_response(buf)? {
            Some((resp, _)) => Ok(resp),
            None => Err(ClientError::Truncated),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ───────── encode_request 测试 ─────────

    #[test]
    fn encode_basic_get() {
        let out = encode_request("GET", "/api/x?a=1", "127.0.0.1:8080", &[], b"");
        let out = match out {
            Some(v) => v,
            None => panic!("encode should succeed"),
        };
        let s = String::from_utf8_lossy(&out);
        assert!(s.starts_with("GET /api/x?a=1 HTTP/1.1\r\n"));
        assert!(s.contains("Host: 127.0.0.1:8080\r\n"));
        assert!(s.contains("Content-Length: 0\r\n"));
        assert!(s.contains("Connection: close\r\n"));
        assert!(s.ends_with("\r\n\r\n"));
    }

    #[test]
    fn encode_post_with_body_and_headers() {
        let headers = vec![
            ("content-type".to_string(), "application/json".to_string()),
            ("x-token".to_string(), "abc".to_string()),
        ];
        let out = encode_request("POST", "/echo", "up:9000", &headers, b"hello");
        let out = match out {
            Some(v) => v,
            None => panic!("encode should succeed"),
        };
        let s = String::from_utf8_lossy(&out);
        assert!(s.starts_with("POST /echo HTTP/1.1\r\n"));
        assert!(s.contains("content-type: application/json\r\n"));
        assert!(s.contains("x-token: abc\r\n"));
        assert!(s.contains("Content-Length: 5\r\n"));
        assert!(s.ends_with("\r\n\r\nhello"));
    }

    #[test]
    fn encode_rejects_crlf_injection_fail_closed() {
        // method/path/host 含 CR/LF → None(绝不静默放行)
        assert!(encode_request("GET\r\nEvil: x", "/", "h", &[], b"").is_none());
        assert!(encode_request("GET", "/a\r\nb", "h", &[], b"").is_none());
        assert!(encode_request("GET", "/", "ho\r\nst", &[], b"").is_none());
        assert!(encode_request("GET", "/a\nb", "h", &[], b"").is_none());
        // 头名/头值含 CR/LF → None
        let bad_value = vec![("x-bad".to_string(), "evil\r\nInjected: yes".to_string())];
        assert!(encode_request("GET", "/", "h", &bad_value, b"").is_none());
        let bad_name = vec![("x-bad\r\nInjected".to_string(), "v".to_string())];
        assert!(encode_request("GET", "/", "h", &bad_name, b"").is_none());
        // 非法 method / 空 path / 空 host / 空头名 → None
        assert!(encode_request("GE T", "/", "h", &[], b"").is_none());
        assert!(encode_request("", "/", "h", &[], b"").is_none());
        assert!(encode_request("GET", "", "h", &[], b"").is_none());
        assert!(encode_request("GET", "/", "", &[], b"").is_none());
        let empty_name = vec![("".to_string(), "v".to_string())];
        assert!(encode_request("GET", "/", "h", &empty_name, b"").is_none());
    }

    // ───────── parse_response:Content-Length 分帧 ─────────

    #[test]
    fn parse_content_length_response() {
        let raw = b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhello";
        let r = parse_response(raw);
        let (resp, consumed) = match r {
            Ok(Some(v)) => v,
            other => panic!("expected complete response, got {other:?}"),
        };
        assert_eq!(resp.status, 200);
        assert_eq!(resp.body, b"hello");
        assert_eq!(consumed, raw.len());
        assert_eq!(
            resp.headers,
            vec![
                ("Content-Type".to_string(), "text/plain".to_string()),
                ("Content-Length".to_string(), "5".to_string()),
            ]
        );
    }

    #[test]
    fn parse_content_length_incremental_feed() {
        // 逐字节喂入:完整前必须 Ok(None),完整后立即 Some
        let raw = b"HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nhello world";
        for i in 0..raw.len() {
            match parse_response(&raw[..i]) {
                Ok(None) => {}
                other => panic!("prefix {i} should be incomplete, got {other:?}"),
            }
        }
        match parse_response(raw) {
            Ok(Some((resp, consumed))) => {
                assert_eq!(resp.body, b"hello world");
                assert_eq!(consumed, raw.len());
            }
            other => panic!("full input should complete, got {other:?}"),
        }
    }

    #[test]
    fn parse_content_length_sticky_packet_consumed() {
        // 粘包:响应后紧跟多余字节,consumed 必须精确指向响应末尾
        let raw = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhiNEXT-REQUEST-BYTES";
        match parse_response(raw) {
            Ok(Some((resp, consumed))) => {
                assert_eq!(resp.body, b"hi");
                assert_eq!(&raw[consumed..], b"NEXT-REQUEST-BYTES");
            }
            other => panic!("expected complete, got {other:?}"),
        }
    }

    #[test]
    fn parse_status_without_reason_phrase() {
        let raw = b"HTTP/1.1 200\r\nContent-Length: 0\r\n\r\n";
        match parse_response(raw) {
            Ok(Some((resp, _))) => assert_eq!(resp.status, 200),
            other => panic!("expected complete, got {other:?}"),
        }
    }

    #[test]
    fn parse_http10_response() {
        let raw = b"HTTP/1.0 302 Found\r\nContent-Length: 2\r\n\r\nok";
        match parse_response(raw) {
            Ok(Some((resp, _))) => {
                assert_eq!(resp.status, 302);
                assert_eq!(resp.body, b"ok");
            }
            other => panic!("expected complete, got {other:?}"),
        }
    }

    #[test]
    fn parse_bodiless_status_complete_without_body() {
        // 204 无长度头也必须立即完成(禁止 body),不能等 EOF
        let raw = b"HTTP/1.1 204 No Content\r\nX-A: b\r\n\r\n";
        match parse_response(raw) {
            Ok(Some((resp, consumed))) => {
                assert_eq!(resp.status, 204);
                assert!(resp.body.is_empty());
                assert_eq!(consumed, raw.len());
            }
            other => panic!("204 should complete immediately, got {other:?}"),
        }
        // 304 同理
        let raw304 = b"HTTP/1.1 304 Not Modified\r\n\r\n";
        match parse_response(raw304) {
            Ok(Some((resp, _))) => assert_eq!(resp.status, 304),
            other => panic!("304 should complete immediately, got {other:?}"),
        }
    }

    #[test]
    fn parse_duplicate_identical_content_length_ok() {
        let raw = b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nContent-Length: 3\r\n\r\nabc";
        match parse_response(raw) {
            Ok(Some((resp, _))) => assert_eq!(resp.body, b"abc"),
            other => panic!("expected complete, got {other:?}"),
        }
    }

    // ───────── parse_response:chunked 分帧 ─────────

    #[test]
    fn parse_chunked_response() {
        let raw = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n";
        match parse_response(raw) {
            Ok(Some((resp, consumed))) => {
                assert_eq!(resp.status, 200);
                assert_eq!(resp.body, b"hello world");
                assert_eq!(consumed, raw.len());
            }
            other => panic!("expected complete, got {other:?}"),
        }
    }

    #[test]
    fn parse_chunked_with_trailer_ignored() {
        let raw = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nhi\r\n0\r\nX-Trailer: v\r\n\r\n";
        match parse_response(raw) {
            Ok(Some((resp, _))) => assert_eq!(resp.body, b"hi"),
            other => panic!("expected complete, got {other:?}"),
        }
    }

    #[test]
    fn parse_chunked_incremental_across_chunks() {
        // chunked 跨块增量喂入:零块未到时一律 Ok(None)
        let raw = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n";
        let mut saw_complete_before_full = false;
        for i in 0..raw.len() {
            if let Ok(Some(_)) = parse_response(&raw[..i]) {
                saw_complete_before_full = true;
            }
        }
        assert!(!saw_complete_before_full, "chunked must not complete before terminator");
        match parse_response(raw) {
            Ok(Some((resp, _))) => assert_eq!(resp.body, b"hello world"),
            other => panic!("expected complete, got {other:?}"),
        }
    }

    #[test]
    fn parse_chunked_uppercase_hex_and_extension() {
        let raw = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nA;ext=1\r\n0123456789\r\n0\r\n\r\n";
        match parse_response(raw) {
            Ok(Some((resp, _))) => assert_eq!(resp.body, b"0123456789"),
            other => panic!("expected complete, got {other:?}"),
        }
    }

    // ───────── parse_response:connection-close 分帧 + EOF 兜底 ─────────

    #[test]
    fn parse_until_eof_waits_then_eof_completes() {
        // 无 CL 无 TE:增量解析始终 Ok(None),EOF 兜底取全部剩余字节
        let raw = b"HTTP/1.1 200 OK\r\nX-A: b\r\n\r\nstreamed-body-until-close";
        match parse_response(raw) {
            Ok(None) => {}
            other => panic!("until-eof framing must wait for EOF, got {other:?}"),
        }
        let resp = match parse_response_eof(raw) {
            Ok(r) => r,
            Err(e) => panic!("eof parse should succeed: {e}"),
        };
        assert_eq!(resp.status, 200);
        assert_eq!(resp.body, b"streamed-body-until-close");
    }

    #[test]
    fn parse_response_eof_rejects_truncated() {
        // 头区未齐即 EOF
        assert!(matches!(
            parse_response_eof(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n"),
            Err(ClientError::Truncated)
        ));
        // CL 声明 10 字节只到 5 字节
        assert!(matches!(
            parse_response_eof(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nshort"),
            Err(ClientError::Truncated)
        ));
        // chunked 未见零块
        assert!(matches!(
            parse_response_eof(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhel"),
            Err(ClientError::Truncated)
        ));
        // 完全空缓冲
        assert!(matches!(parse_response_eof(b""), Err(ClientError::Truncated)));
    }

    // ───────── parse_response:非法输入 fail-closed ─────────

    #[test]
    fn parse_rejects_bad_status_line() {
        for raw in [
            &b"NOTHTTP 200 OK\r\n\r\n"[..],
            b"HTTP/2 200 OK\r\n\r\n",
            b"HTTP/1.1 20 OK\r\n\r\n",
            b"HTTP/1.1 abc OK\r\n\r\n",
            b"HTTP/1.1 \r\n\r\n",
        ] {
            match parse_response(raw) {
                Err(ClientError::InvalidStatusLine) => {}
                other => panic!(
                    "should reject {:?}, got {other:?}",
                    String::from_utf8_lossy(raw)
                ),
            }
        }
    }

    #[test]
    fn parse_rejects_header_without_colon() {
        let raw = b"HTTP/1.1 200 OK\r\nBadHeaderLine\r\n\r\n";
        assert!(matches!(
            parse_response(raw),
            Err(ClientError::InvalidHeader(_))
        ));
    }

    #[test]
    fn parse_rejects_invalid_header_name() {
        let raw = b"HTTP/1.1 200 OK\r\nBad Name: v\r\n\r\n";
        assert!(matches!(
            parse_response(raw),
            Err(ClientError::InvalidHeader(_))
        ));
    }

    #[test]
    fn parse_rejects_bare_lf_in_status_line() {
        // H-4: malicious upstream uses bare LF to inject headers
        let raw = b"HTTP/1.1 200 OK\nInjected: evil\r\nContent-Length: 0\r\n\r\n";
        assert!(matches!(
            parse_response(raw),
            Err(ClientError::InvalidHeader(_))
        ));
    }

    #[test]
    fn parse_rejects_bare_lf_in_header_line() {
        // H-4: header line uses bare LF (non-last line missing \r)
        let raw = b"HTTP/1.1 200 OK\r\nX-A: b\nInjected: evil\r\nContent-Length: 0\r\n\r\n";
        assert!(matches!(
            parse_response(raw),
            Err(ClientError::InvalidHeader(_))
        ));
    }

    #[test]
    fn parse_rejects_cl_and_te_coexist() {
        let raw = b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n";
        assert!(matches!(
            parse_response(raw),
            Err(ClientError::ProtocolInconsistency(_))
        ));
    }

    #[test]
    fn parse_rejects_conflicting_content_length() {
        let raw = b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nContent-Length: 4\r\n\r\nabcd";
        assert!(matches!(
            parse_response(raw),
            Err(ClientError::ProtocolInconsistency(_))
        ));
    }

    #[test]
    fn parse_rejects_invalid_chunk_size() {
        let raw = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nZZ\r\nx\r\n0\r\n\r\n";
        assert!(matches!(
            parse_response(raw),
            Err(ClientError::InvalidChunked(_))
        ));
    }

    #[test]
    fn parse_rejects_oversized_header_section() {
        let mut raw = Vec::new();
        raw.extend_from_slice(b"HTTP/1.1 200 OK\r\n");
        // 构造超过 64 KiB 的头区(无 \r\n\r\n 终止)
        while raw.len() <= MAX_HEADER_SECTION {
            raw.extend_from_slice(b"X-Pad: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n");
        }
        assert!(matches!(
            parse_response(&raw),
            Err(ClientError::HeaderTooLarge)
        ));
    }

    // ───────── M-4:客户端响应头防线(与服务端 parser 对称) ─────────

    #[test]
    fn parse_rejects_oversized_header_section_with_terminator() {
        // M-4:终止标记已找到、头区总字节仍超 64 KiB 时也必须拒绝
        // (修复前仅未找到 \r\n\r\n 时才检查上限,终止后可绕过)
        let mut raw = Vec::new();
        raw.extend_from_slice(b"HTTP/1.1 200 OK\r\n");
        while raw.len() <= MAX_HEADER_SECTION {
            raw.extend_from_slice(b"X-Pad: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n");
        }
        raw.extend_from_slice(b"\r\n"); // 补上终止标记
        raw.extend_from_slice(b"ok");
        assert!(matches!(
            parse_response(&raw),
            Err(ClientError::HeaderTooLarge)
        ));
        // EOF 兜底路径同样拒绝
        assert!(matches!(
            parse_response_eof(&raw),
            Err(ClientError::HeaderTooLarge)
        ));
    }

    #[test]
    fn parse_rejects_too_many_headers() {
        // M-4:条数上限(> MAX_HEADER_COUNT)
        let mut raw = Vec::new();
        raw.extend_from_slice(b"HTTP/1.1 200 OK\r\n");
        for i in 0..=MAX_HEADER_COUNT {
            raw.extend_from_slice(format!("X-H{i}: v\r\n").as_bytes());
        }
        raw.extend_from_slice(b"Content-Length: 0\r\n\r\n");
        assert!(matches!(
            parse_response(&raw),
            Err(ClientError::HeaderTooLarge)
        ));
    }

    #[test]
    fn parse_accepts_header_count_at_limit() {
        // 边界:恰好 MAX_HEADER_COUNT 条放行
        let mut raw = Vec::new();
        raw.extend_from_slice(b"HTTP/1.1 200 OK\r\n");
        for i in 1..MAX_HEADER_COUNT {
            raw.extend_from_slice(format!("X-H{i}: v\r\n").as_bytes());
        }
        raw.extend_from_slice(b"Content-Length: 0\r\n\r\n");
        assert!(
            matches!(parse_response(&raw), Ok(Some(_))),
            "恰在上限内的条数必须放行"
        );
    }

    #[test]
    fn parse_rejects_oversized_header_name() {
        // M-4:单名长度上限(> MAX_HEADER_NAME_LEN)
        let name = format!("X-{}", "A".repeat(MAX_HEADER_NAME_LEN));
        let raw = format!("HTTP/1.1 200 OK\r\n{name}: v\r\nContent-Length: 0\r\n\r\n");
        assert!(matches!(
            parse_response(raw.as_bytes()),
            Err(ClientError::HeaderTooLarge)
        ));
    }

    #[test]
    fn parse_rejects_oversized_header_value() {
        // M-4:单值长度上限(> MAX_HEADER_VALUE_LEN)
        let value = "v".repeat(MAX_HEADER_VALUE_LEN + 1);
        let raw = format!("HTTP/1.1 200 OK\r\nX-Pad: {value}\r\nContent-Length: 0\r\n\r\n");
        assert!(matches!(
            parse_response(raw.as_bytes()),
            Err(ClientError::HeaderTooLarge)
        ));
    }

    #[test]
    fn parse_header_ows_trimmed() {
        let raw = b"HTTP/1.1 200 OK\r\nX-Pad:   value  \r\nContent-Length: 1\r\n\r\nx";
        match parse_response(raw) {
            Ok(Some((resp, _))) => {
                assert_eq!(resp.headers[0], ("X-Pad".to_string(), "value".to_string()))
            }
            other => panic!("expected complete, got {other:?}"),
        }
    }

    // ───────── 错误类型 ─────────

    #[test]
    fn error_display_impl() {
        let e = ClientError::InvalidStatusLine;
        assert!(!format!("{e}").is_empty());
        let e = ClientError::Truncated;
        assert!(format!("{e}").contains("truncated"));
        // Error trait 可用
        let _: &dyn std::error::Error = &ClientError::HeaderTooLarge;
    }
}