tii 0.0.6

A Low-Latency Web Server.
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
//! Provides functionality for handling HTTP requests.

use crate::{error_log, AcceptMimeCharset, HttpMethod, MimeCharset, MimeTypeWithCharset};
use crate::{trace_log, Cookie};
use crate::{Headers, HttpHeader, HttpHeaderName};

use crate::tii_error::{RequestHeadParsingError, TiiError, TiiResult, UserError};
use crate::util::{unwrap_ok, unwrap_some};
use crate::warn_log;
use crate::ConnectionStream;
use crate::{AcceptQualityMimeType, MimeType, QValue};
use std::fmt::{Display, Formatter};
use std::io::ErrorKind;
use std::vec;

/// Enum for http versions tii supports.
#[derive(Clone, Debug, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
#[non_exhaustive] //Not sure but I don't want to close the door on http 2 shut!
pub enum HttpVersion {
  /// Earliest http version. Has no concept of request bodies or headers. to trigger a request run `echo -ne 'GET /path/goes/here\r\n' | nc 127.0.0.1 8080`
  /// Responses are just the body, no headers, no nothing.
  Http09,
  /// First actually usable http version. Has headers, bodies, etc. but notably 1 connection per request and thus no transfer encoding
  Http10,
  /// Most recent 1.X version, has all features.
  Http11,
}

impl HttpVersion {
  /// returns the printable name of the http version.
  /// This is not always equivalent to how its appears in binary on the status line.
  pub fn as_str(&self) -> &'static str {
    match self {
      HttpVersion::Http09 => "HTTP/0.9",
      HttpVersion::Http10 => "HTTP/1.0",
      HttpVersion::Http11 => "HTTP/1.1",
    }
  }
  /// returns the network bytes in the status line for the http version.
  pub fn as_net_str(&self) -> &'static str {
    match self {
      HttpVersion::Http09 => "",
      HttpVersion::Http10 => "HTTP/1.0",
      HttpVersion::Http11 => "HTTP/1.1",
    }
  }
}

impl Display for HttpVersion {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    match self {
      HttpVersion::Http09 => f.write_str("HTTP/0.9"),
      HttpVersion::Http10 => f.write_str("HTTP/1.0"),
      HttpVersion::Http11 => f.write_str("HTTP/1.1"),
    }
  }
}

impl HttpVersion {
  /// Tries to parse the http version part of the status line to a http version.
  /// empty string is treated as http09 because http09 doesn't have a version in its status line.
  /// Returns input on error.
  pub fn try_from_net_str<T: AsRef<str>>(value: T) -> Result<Self, T> {
    match value.as_ref() {
      "HTTP/1.0" => Ok(HttpVersion::Http10),
      "HTTP/1.1" => Ok(HttpVersion::Http11),
      "" => Ok(HttpVersion::Http09),
      _ => Err(value),
    }
  }

  /// Tries to parse the http version from the printable name. This was most likely returned by a call to `HttpVersion::as_str`
  pub fn try_from_str<T: AsRef<str>>(value: T) -> Result<Self, T> {
    match value.as_ref() {
      "HTTP/1.0" => Ok(HttpVersion::Http10),
      "HTTP/1.1" => Ok(HttpVersion::Http11),
      "HTTP/0.9" => Ok(HttpVersion::Http09),
      _ => Err(value),
    }
  }
}

/// Represents a request to the server.
/// Contains parsed information about the request's data.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct RequestHead {
  /// The method used in making the request, e.g. "GET".
  method: HttpMethod,

  /// The HTTP version of the request.
  version: HttpVersion,

  /// The status line as is.
  /// For example "GET /index.html HTTP1.1"
  /// the crlf has been stripped already!
  status_line: String,

  /// The path to which the request was made.
  path: String,

  /// Vec of query parameters, key=value in order of appearance.
  query: Vec<(String, String)>,

  accept: Vec<AcceptQualityMimeType>,

  content_type: Option<MimeTypeWithCharset>,

  accept_charset: Vec<AcceptMimeCharset>,

  /// A list of headers included in the request.
  headers: Headers,
}

fn validate_raw_path(raw_path: &str) -> TiiResult<()> {
  if !raw_path.starts_with("/") {
    trace_log!("validate_raw_path Err {raw_path} because it does not start with /");
    return Err(TiiError::RequestHeadParsing(RequestHeadParsingError::InvalidPath(
      raw_path.to_string(),
    )));
  }

  //https://datatracker.ietf.org/doc/html/rfc3986#section-3.3
  for n in raw_path.bytes() {
    match n {
      b'/' => {}
      b'-' => {}
      b'.' => {}
      b'_' => {}
      b'~' => {}
      b'!' => {}
      b'$' => {}
      b'\'' => {}
      b'(' => {}
      b')' => {}
      b'*' => {}
      b'+' => {}
      b',' => {}
      b';' => {}
      b'=' => {}
      b':' => {}
      b'@' => {}
      b'%' => {}
      //Curl doesn't escape this and it probably won't cause harm?
      b'\\' => {}
      _ => {
        if !n.is_ascii_alphanumeric() {
          trace_log!("validate_raw_path Err {raw_path} due to byte {n}");
          return Err(TiiError::RequestHeadParsing(RequestHeadParsingError::InvalidPath(
            raw_path.to_string(),
          )));
        }
      }
    }
  }

  Ok(())
}

fn parse_status_line(start_line_buf: &Vec<u8>) -> TiiResult<&str> {
  for n in start_line_buf {
    // https://en.wikipedia.org/wiki/Percent-encoding#Types_of_URI_characters
    // plus space char which we check later...
    match *n {
      //RFC 3986 section 2.2 Reserved Characters
      // TODO some of these chars are not valid for the status line... the status line is not the URI!
      b'!' => {}
      b'$' => {}
      b'&' => {}
      b'\'' => {}
      b'(' => {}
      b')' => {}
      b'*' => {}
      b'+' => {}
      b',' => {}
      b'/' => {}
      b':' => {}
      b';' => {}
      b'=' => {}
      b'?' => {}
      b'@' => {}
      b'[' => {}
      b']' => {}
      // RFC 3986 section 2.3 Unreserved Characters
      b'-' => {}
      b'.' => {}
      b'_' => {}
      b'~' => {}
      //Other Stuff
      b'%' => {}
      b' ' => {}
      b'\\' => {} // curl doesnt escape this character
      b'\r' => {} // TODO we should check this later... this is only allowed as the second to last char...
      b'\n' => {} // TODO we should check this later... this is only allowed as the last char...
      other => {
        if other.is_ascii_alphanumeric() {
          continue;
        }
        return Err(RequestHeadParsingError::StatusLineContainsInvalidBytes.into());
      }
    }
  }

  if let Ok(res) = std::str::from_utf8(start_line_buf) {
    return Ok(res);
  }

  error_log!("parse_status_line: fatal error std::str::from_utf8 with buf failed utf8 validation even tho it succeeded ascii validation. buf={start_line_buf:?}");
  crate::util::unreachable()
}

fn parse_raw_query(raw_query: &str) -> TiiResult<Vec<(String, String)>> {
  if raw_query.is_empty() {
    return Ok(Vec::new());
  }

  let mut query = Vec::new();
  let mut current_key = Vec::new();
  let mut current_value = Vec::new();
  let mut matching_value = false;
  let mut matching_percent = 0;
  for n in raw_query.as_bytes().iter().copied() {
    if matching_percent != 0 {
      match n {
        b'0'..=b'9' | b'a'..=b'f' | b'A'..=b'F' => {
          matching_percent -= 1;
        }
        _ => {
          return Err(RequestHeadParsingError::InvalidQueryString(raw_query.to_string()).into());
        }
      }
    }

    match n {
      b'=' => {
        if matching_value {
          return Err(RequestHeadParsingError::InvalidQueryString(raw_query.to_string()).into());
        }
        matching_value = true;
        continue;
      }
      b'&' => {
        if !matching_value {
          return Err(RequestHeadParsingError::InvalidQueryString(raw_query.to_string()).into());
        }

        let key = urlencoding::decode(unwrap_ok(std::str::from_utf8(current_key.as_slice())))
          .map_err(|_| RequestHeadParsingError::InvalidQueryString(raw_query.to_string()))?
          .replace('+', " ");

        let value = urlencoding::decode(unwrap_ok(std::str::from_utf8(current_value.as_slice())))
          .map_err(|_| RequestHeadParsingError::InvalidQueryString(raw_query.to_string()))?
          .replace('+', " ");

        query.push((key, value));

        matching_value = false;
        current_key = Vec::new();
        current_value = Vec::new();
        continue;
      }
      b'%' => {
        matching_percent = 2;
      }
      b'!' | b'$' | b'\'' | b'(' | b')' | b'*' | b'+' | b',' | b'-' | b'.' | b'/' | b':' | b';'
      | b'@' | b'_' | b'~' => {}
      other => {
        if !other.is_ascii_alphanumeric() {
          return Err(RequestHeadParsingError::InvalidQueryString(raw_query.to_string()).into());
        }
      }
    }

    if matching_value {
      current_value.push(n);
    } else {
      current_key.push(n);
    }
  }

  if !matching_value || matching_percent != 0 {
    return Err(RequestHeadParsingError::InvalidQueryString(raw_query.to_string()).into());
  }

  let key = urlencoding::decode(unwrap_ok(std::str::from_utf8(current_key.as_slice())))
    .map_err(|_| RequestHeadParsingError::InvalidQueryString(raw_query.to_string()))?
    .replace('+', " ");

  let value = urlencoding::decode(unwrap_ok(std::str::from_utf8(current_value.as_slice())))
    .map_err(|_| RequestHeadParsingError::InvalidQueryString(raw_query.to_string()))?
    .replace('+', " ");

  query.push((key, value));

  Ok(query)
}

impl RequestHead {
  /// Create a new RequestHead programmatically.
  /// This is useful for unit testing endpoints.
  pub(crate) fn new(
    method: HttpMethod,
    version: HttpVersion,
    path: impl ToString,
    query: Vec<(impl ToString, impl ToString)>,
    headers: Vec<HttpHeader>,
  ) -> TiiResult<Self> {
    let mut path = path.to_string();
    if validate_raw_path(path.as_str()).is_err() {
      //Path is not yet url encoded, encode it...
      let mut path_encoder = String::new();
      for (idx, part) in path.split("/").enumerate() {
        if idx == 0 {
          if !part.is_empty() {
            //Path does not start with /
            return Err(TiiError::RequestHeadParsing(RequestHeadParsingError::InvalidPath(path)));
          }
          continue;
        }
        path_encoder.push('/');
        path_encoder.push_str(urlencoding::encode(part).as_ref());
      }
      validate_raw_path(&path_encoder)?;
      path = path_encoder;
    }

    let query: Vec<(String, String)> = query
      .into_iter()
      .map(|(k, v)| (k.to_string(), v.to_string()))
      .filter(|(k, v)| !k.is_empty() || !v.is_empty())
      .collect();
    let mut query_string = String::new();
    for (idx, (key, value)) in query.iter().enumerate() {
      if idx == 0 {
        query_string.push('?');
      } else {
        query_string.push('&');
      }
      query_string.push_str(urlencoding::encode(key).as_ref());
      if !value.is_empty() {
        query_string.push('=');
        query_string.push_str(urlencoding::encode(value).as_ref());
      }
    }

    if version == HttpVersion::Http09 {
      if method != HttpMethod::Get {
        return Err(TiiError::RequestHeadParsing(
          RequestHeadParsingError::MethodNotSupportedByHttpVersion(version, method),
        ));
      }

      if !headers.is_empty() {
        return Err(TiiError::UserError(UserError::HeaderNotSupportedByHttpVersion(version)));
      }

      let status_line = format!("GET {}{}", path.as_str(), query_string.as_str());

      return Ok(Self {
        method: HttpMethod::Get,
        version: HttpVersion::Http09,
        status_line,
        path,
        query,
        accept: vec![AcceptQualityMimeType::from_mime(
          MimeType::TextHtml,
          QValue::default(),
          MimeCharset::Unspecified,
        )],
        accept_charset: vec![AcceptMimeCharset::new(MimeCharset::UsAscii, QValue::default())],
        content_type: None,
        headers: Default::default(),
      });
    }

    let status_line = format!("{} {}{} {}", method, path.as_str(), query_string.as_str(), version);
    let headers = Headers::from(headers);
    let accept_hdr = headers.get(HttpHeaderName::Accept).unwrap_or("*/*");
    let Some(accept) = AcceptQualityMimeType::parse(accept_hdr) else {
      return Err(TiiError::UserError(UserError::IllegalAcceptHeaderValueSet(
        accept_hdr.to_string(),
      )));
    };

    let accept_charset_hdr = headers.get(HttpHeaderName::AcceptCharset).unwrap_or("");
    let Some(accept_charset) = AcceptMimeCharset::parse(accept_charset_hdr) else {
      return Err(TiiError::UserError(UserError::IllegalAcceptHeaderValueSet(
        accept_hdr.to_string(),
      )));
    };

    let content_type = if let Some(ctype_raw) = headers.get(HttpHeaderName::ContentType) {
      let Some(ctype) = MimeTypeWithCharset::parse_from_content_type_header(ctype_raw) else {
        return Err(TiiError::UserError(UserError::IllegalContentTypeHeaderValueSet(
          ctype_raw.to_string(),
        )));
      };
      Some(ctype)
    } else {
      None
    };

    Ok(Self {
      method,
      version,
      status_line,
      path,
      query,
      accept,
      accept_charset,
      content_type,
      headers,
    })
  }

  /// Attempts to read and parse one HTTP request from the given reader.
  pub fn read(
    id: u128,
    stream: &dyn ConnectionStream,
    max_head_buffer_size: usize,
  ) -> TiiResult<Self> {
    let mut start_line_buf: Vec<u8> = Vec::with_capacity(256);
    let count = stream.read_until(0xA, max_head_buffer_size, &mut start_line_buf)?;

    if count == 0 {
      //Unreachable unless stream implementation is shit. TC 42 tests this case.
      error_log!("tii: RequestHead::new call to ConnectionStream::read_until returned 0 bytes, but this RequestHead::new is only called when the stream should have at least one byte buffered. Is the ConnectionStream impl buggy? Will return io::Error UnexpectedEof.");
      return Err(TiiError::from_io_kind(ErrorKind::UnexpectedEof));
    }

    if count == max_head_buffer_size {
      error_log!(
        "tii: Request {} Client sent more than {} bytes for status line",
        id,
        max_head_buffer_size
      );
      return Err(RequestHeadParsingError::StatusLineTooLong(start_line_buf).into());
    }

    trace_log!(
      "tii: Request {} received {} bytes of data until 0xA (\\n) byte for status line",
      id,
      count
    );

    let start_line_string = parse_status_line(&start_line_buf)?;

    let status_line =
      start_line_string.strip_suffix("\r\n").ok_or(RequestHeadParsingError::StatusLineNoCRLF)?;

    trace_log!("tii: Request {} status line: {}", id, status_line);

    let mut start_line = status_line.split(' ');

    let method = HttpMethod::from(unwrap_some(start_line.next()));

    let mut uri_iter =
      start_line.next().ok_or(RequestHeadParsingError::StatusLineNoWhitespace)?.splitn(2, '?');

    let version = start_line
      .next()
      .map(HttpVersion::try_from_net_str)
      .unwrap_or(Ok(HttpVersion::Http09)) //Http 0.9 has no suffix
      .map_err(|version| RequestHeadParsingError::HttpVersionNotSupported(version.to_string()))?;

    if start_line.next().is_some() {
      return Err(TiiError::from(RequestHeadParsingError::StatusLineTooManyWhitespaces));
    }

    let raw_path = unwrap_some(uri_iter.next());
    validate_raw_path(raw_path)?;

    let path = urlencoding::decode(raw_path)
      .map_err(|_| {
        TiiError::from(RequestHeadParsingError::InvalidPathUrlEncoding(raw_path.to_string()))
      })?
      .to_string();

    let raw_query = uri_iter.next().unwrap_or("");
    let query = parse_raw_query(raw_query)?;

    let mut headers = Headers::new();

    if version == HttpVersion::Http09 {
      if method != HttpMethod::Get {
        return Err(TiiError::from(RequestHeadParsingError::MethodNotSupportedByHttpVersion(
          version, method,
        )));
      }

      return Ok(Self {
        method,
        path,
        query,
        version,
        headers,
        content_type: None,
        accept: vec![AcceptQualityMimeType::from_mime(
          MimeType::TextHtml,
          QValue::default(),
          MimeCharset::Unspecified,
        )], // Http 0.9 only accepts html.
        accept_charset: vec![AcceptMimeCharset::new(MimeCharset::UsAscii, QValue::default())],
        status_line: status_line.to_string(),
      });
    }

    loop {
      let mut line_buf: Vec<u8> = Vec::with_capacity(256);
      let count = stream.read_until(0xA, max_head_buffer_size, &mut line_buf)?;

      if count == max_head_buffer_size {
        error_log!(
          "tii: Request {id} Client sent more than {max_head_buffer_size} bytes for header line"
        );
        return Err(RequestHeadParsingError::HeaderLineTooLong(line_buf).into());
      }

      trace_log!(
        "tii: Request {id} received {count} bytes of data until 0xA (\\n) byte for header line"
      );

      let line = std::str::from_utf8(&line_buf)
        .map_err(|_| RequestHeadParsingError::HeaderLineIsNotUsAscii)?;

      if line == "\r\n" {
        trace_log!("tii: Request {id} Client sent CRLF, end of header section");
        break;
      }

      let line = line.strip_suffix("\r\n").ok_or(RequestHeadParsingError::HeaderLineNoCRLF)?;
      #[cfg(feature = "log")]
      {
        if log::max_level() == log::Level::Trace {
          if line.starts_with("Authorization:") {
            trace_log!("tii: Request {id} next header line: Authorization: ***MASKED***");
          } else {
            trace_log!("tii: Request {id} next header line: {line}");
          }
        }
      }

      let mut line_parts = line.splitn(2, ": ");
      let name = unwrap_some(line_parts.next()).trim();

      if name.is_empty() {
        return Err(TiiError::from(RequestHeadParsingError::HeaderNameEmpty));
      }

      let value = line_parts.next().ok_or(RequestHeadParsingError::HeaderValueMissing)?.trim();

      if value.is_empty() {
        return Err(TiiError::from(RequestHeadParsingError::HeaderValueEmpty));
      }

      headers.add(HttpHeaderName::from(name), value);
    }

    let accept_hdr = headers.get(HttpHeaderName::Accept).unwrap_or("*/*"); //TODO This is probably also wrong.
    let accept = AcceptQualityMimeType::parse(accept_hdr);
    if accept.is_none() {
      // TODO should this be a hard error?
      warn_log!(
        "tii: Request to '{}' has invalid Accept header '{}' will assume 'Accept: */*'",
        path.as_str(),
        accept_hdr
      );
    }

    let accept = accept.unwrap_or_else(|| vec![AcceptQualityMimeType::default()]);

    let content_type = headers.get(HttpHeaderName::ContentType).map(|ctype_raw| {
      let ctype = MimeTypeWithCharset::parse_from_content_type_header(ctype_raw);
      if ctype.is_none() {
        warn_log!(
         "tii: Request to '{}' has invalid Content-Type header '{}' will assume 'Content-Type: application/octet-stream'",
          path.as_str(),
          ctype_raw
        );
      }

      ctype.unwrap_or(MimeTypeWithCharset::APPLICATION_OCTET_STREAM)
    });

    let accept_charset_hdr = headers.get(HttpHeaderName::AcceptCharset).unwrap_or("");
    let accept_charset = AcceptMimeCharset::parse(accept_charset_hdr);
    if accept_charset.is_none() {
      // TODO should this be a hard error?
      warn_log!(
        "tii: Request to '{}' has invalid Accept-Charset header '{}' will assume the header is not set",
        path.as_str(),
        accept_charset_hdr
      );
    }

    let accept_charset = accept_charset.unwrap_or_default();

    Ok(Self {
      method,
      path,
      query,
      version,
      headers,
      accept,
      accept_charset,
      content_type,
      status_line: status_line.to_string(),
    })
  }

  /// get the http version this request was made in by the client.
  pub fn get_version(&self) -> HttpVersion {
    self.version
  }

  /// Returns the raw status line.
  pub fn get_raw_status_line(&self) -> &str {
    self.status_line.as_str()
  }

  /// Returns the path the request will be routed to
  /// This should not contain any url encoding.
  pub fn get_path(&self) -> &str {
    self.path.as_str()
  }

  /// Sets the path the request will be routed to.
  /// This should not contain any url encoding.
  pub fn set_path(&mut self, path: impl ToString) {
    self.path = path.to_string();
  }

  /// Gets the query parameters.
  pub fn get_query(&self) -> &[(String, String)] {
    self.query.as_slice()
  }

  /// Gets the mutable Vec that contains the query parameters.
  pub fn query_mut(&mut self) -> &mut Vec<(String, String)> {
    &mut self.query
  }

  /// Set the query parameters
  pub fn set_query(&mut self, query: Vec<(String, String)>) {
    self.query = query;
  }

  /// Add a query parameter. Existing query parameters with the same key are not touched.
  pub fn add_query_param(&mut self, key: impl ToString, value: impl ToString) {
    self.query.push((key.to_string(), value.to_string()));
  }

  /// Removes all query parameters that match the given key.
  /// Returns the removed values.
  pub fn remove_query_params(&mut self, key: impl AsRef<str>) -> Vec<String> {
    let key = key.as_ref();

    let mut result = Vec::new();

    for n in (0..self.query.len()).rev() {
      let (k, _) = unwrap_some(self.query.get(n));
      if k == key {
        let (_, v) = self.query.remove(n);
        result.push(v);
      }
    }

    result.reverse();
    result
  }

  /// Removes all instances of the query parameter with the given key if there are any and adds a new query
  /// parameter with the given key and value to the end of the query parameters.
  ///
  /// If the key already has the value then its position is retained.
  /// All other values for the key are still removed.
  ///
  /// Returns the removed values.
  pub fn set_query_param(&mut self, key: impl ToString, value: impl ToString) -> Vec<String> {
    let key = key.to_string();
    let value = value.to_string();

    let mut result = Vec::new();
    let mut added = false;
    for n in (0..self.query.len()).rev() {
      let (k, v) = unwrap_some(self.query.get(n));
      if k == key.as_str() {
        if !added && v == value.as_str() {
          added = true;
          continue;
        }
        let (_, v) = self.query.remove(n);
        result.push(v);
      }
    }

    if !added {
      self.query.push((key, value));
    }

    result.reverse();
    result
  }

  /// Gets the first query parameter with the given key.
  pub fn get_query_param(&self, key: impl AsRef<str>) -> Option<&str> {
    let key = key.as_ref();
    for (k, v) in &self.query {
      if k == key {
        return Some(v.as_str());
      }
    }

    None
  }

  /// Gets all query params in order of appearance that contain the given key.
  /// Returns empty vec if the key doesn't exist.
  pub fn get_query_params(&self, key: impl AsRef<str>) -> Vec<&str> {
    let mut result = Vec::new();
    let key = key.as_ref();
    for (k, v) in &self.query {
      if k == key {
        result.push(v.as_str());
      }
    }

    result
  }

  /// gets the method of the request.
  pub fn get_method(&self) -> &HttpMethod {
    &self.method
  }

  /// Changes the method of the request
  pub fn set_method(&mut self, method: HttpMethod) {
    self.method = method;
  }

  /// Get the cookies from the request.
  pub fn get_cookies(&self) -> Vec<Cookie> {
    self
      .headers
      .get(HttpHeaderName::Cookie)
      .map(|cookies| {
        cookies
          .split(';')
          .filter_map(|cookie| {
            let (k, v) = cookie.split_once('=')?;
            Some(Cookie::new(k.trim(), v.trim()))
          })
          .collect()
      })
      .unwrap_or_default()
  }

  /// Attempts to get a specific cookie from the request.
  pub fn get_cookie(&self, name: impl AsRef<str>) -> Option<Cookie> {
    self.get_cookies().into_iter().find(|cookie| cookie.name == name.as_ref())
  }

  /// Manipulates the accept header values.
  /// This also overwrites the actual accept header!
  pub fn set_accept(&mut self, types: Vec<AcceptQualityMimeType>) {
    let hdr_value = AcceptQualityMimeType::elements_to_header_value(&types);
    self.headers.set(HttpHeaderName::Accept, hdr_value);
    self.accept = types;
  }

  /// Returns the content type of the body if any.
  /// This is usually equivalent to parsing the raw get_header() value of Content-Type.
  /// The only case where this is different is if the request as received from the network had an invalid Content-Type value then
  /// this value is ApplicationOctetStream even tho the raw header value is different.
  /// This returns none if the Content-Type header was not present at all.
  /// (For example ordinary GET requests do not have this header)
  pub fn get_content_type(&self) -> Option<&MimeTypeWithCharset> {
    self.content_type.as_ref()
  }

  /// sets the content type header to given MimeType.
  /// This will affect both the header and the return value of get_content_type.
  pub fn set_content_type(&mut self, content_type: impl Into<MimeTypeWithCharset>) {
    let content_type = content_type.into();
    self.headers.set(HttpHeaderName::ContentType, content_type.to_string());
    self.content_type = Some(content_type);
  }

  /// Removes the content type header. get_content_type will return None after this call.
  pub fn remove_content_type(&mut self) -> Option<MimeTypeWithCharset> {
    self.headers.remove(HttpHeaderName::ContentType);
    self.content_type.take()
  }

  /// Returns the acceptable mime types
  pub fn get_accept(&self) -> &[AcceptQualityMimeType] {
    self.accept.as_slice()
  }

  pub fn get_accept_charset(&self) -> &[AcceptMimeCharset] {
    self.accept_charset.as_slice()
  }

  /// Returns an iterator over all headers.
  pub fn iter_headers(&self) -> impl Iterator<Item = &HttpHeader> {
    self.headers.iter()
  }

  /// Returns the first header or None
  pub fn get_header(&self, name: impl AsRef<str>) -> Option<&str> {
    self.headers.get(name)
  }

  /// Returns true if the client indicates that it accepts gzip.
  pub fn accepts_gzip(&self) -> bool {
    let Some(accept_enc) = self.get_header(HttpHeaderName::AcceptEncoding) else {
      return false;
    };

    //we have to match "gzip" " gzip," " gzip" "gzip,"
    //as well as the same variant with x-gzip
    //this is not perfect, we should later improve this by parsing the header to an Enum.
    accept_enc.contains("gzip")
  }

  /// Returns the all header values of empty Vec.
  pub fn get_headers(&self, name: impl AsRef<str>) -> Vec<&str> {
    self.headers.get_all(name)
  }

  /// Removes all instances of a particular header.
  pub fn remove_headers(&mut self, hdr: impl AsRef<str>) -> TiiResult<()> {
    match &hdr.as_ref().into() {
      HttpHeaderName::Accept => {
        self.accept = vec![AcceptQualityMimeType::default()];
        self.headers.set(hdr, "*/*");
        Ok(())
      }
      HttpHeaderName::ContentType => {
        self.headers.remove(hdr);
        self.content_type = None;
        Ok(())
      }
      HttpHeaderName::TransferEncoding => {
        UserError::ImmutableRequestHeaderRemoved(HttpHeaderName::TransferEncoding).into()
      }
      HttpHeaderName::ContentLength => {
        UserError::ImmutableRequestHeaderRemoved(HttpHeaderName::ContentLength).into()
      }
      _ => {
        self.headers.remove(hdr);
        Ok(())
      }
    }
  }

  /// Sets the header value.
  /// Some header values cannot be modified through this fn and attempting to change them are a noop.
  pub fn set_header(&mut self, hdr: impl AsRef<str>, value: impl ToString) -> TiiResult<()> {
    let hdr_value = value.to_string();
    match &hdr.as_ref().into() {
      HttpHeaderName::Accept => {
        if let Some(accept) = AcceptQualityMimeType::parse(&hdr_value) {
          self.accept = accept;
          self.headers.set(hdr, value);
          return Ok(());
        }

        UserError::IllegalAcceptHeaderValueSet(hdr_value.to_string()).into()
      }
      HttpHeaderName::ContentType => {
        let mime = MimeTypeWithCharset::parse_from_content_type_header(&hdr_value)
          .ok_or_else(|| UserError::IllegalContentTypeHeaderValueSet(hdr_value.to_string()))?;
        self.headers.set(HttpHeaderName::ContentType, hdr_value);
        self.content_type = Some(mime);
        Ok(())
      }
      HttpHeaderName::TransferEncoding => UserError::ImmutableRequestHeaderModified(
        HttpHeaderName::TransferEncoding,
        hdr_value.to_string(),
      )
      .into(),
      HttpHeaderName::ContentLength => UserError::ImmutableRequestHeaderModified(
        HttpHeaderName::ContentLength,
        hdr_value.to_string(),
      )
      .into(),
      _ => {
        self.headers.set(hdr, value);
        Ok(())
      }
    }
  }

  /// Adds a new header value to the headers. This can be the first value with the given key or an additional value.
  pub fn add_header(&mut self, hdr: impl AsRef<str>, value: impl ToString) -> TiiResult<()> {
    let hdr_value = value.to_string();
    match &hdr.as_ref().into() {
      HttpHeaderName::Accept => {
        if let Some(accept) = AcceptQualityMimeType::parse(&hdr_value) {
          if let Some(old_value) = self.headers.try_set(hdr, &hdr_value) {
            return UserError::MultipleAcceptHeaderValuesSet(old_value.to_string(), hdr_value)
              .into();
          }
          self.accept = accept;
          return Ok(());
        }
        UserError::IllegalAcceptHeaderValueSet(hdr_value.to_string()).into()
      }
      HttpHeaderName::ContentType => {
        let mime = MimeTypeWithCharset::parse_from_content_type_header(&hdr_value)
          .ok_or_else(|| UserError::IllegalContentTypeHeaderValueSet(hdr_value.to_string()))?;
        if let Some(old_value) = self.headers.try_set(hdr, &hdr_value) {
          return UserError::MultipleContentTypeHeaderValuesSet(old_value.to_string(), hdr_value)
            .into();
        }
        self.content_type = Some(mime);
        Ok(())
      }
      HttpHeaderName::TransferEncoding => UserError::ImmutableRequestHeaderModified(
        HttpHeaderName::TransferEncoding,
        hdr_value.to_string(),
      )
      .into(),
      HttpHeaderName::ContentLength => UserError::ImmutableRequestHeaderModified(
        HttpHeaderName::ContentLength,
        hdr_value.to_string(),
      )
      .into(),
      _ => {
        self.headers.add(hdr, value);
        Ok(())
      }
    }
  }
}