tiny_http_fork 0.12.11

Low level HTTP server library FORK
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


use std::fmt;
use std::io::Error as IoError;
use std::io::Result as IoResult;
use std::io::{BufReader, BufWriter, ErrorKind, Read};

use std::net::SocketAddr;
use std::str::FromStr;

#[cfg(not(feature = "allow_utf8_headers"))]
use ascii::AsciiString;

use crate::Header;
use crate::common::HeaderError;
use crate::common::{HTTPVersion, Method};
use crate::log;
use crate::util::RefinedTcpStream;
use crate::util::{SequentialReader, SequentialReaderBuilder, SequentialWriterBuilder};
use crate::Request;

/// A ClientConnection is an object that will store a socket to a client
/// and return Request objects.
pub struct ClientConnection {
    // address of the client
    remote_addr: IoResult<Option<SocketAddr>>,

    // sequence of Readers to the stream, so that the data is not read in
    //  the wrong order
    source: SequentialReaderBuilder<BufReader<RefinedTcpStream>>,

    // sequence of Writers to the stream, to avoid writing response #2 before
    //  response #1
    sink: SequentialWriterBuilder<BufWriter<RefinedTcpStream>>,

    // Reader to read the next header from
    next_header_source: SequentialReader<BufReader<RefinedTcpStream>>,

    // set to true if we know that the previous request is the last one
    no_more_requests: bool,

    // true if the connection goes through SSL
    secure: bool,
}

/// Error that can happen when reading a request.
#[derive(Debug)]
pub enum ReadError 
{
    /// Issued when parsing headers or any other things fails
    ProtocolViolation(String),
    WrongRequestLine,
    WrongHeader(HTTPVersion),
    /// the client sent an unrecognized `Expect` header
    ExpectationFailed(HTTPVersion),
    ReadIoError(IoError),
}

impl fmt::Display for ReadError
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match self
        {
            Self::ProtocolViolation(errmsg) => 
                write!(f, "[ProtocolViolation] {}", errmsg),
            Self::WrongRequestLine => 
                write!(f, "[WrongRequestLine]"),
            Self::WrongHeader(_httpversion) => 
                write!(f, "[WrongHeader]"),
            Self::ExpectationFailed(_httpversion) => 
                write!(f, "[ExpectationFailed]"),
            Self::ReadIoError(error) => 
                write!(f, "[ReadIoError] {}", error),
        }
    }
}

impl ClientConnection {
    /// Creates a new `ClientConnection` that takes ownership of the `TcpStream`.
    pub fn new(
        write_socket: RefinedTcpStream,
        mut read_socket: RefinedTcpStream,
    ) -> ClientConnection 
    {
        let remote_addr = read_socket.peer_addr();
        let secure = read_socket.secure();

        let mut source = SequentialReaderBuilder::new(BufReader::with_capacity(1024, read_socket));
        let first_header = source.next().unwrap();

        ClientConnection 
        {
            source,
            sink: SequentialWriterBuilder::new(BufWriter::with_capacity(1024, write_socket)),
            remote_addr,
            next_header_source: first_header,
            no_more_requests: false,
            secure,
        }
    }

    /// true if the connection is HTTPS
    pub fn secure(&self) -> bool {
        self.secure
    }

    /// Reads the next line from self.next_header_source.
    ///
    /// Reads until `CRLF` is reached. The next read will start
    ///  at the first byte of the new line.
    /// 
    /// CVE-2026-66753 fixed
    #[cfg(not(feature = "allow_utf8_headers"))]
    fn read_next_line(&mut self) -> Result<AsciiString, ReadError> 
    {
        let mut buf = Vec::new();
        let mut rn = [0_u8; 2];
        let mut rn_p = 0;
        const RNC: u16 = u16::from_le_bytes([b'\r', b'\n']);

        
        loop 
        {
            let cur_byte = 
                self.next_header_source.by_ref().bytes().next()
                    .ok_or_else(||
                       ReadError::ReadIoError(IoError::new(ErrorKind::ConnectionAborted, "Unexpected EOF"))
                    )?
                    .map_err(|e|
                        ReadError::ReadIoError(e)
                    )?;

            match rn_p
            {
                0 => 
                {
                    if cur_byte != b'\r' && cur_byte != b'\n'
                    { // most times true
                        buf.push(cur_byte);
                    }
                    else
                    {
                        rn[rn_p] = cur_byte;
                        rn_p += 1;
                    }
                },
                _ =>
                {
                    rn[rn_p] = cur_byte;

                    if u16::from_le_bytes(rn) != RNC
                    {
                        // error
                        return Err(ReadError::WrongRequestLine);
                    }

                    return
                        AsciiString::from_ascii(buf)
                            .map_err(|_| ReadError::ProtocolViolation(format!("Header is not in ASCII")));
                }
            }
        }
    }

    /// Reads the next line from self.next_header_source.
    ///
    /// Reads until `CRLF` is reached. The next read will start
    ///  at the first byte of the new line.
    /// 
    /// CVE-2026-66753 fixed
    #[cfg(feature = "allow_utf8_headers")]
    fn read_next_line(&mut self) -> Result<String, ReadError> 
    {
        let mut buf = Vec::new();
        let mut rn = [0_u8; 2];
        let mut rn_p = 0;
        const RNC: u16 = u16::from_le_bytes([b'\r', b'\n']);

        
        loop 
        {
            let cur_byte = 
                self.next_header_source.by_ref().bytes().next()
                    .ok_or_else(||
                       ReadError::ReadIoError(IoError::new(ErrorKind::ConnectionAborted, "Unexpected EOF"))
                    )?
                    .map_err(|e|
                        ReadError::ReadIoError(e)
                    )?;

            match rn_p
            {
                0 => 
                {
                    if cur_byte != b'\r' && cur_byte != b'\n'
                    { // most times true
                        buf.push(cur_byte);
                    }
                    else
                    {
                        rn[rn_p] = cur_byte;
                        rn_p += 1;
                    }
                },
                _ =>
                {
                    rn[rn_p] = cur_byte;

                    if u16::from_le_bytes(rn) != RNC
                    {
                        // error
                        return Err(ReadError::WrongRequestLine);
                    }

                    return
                        String::from_utf8(buf)
                            .map_err(|_| ReadError::ReadIoError(IoError::new(ErrorKind::InvalidInput, "Header is not in ASCII")));
                }
            }
        }
    }

    /// Reads a request from the stream.
    /// Blocks until the header has been read.
    fn read(&mut self) -> Result<Request, ReadError> 
    {
        let (method, path, version, headers) = 
            {
                // reading the request line
                let (method, path, version) = {
                    let line = self.read_next_line()?;

                    parse_request_line(
                        line.as_str().trim(), // TODO: remove this conversion
                    )?
                };

                // getting all headers
                let headers = 
                    {
                        let mut headers = Vec::new();
                        loop 
                        {
                            let line = self.read_next_line()?;

                            if line.is_empty() == true
                            {
                                break;
                            }

                            let header_res: Result<Header, HeaderError> = FromStr::from_str(line.as_str().trim());

                            match header_res
                            {
                                Ok(hd) => 
                                {
                                    headers.push(hd);
                                },
                                Err(e) => 
                                {
                                    log::error!("{}", e);

                                    return Err(ReadError::ProtocolViolation(e.to_string()));
                                }
                            }
                        }

                        headers
                    };

                (method, path, version, headers)
            };

        // building the writer for the request
        let writer = self.sink.next().unwrap();

        // follow-up for next potential request
        let mut data_source = self.source.next().unwrap();
        std::mem::swap(&mut self.next_header_source, &mut data_source);

        // fix https://github.com/tiny-http/tiny-http/pull/285
        let remote_addr = 
            self.remote_addr.as_ref()
                .map_err(|e| ReadError::ReadIoError(IoError::from(e.kind())))
                .map(|addr| *addr)?;

        // building the next reader
        let request = 
            crate::request::new_request(
                self.secure,
                method,
                path,
                version.clone(),
                headers,
                remote_addr,
                data_source,
                writer,
            )
            .map_err(|e| 
                {
                    use crate::request;
                    match e 
                    {
                        request::RequestCreationError::ProtocolViolation => 
                            ReadError::WrongRequestLine, // 400
                        request::RequestCreationError::CreationIoError(e) => 
                            ReadError::ReadIoError(e),
                        request::RequestCreationError::ExpectationFailed => 
                        {
                            ReadError::ExpectationFailed(version)
                        }
                    }
                }
            )?;

        // return the request
        Ok(request)
    }
}

impl Iterator for ClientConnection 
{
    type Item = Result<Request, ReadError>;

    /// Blocks until the next Request is available.
    /// Returns None when no new Requests will come from the client.
    fn next(&mut self) -> Option<Self::Item> 
    {
        use crate::{Response, StatusCode};

        // the client sent a "connection: close" header in this previous request
        //  or is using HTTP 1.0, meaning that no new request will come
        if self.no_more_requests == true 
        {
            return None;
        }


        loop 
        {
            let rq_res = self.read();

            if let Err(e) = rq_res
            {
                match &e
                {
                    ReadError::ProtocolViolation(_err_descr) =>
                    {
                        let writer = self.sink.next().unwrap();
                        let response = Response::new_empty(StatusCode(400));
                        response.raw_print(writer, HTTPVersion(1, 1), &[], false, None).ok();
                    },

                    ReadError::WrongRequestLine => 
                    {
                        let writer = self.sink.next().unwrap();
                        let response = Response::new_empty(StatusCode(400));
                        response
                            .raw_print(writer, HTTPVersion(1, 1), &[], false, None)
                            .ok();
                    },

                    ReadError::WrongHeader(ver) => 
                    {
                        let writer = self.sink.next().unwrap();
                        let response = Response::new_empty(StatusCode(400));
                        response.raw_print(writer, ver.clone(), &[], false, None).ok();
                    },

                    ReadError::ReadIoError(err) if err.kind() == ErrorKind::TimedOut => {
                        // request timeout
                        let writer = self.sink.next().unwrap();
                        let response = Response::new_empty(StatusCode(408));
                        response
                            .raw_print(writer, HTTPVersion(1, 1), &[], false, None)
                            .ok();
                    },

                    ReadError::ExpectationFailed(ver) => 
                    {
                        let writer = self.sink.next().unwrap();
                        let response = Response::new_empty(StatusCode(417));
                        response.raw_print(writer, ver.clone(), &[], true, None).ok();
                    },

                    e => 
                    {
                        let writer = self.sink.next().unwrap();
                        let response = Response::new_empty(StatusCode(400));
                        response.raw_print(writer, HTTPVersion(1, 1), &[], false, None).ok();
                    }
                }

                // workaround
                self.no_more_requests = true;

                return Some(Err(e));
            }

            let rq = rq_res.unwrap();

            // checking HTTP version
            if *rq.http_version() > (1, 1) {
                let writer = self.sink.next().unwrap();
                let response = Response::from_string(
                    "This server only supports HTTP versions 1.0 and 1.1".to_owned(),
                )
                .with_status_code(StatusCode(505));
                response
                    .raw_print(writer, HTTPVersion(1, 1), &[], false, None)
                    .ok();
                continue;
            }

            // updating the status of the connection
            let connection_header = rq
                .headers()
                .iter()
                .find(|h| h.field.equiv("Connection"))
                .map(|h| h.value.as_str());

            let lowercase = connection_header.map(|h| h.to_ascii_lowercase());

            match lowercase 
            {
                Some(ref val) if val.contains("close") => self.no_more_requests = true,
                Some(ref val) if val.contains("upgrade") => self.no_more_requests = true,
                Some(ref val)
                    if !val.contains("keep-alive") && *rq.http_version() == HTTPVersion(1, 0) =>
                {
                    self.no_more_requests = true
                }
                None if *rq.http_version() == HTTPVersion(1, 0) => self.no_more_requests = true,
                _ => (),
            };

            // returning the request
            return Some(Ok(rq));
        }
    }
}

/// Parses a "HTTP/1.1" string.
fn parse_http_version(version: &str) -> Result<HTTPVersion, ReadError> {
    let (major, minor) = match version {
        "HTTP/0.9" => (0, 9),
        "HTTP/1.0" => (1, 0),
        "HTTP/1.1" => (1, 1),
        "HTTP/2.0" => (2, 0),
        "HTTP/3.0" => (3, 0),
        _ => return Err(ReadError::WrongRequestLine),
    };

    Ok(HTTPVersion(major, minor))
}

/// Parses the request line of the request.
/// eg. GET / HTTP/1.1
fn parse_request_line(line: &str) -> Result<(Method, String, HTTPVersion), ReadError> {
    let mut parts = line.split(' ');

    let method = parts.next().and_then(|w| w.parse().ok());
    let path = parts.next().map(ToOwned::to_owned);
    let version = parts.next().and_then(|w| parse_http_version(w).ok());

    method
        .and_then(|method| Some((method, path?, version?)))
        .ok_or(ReadError::WrongRequestLine)
}

#[cfg(test)]
mod test 
{
    use std::{iter::Peekable, str::Bytes};
    use ascii::AsciiString;
    use super::*;

    #[test]
    fn test_parse_request_line() 
    {
        let (method, path, ver) = super::parse_request_line("GET /hello HTTP/1.1").unwrap();

        assert!(method == crate::Method::Get);
        assert!(path == "/hello");
        assert!(ver == crate::common::HTTPVersion(1, 1));

        assert!(super::parse_request_line("GET /hello").is_err());
        assert!(super::parse_request_line("qsd qsd qsd").is_err());
    }

    fn new_readline(line: &str) -> Result<Vec<String>, ReadError> 
    {   
        let mut line_itr = line.bytes().peekable();
        let mut res = Vec::with_capacity(6);

        while let Some(_) = line_itr.peek()
        {
            res.push(new_readline_int(&mut line_itr).map(|v| v.as_str().to_string())?);
        }

        return Ok(res);
    }   

    fn new_readline_int(line_itr: &mut Peekable<Bytes<'_>>) -> Result<AsciiString, ReadError> 
    {
        let mut buf = Vec::new();
        let mut rn = [0_u8; 2];
        let mut rn_p = 0;
        const RNC: u16 = u16::from_le_bytes([b'\r', b'\n']);

        
        loop 
        {
            let cur_byte = 
                line_itr.next()
                    .ok_or_else(||
                       ReadError::ReadIoError(IoError::new(ErrorKind::ConnectionAborted, "Unexpected EOF"))
                    )?;

            match rn_p
            {
                0 => 
                {
                    if cur_byte != b'\r' && cur_byte != b'\n'
                    { // most times true
                        buf.push(cur_byte);
                    }
                    else
                    {
                        rn[rn_p] = cur_byte;
                        rn_p += 1;
                    }
                },
                _ =>
                {
                    rn[rn_p] = cur_byte;

                    if u16::from_le_bytes(rn) != RNC
                    {
                        // error
                        return Err(ReadError::WrongRequestLine);
                    }

                    return
                        AsciiString::from_ascii(buf)
                            .map_err(|_| ReadError::ReadIoError(IoError::new(ErrorKind::InvalidInput, "Header is not in ASCII")));
                }
            }
        }
    }

    #[test]
    fn test_new_readline()
    {
        let vals = new_readline("Server: 小さなHTTPサーバー (Rust)\r\n");
        assert_eq!(vals.is_err(), true);

        let vals = new_readline("Server: tiny-http (Rust)\r\n").unwrap();
        assert_eq!(vals.len(), 1);
        assert_eq!(vals.contains(&"Server: tiny-http (Rust)".into()), true);

        let vals = new_readline("Server: tiny-http (Rust)\r\nContent-Type: text/plain; charset=UTF-8\r\n").unwrap();
        assert_eq!(vals.len(), 2);
        assert_eq!(vals.contains(&"Server: tiny-http (Rust)".into()), true);
        assert_eq!(vals.contains(&"Content-Type: text/plain; charset=UTF-8".into()), true);

        let vals = new_readline("Server: tiny-http (Rust)\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n").unwrap();
        assert_eq!(vals.len(), 3);
        assert_eq!(vals.contains(&"Server: tiny-http (Rust)".into()), true);
        assert_eq!(vals.contains(&"Content-Type: text/plain; charset=UTF-8".into()), true);


        assert_eq!(new_readline("Server: tiny-http (Rust)\r\r\n").is_err(), true);
        assert_eq!(new_readline("Server: tiny-http (Rust)\n\r\n").is_err(), true);
        assert_eq!(new_readline("Server: tiny-http\n(Rust)\r\n").is_err(), true);
        assert_eq!(new_readline("GET / HTTP/1.1\r\nHost: x\r\nX-Test: aaa\nbbb\r\nConnection: close\r\n\r\n").is_err(), true);
    }

    fn new_readline_utf8(line: &str) -> Result<Vec<String>, ReadError> 
    {   
        let mut line_itr = line.bytes().peekable();
        let mut res = Vec::with_capacity(6);

        while let Some(_) = line_itr.peek()
        {
            res.push(new_readline_int_utf(&mut line_itr).map(|v| v.as_str().to_string())?);
        }

        return Ok(res);
    } 

    fn new_readline_int_utf(line_itr: &mut Peekable<Bytes<'_>>) -> Result<String, ReadError> 
    {
        let mut buf = Vec::new();
        let mut rn = [0_u8; 2];
        let mut rn_p = 0;
        const RNC: u16 = u16::from_le_bytes([b'\r', b'\n']);

        
        loop 
        {
            let cur_byte = 
                line_itr.next()
                    .ok_or_else(||
                       ReadError::ReadIoError(IoError::new(ErrorKind::ConnectionAborted, "Unexpected EOF"))
                    )?;

            match rn_p
            {
                0 => 
                {
                    if cur_byte != b'\r' && cur_byte != b'\n'
                    { // most times true
                        buf.push(cur_byte);
                    }
                    else
                    {
                        rn[rn_p] = cur_byte;
                        rn_p += 1;
                    }
                },
                _ =>
                {
                    rn[rn_p] = cur_byte;

                    if u16::from_le_bytes(rn) != RNC
                    {
                        // error
                        return Err(ReadError::WrongRequestLine);
                    }

                    return
                        String::from_utf8(buf)
                            .map_err(|_| ReadError::ReadIoError(IoError::new(ErrorKind::InvalidInput, "Header is not in ASCII")));
                }
            }
        }
    }

    #[test]
    fn test_new_readline_utf8()
    {
        let vals = new_readline_utf8("Server: 小さなHTTPサーバー (Rust)\r\n").unwrap();
        assert_eq!(vals.len(), 1);
        assert_eq!(vals.contains(&"Server: 小さなHTTPサーバー (Rust)".into()), true);

        let vals = new_readline_utf8("Server: tiny-http (Rust)\r\n").unwrap();
        assert_eq!(vals.len(), 1);
        assert_eq!(vals.contains(&"Server: tiny-http (Rust)".into()), true);

        let vals = new_readline_utf8("Server: tiny-http (Rust)\r\nContent-Type: text/plain; charset=UTF-8\r\n").unwrap();
        assert_eq!(vals.len(), 2);
        assert_eq!(vals.contains(&"Server: tiny-http (Rust)".into()), true);
        assert_eq!(vals.contains(&"Content-Type: text/plain; charset=UTF-8".into()), true);

        let vals = new_readline_utf8("Server: tiny-http (Rust)\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n").unwrap();
        assert_eq!(vals.len(), 3);
        assert_eq!(vals.contains(&"Server: tiny-http (Rust)".into()), true);
        assert_eq!(vals.contains(&"Content-Type: text/plain; charset=UTF-8".into()), true);


        assert_eq!(new_readline_utf8("Server: tiny-http (Rust)\r\r\n").is_err(), true);
        assert_eq!(new_readline_utf8("Server: tiny-http (Rust)\n\r\n").is_err(), true);
        assert_eq!(new_readline_utf8("Server: tiny-http\n(Rust)\r\n").is_err(), true);
        assert_eq!(new_readline_utf8("GET / HTTP/1.1\r\nHost: x\r\nX-Test: aaa\nbbb\r\nConnection: close\r\n\r\n").is_err(), true);
    }
}