shiguredo_http11 2026.1.0

HTTP/1.1 Library
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
//! Content-Type ヘッダーパース (RFC 9110 Section 8.3)
//!
//! ## 概要
//!
//! RFC 9110 に基づいた Content-Type ヘッダーのパースを提供します。
//!
//! ## 使い方
//!
//! ```rust
//! use shiguredo_http11::content_type::ContentType;
//!
//! // 基本的な Content-Type
//! let ct = ContentType::parse("text/html").unwrap();
//! assert_eq!(ct.media_type(), "text");
//! assert_eq!(ct.subtype(), "html");
//!
//! // パラメータ付き
//! let ct = ContentType::parse("text/html; charset=utf-8").unwrap();
//! assert_eq!(ct.charset(), Some("utf-8"));
//!
//! // multipart/form-data
//! let ct = ContentType::parse("multipart/form-data; boundary=----WebKitFormBoundary").unwrap();
//! assert_eq!(ct.boundary(), Some("----WebKitFormBoundary"));
//! ```

use core::fmt;

/// Content-Type パースエラー
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ContentTypeError {
    /// 空の Content-Type
    Empty,
    /// 不正なメディアタイプ形式
    InvalidMediaType,
    /// 不正なパラメータ形式
    InvalidParameter,
    /// 引用符が閉じていない
    UnterminatedQuote,
}

impl fmt::Display for ContentTypeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ContentTypeError::Empty => write!(f, "empty Content-Type"),
            ContentTypeError::InvalidMediaType => write!(f, "invalid media type"),
            ContentTypeError::InvalidParameter => write!(f, "invalid parameter"),
            ContentTypeError::UnterminatedQuote => write!(f, "unterminated quote"),
        }
    }
}

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

/// パース済み Content-Type
///
/// RFC 9110 Section 8.3 に基づいた Content-Type 構造:
/// ```text
/// Content-Type = media-type
/// media-type = type "/" subtype parameters
/// parameters = *( OWS ";" OWS [ parameter ] )
/// parameter = parameter-name "=" parameter-value
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContentType {
    /// メディアタイプ (例: "text")
    media_type: String,
    /// サブタイプ (例: "html")
    subtype: String,
    /// パラメータ (name, value) のペア
    parameters: Vec<(String, String)>,
}

impl ContentType {
    /// Content-Type 文字列をパース
    ///
    /// # 例
    ///
    /// ```rust
    /// use shiguredo_http11::content_type::ContentType;
    ///
    /// let ct = ContentType::parse("text/html; charset=utf-8").unwrap();
    /// assert_eq!(ct.media_type(), "text");
    /// assert_eq!(ct.subtype(), "html");
    /// assert_eq!(ct.charset(), Some("utf-8"));
    /// ```
    pub fn parse(input: &str) -> Result<Self, ContentTypeError> {
        let input = input.trim();
        if input.is_empty() {
            return Err(ContentTypeError::Empty);
        }

        // メディアタイプをパース (type/subtype)
        let (media_type_part, rest) = split_at_semicolon(input);
        let (media_type, subtype) = parse_media_type(media_type_part)?;

        // パラメータをパース
        let parameters = parse_parameters(rest)?;

        Ok(ContentType {
            media_type: media_type.to_ascii_lowercase(),
            subtype: subtype.to_ascii_lowercase(),
            parameters,
        })
    }

    /// 新しい ContentType を作成
    pub fn new(media_type: &str, subtype: &str) -> Self {
        ContentType {
            media_type: media_type.to_ascii_lowercase(),
            subtype: subtype.to_ascii_lowercase(),
            parameters: Vec::new(),
        }
    }

    /// パラメータを追加
    pub fn with_parameter(mut self, name: &str, value: &str) -> Self {
        self.parameters
            .push((name.to_ascii_lowercase(), value.to_string()));
        self
    }

    /// メディアタイプを取得 (例: "text")
    pub fn media_type(&self) -> &str {
        &self.media_type
    }

    /// サブタイプを取得 (例: "html")
    pub fn subtype(&self) -> &str {
        &self.subtype
    }

    /// 完全なメディアタイプを取得 (例: "text/html")
    pub fn mime_type(&self) -> String {
        format!("{}/{}", self.media_type, self.subtype)
    }

    /// パラメータを取得
    pub fn parameter(&self, name: &str) -> Option<&str> {
        let name_lower = name.to_ascii_lowercase();
        self.parameters
            .iter()
            .find(|(n, _)| n == &name_lower)
            .map(|(_, v)| v.as_str())
    }

    /// すべてのパラメータを取得
    pub fn parameters(&self) -> &[(String, String)] {
        &self.parameters
    }

    /// charset パラメータを取得
    pub fn charset(&self) -> Option<&str> {
        self.parameter("charset")
    }

    /// boundary パラメータを取得
    pub fn boundary(&self) -> Option<&str> {
        self.parameter("boundary")
    }

    /// text/* かどうか
    pub fn is_text(&self) -> bool {
        self.media_type == "text"
    }

    /// application/json かどうか
    pub fn is_json(&self) -> bool {
        self.media_type == "application" && self.subtype == "json"
    }

    /// multipart/* かどうか
    pub fn is_multipart(&self) -> bool {
        self.media_type == "multipart"
    }

    /// multipart/form-data かどうか
    pub fn is_form_data(&self) -> bool {
        self.media_type == "multipart" && self.subtype == "form-data"
    }

    /// application/x-www-form-urlencoded かどうか
    pub fn is_form_urlencoded(&self) -> bool {
        self.media_type == "application" && self.subtype == "x-www-form-urlencoded"
    }
}

impl fmt::Display for ContentType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", self.media_type, self.subtype)?;
        for (name, value) in &self.parameters {
            // 値に特殊文字が含まれる場合は引用符で囲む
            if needs_quoting(value) {
                write!(f, "; {}=\"{}\"", name, escape_quotes(value))?;
            } else {
                write!(f, "; {}={}", name, value)?;
            }
        }
        Ok(())
    }
}

/// セミコロンで分割 (最初のセミコロンのみ)
fn split_at_semicolon(input: &str) -> (&str, &str) {
    if let Some(pos) = input.find(';') {
        (input[..pos].trim(), input[pos + 1..].trim())
    } else {
        (input.trim(), "")
    }
}

/// メディアタイプをパース
fn parse_media_type(input: &str) -> Result<(&str, &str), ContentTypeError> {
    let input = input.trim();
    if input.is_empty() {
        return Err(ContentTypeError::InvalidMediaType);
    }

    let slash_pos = input.find('/').ok_or(ContentTypeError::InvalidMediaType)?;

    let media_type = input[..slash_pos].trim();
    let subtype = input[slash_pos + 1..].trim();

    if media_type.is_empty() || subtype.is_empty() {
        return Err(ContentTypeError::InvalidMediaType);
    }

    // トークン文字の検証
    if !is_valid_token(media_type) || !is_valid_token(subtype) {
        return Err(ContentTypeError::InvalidMediaType);
    }

    Ok((media_type, subtype))
}

/// パラメータをパース
fn parse_parameters(input: &str) -> Result<Vec<(String, String)>, ContentTypeError> {
    let mut parameters = Vec::new();
    let mut rest = input.trim();

    while !rest.is_empty() {
        // セミコロンをスキップ
        rest = rest.trim_start_matches(';').trim();
        if rest.is_empty() {
            break;
        }

        // name=value をパース
        let eq_pos = rest.find('=').ok_or(ContentTypeError::InvalidParameter)?;
        let name = rest[..eq_pos].trim();

        if name.is_empty() || !is_valid_token(name) {
            return Err(ContentTypeError::InvalidParameter);
        }

        rest = rest[eq_pos + 1..].trim();

        // 値をパース (引用符付きまたはトークン)
        let (value, remaining) = if let Some(after_quote) = rest.strip_prefix('"') {
            parse_quoted_string(after_quote)?
        } else {
            parse_token_value(rest)?
        };

        parameters.push((name.to_ascii_lowercase(), value));
        rest = remaining.trim_start_matches(';').trim();
    }

    Ok(parameters)
}

/// 引用符付き文字列をパース
fn parse_quoted_string(input: &str) -> Result<(String, &str), ContentTypeError> {
    let mut result = String::new();
    let mut escaped = false;

    for (i, c) in input.char_indices() {
        if escaped {
            result.push(c);
            escaped = false;
        } else if c == '\\' {
            escaped = true;
        } else if c == '"' {
            return Ok((result, &input[i + 1..]));
        } else {
            result.push(c);
        }
    }

    Err(ContentTypeError::UnterminatedQuote)
}

/// トークン値をパース
///
/// RFC 9110 Section 5.6.6: パラメータ値がトークンの場合、
/// トークン文字 (tchar) のみで構成されている必要がある
fn parse_token_value(input: &str) -> Result<(String, &str), ContentTypeError> {
    let end = input
        .find(|c: char| c == ';' || c.is_whitespace())
        .unwrap_or(input.len());
    let token = &input[..end];

    // トークン値の検証 (RFC 9110 Section 5.6.2)
    if !is_valid_token(token) {
        return Err(ContentTypeError::InvalidParameter);
    }

    Ok((token.to_string(), &input[end..]))
}

/// 有効なトークン文字かどうか
fn is_valid_token(s: &str) -> bool {
    !s.is_empty() && s.bytes().all(is_token_char)
}

/// RFC 9110 Section 5.6.2 のトークン文字 (tchar)
///
/// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
///         "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA
fn is_token_char(b: u8) -> bool {
    matches!(b,
        b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'*' | b'+' | b'-' | b'.' |
        b'0'..=b'9' | b'A'..=b'Z' | b'^' | b'_' | b'`' | b'a'..=b'z' | b'|' | b'~'
    )
}

/// 引用符で囲む必要があるかどうか
fn needs_quoting(s: &str) -> bool {
    s.bytes().any(|b| !is_token_char(b))
}

/// 引用符をエスケープ
fn escape_quotes(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

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

    #[test]
    fn test_parse_simple() {
        let ct = ContentType::parse("text/html").unwrap();
        assert_eq!(ct.media_type(), "text");
        assert_eq!(ct.subtype(), "html");
        assert_eq!(ct.mime_type(), "text/html");
        assert!(ct.parameters().is_empty());
    }

    #[test]
    fn test_parse_with_charset() {
        let ct = ContentType::parse("text/html; charset=utf-8").unwrap();
        assert_eq!(ct.media_type(), "text");
        assert_eq!(ct.subtype(), "html");
        assert_eq!(ct.charset(), Some("utf-8"));
    }

    #[test]
    fn test_parse_with_quoted_charset() {
        let ct = ContentType::parse("text/html; charset=\"utf-8\"").unwrap();
        assert_eq!(ct.charset(), Some("utf-8"));
    }

    #[test]
    fn test_parse_multipart() {
        let ct =
            ContentType::parse("multipart/form-data; boundary=----WebKitFormBoundary").unwrap();
        assert!(ct.is_form_data());
        assert_eq!(ct.boundary(), Some("----WebKitFormBoundary"));
    }

    #[test]
    fn test_parse_case_insensitive() {
        let ct = ContentType::parse("TEXT/HTML; CHARSET=UTF-8").unwrap();
        assert_eq!(ct.media_type(), "text");
        assert_eq!(ct.subtype(), "html");
        assert_eq!(ct.charset(), Some("UTF-8")); // 値は大文字小文字を保持
    }

    #[test]
    fn test_parse_multiple_parameters() {
        let ct = ContentType::parse("text/plain; charset=utf-8; boundary=something").unwrap();
        assert_eq!(ct.charset(), Some("utf-8"));
        assert_eq!(ct.boundary(), Some("something"));
    }

    #[test]
    fn test_parse_json() {
        let ct = ContentType::parse("application/json").unwrap();
        assert!(ct.is_json());
    }

    #[test]
    fn test_parse_form_urlencoded() {
        let ct = ContentType::parse("application/x-www-form-urlencoded").unwrap();
        assert!(ct.is_form_urlencoded());
    }

    #[test]
    fn test_parse_with_spaces() {
        let ct = ContentType::parse("  text/html  ;  charset = utf-8  ").unwrap();
        assert_eq!(ct.media_type(), "text");
        assert_eq!(ct.subtype(), "html");
    }

    #[test]
    fn test_parse_quoted_with_escape() {
        let ct = ContentType::parse("text/plain; name=\"hello\\\"world\"").unwrap();
        assert_eq!(ct.parameter("name"), Some("hello\"world"));
    }

    #[test]
    fn test_parse_empty() {
        assert!(ContentType::parse("").is_err());
    }

    #[test]
    fn test_parse_no_subtype() {
        assert!(ContentType::parse("text").is_err());
    }

    #[test]
    fn test_parse_empty_subtype() {
        assert!(ContentType::parse("text/").is_err());
    }

    #[test]
    fn test_display() {
        let ct = ContentType::new("text", "html").with_parameter("charset", "utf-8");
        assert_eq!(ct.to_string(), "text/html; charset=utf-8");
    }

    #[test]
    fn test_display_quoted() {
        let ct = ContentType::new("text", "plain").with_parameter("name", "hello world");
        assert_eq!(ct.to_string(), "text/plain; name=\"hello world\"");
    }

    #[test]
    fn test_is_text() {
        assert!(ContentType::parse("text/plain").unwrap().is_text());
        assert!(ContentType::parse("text/html").unwrap().is_text());
        assert!(!ContentType::parse("application/json").unwrap().is_text());
    }

    #[test]
    fn test_is_multipart() {
        assert!(
            ContentType::parse("multipart/form-data")
                .unwrap()
                .is_multipart()
        );
        assert!(
            ContentType::parse("multipart/mixed")
                .unwrap()
                .is_multipart()
        );
        assert!(!ContentType::parse("text/plain").unwrap().is_multipart());
    }

    // 修正 3: パラメータ値のトークン検証 (RFC 9110 Section 5.6.2)

    #[test]
    fn test_invalid_token_parameter_value() {
        // 不正なトークン値 (@ を含む) はエラー
        assert!(ContentType::parse("text/plain; charset=hello@world").is_err());
    }

    #[test]
    fn test_invalid_token_parameter_value_space() {
        // スペースを含むトークン値は境界で区切られる
        // "text/plain; charset=hello world" -> charset=hello として解釈され、
        // "world" が無効なパラメータになるためエラー
        assert!(ContentType::parse("text/plain; charset=hello world").is_err());
    }

    #[test]
    fn test_valid_token_parameter_value() {
        // 有効なトークン値は通る
        let ct = ContentType::parse("text/plain; charset=utf-8").unwrap();
        assert_eq!(ct.charset(), Some("utf-8"));
    }

    #[test]
    fn test_valid_token_parameter_value_complex() {
        // 有効なトークン文字で構成された値
        let ct = ContentType::parse("application/octet-stream; name=file-v1.0_test").unwrap();
        assert_eq!(ct.parameter("name"), Some("file-v1.0_test"));
    }

    #[test]
    fn test_quoted_special_chars() {
        // 引用符で囲めば特殊文字も OK
        let ct = ContentType::parse("text/plain; charset=\"hello@world\"").unwrap();
        assert_eq!(ct.charset(), Some("hello@world"));
    }

    #[test]
    fn test_empty_token_parameter_value() {
        // 空のトークン値はエラー
        assert!(ContentType::parse("text/plain; charset=").is_err());
    }
}