lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! Minimal HTTP/1.1 server for S3 gateway.
//!
//! This module provides a lightweight HTTP server implementation
//! suitable for both std and no_std environments.

use alloc::collections::BTreeMap;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};

use super::types::{HttpMethod, HttpRequest, HttpResponse};

/// Characters that should NOT be percent-encoded in URL components.
/// Only alphanumeric and: - _ . ~ are preserved (RFC 3986 unreserved characters)
const URL_ENCODE_SET: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'_')
    .remove(b'.')
    .remove(b'~');

// ═══════════════════════════════════════════════════════════════════════════════
// NETWORK PROVIDER TRAIT
// ═══════════════════════════════════════════════════════════════════════════════

/// Network provider for TCP operations.
///
/// This trait abstracts TCP networking for both std and no_std environments.
pub trait NetworkProvider: Send + Sync {
    /// TCP listener type.
    type Listener: TcpListenerTrait;
    /// TCP stream type.
    type Stream: TcpStreamTrait;

    /// Create a TCP listener bound to address and port.
    fn tcp_listen(&self, addr: &str, port: u16) -> Result<Self::Listener, IoError>;
}

/// TCP listener trait.
pub trait TcpListenerTrait {
    /// Stream type for accepted connections.
    type Stream: TcpStreamTrait;

    /// Accept a new connection.
    fn accept(&self) -> Result<Self::Stream, IoError>;

    /// Set non-blocking mode.
    fn set_nonblocking(&self, nonblocking: bool) -> Result<(), IoError>;
}

/// TCP stream trait.
pub trait TcpStreamTrait {
    /// Read data from the stream.
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError>;

    /// Write data to the stream.
    fn write(&mut self, buf: &[u8]) -> Result<usize, IoError>;

    /// Write all data to the stream.
    fn write_all(&mut self, buf: &[u8]) -> Result<(), IoError> {
        let mut written = 0;
        while written < buf.len() {
            written += self.write(&buf[written..])?;
        }
        Ok(())
    }

    /// Flush the stream.
    fn flush(&mut self) -> Result<(), IoError>;

    /// Shutdown the stream.
    fn shutdown(&mut self) -> Result<(), IoError>;

    /// Set read timeout in milliseconds.
    fn set_read_timeout(&mut self, timeout_ms: Option<u64>) -> Result<(), IoError>;

    /// Set write timeout in milliseconds.
    fn set_write_timeout(&mut self, timeout_ms: Option<u64>) -> Result<(), IoError>;

    /// Get peer address as string.
    fn peer_addr(&self) -> Result<String, IoError>;
}

/// I/O error type.
#[derive(Debug, Clone)]
pub struct IoError {
    /// Error kind.
    pub kind: IoErrorKind,
    /// Error message.
    pub message: String,
}

/// I/O error kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IoErrorKind {
    /// Connection refused.
    ConnectionRefused,
    /// Connection reset.
    ConnectionReset,
    /// Connection aborted.
    ConnectionAborted,
    /// Not connected.
    NotConnected,
    /// Address in use.
    AddrInUse,
    /// Address not available.
    AddrNotAvailable,
    /// Would block.
    WouldBlock,
    /// Timed out.
    TimedOut,
    /// Interrupted.
    Interrupted,
    /// Invalid input.
    InvalidInput,
    /// Invalid data.
    InvalidData,
    /// Unexpected EOF.
    UnexpectedEof,
    /// Other error.
    Other,
}

impl IoError {
    /// Create a new I/O error.
    pub fn new(kind: IoErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// HTTP PARSING
// ═══════════════════════════════════════════════════════════════════════════════

/// HTTP parse error.
#[derive(Debug, Clone)]
pub enum HttpParseError {
    /// Invalid request line.
    InvalidRequestLine,
    /// Invalid method.
    InvalidMethod,
    /// Invalid header.
    InvalidHeader,
    /// Missing host header.
    MissingHost,
    /// Content too large.
    ContentTooLarge,
    /// IO error.
    Io(IoError),
}

impl From<IoError> for HttpParseError {
    fn from(e: IoError) -> Self {
        HttpParseError::Io(e)
    }
}

/// Maximum request size (16 MB).
const MAX_REQUEST_SIZE: usize = 16 * 1024 * 1024;

/// Maximum header size (64 KB).
const MAX_HEADER_SIZE: usize = 64 * 1024;

/// Parse an HTTP request from a stream.
pub fn parse_request<S: TcpStreamTrait>(stream: &mut S) -> Result<HttpRequest, HttpParseError> {
    // Read headers
    let mut header_buf = vec![0u8; MAX_HEADER_SIZE];
    let mut header_len = 0;

    loop {
        if header_len >= MAX_HEADER_SIZE {
            return Err(HttpParseError::ContentTooLarge);
        }

        let n = stream.read(&mut header_buf[header_len..header_len + 1])?;
        if n == 0 {
            return Err(HttpParseError::Io(IoError::new(
                IoErrorKind::UnexpectedEof,
                "connection closed",
            )));
        }
        header_len += n;

        // Check for end of headers (\r\n\r\n)
        if header_len >= 4 && &header_buf[header_len - 4..header_len] == b"\r\n\r\n" {
            break;
        }
    }

    // Parse the headers
    let header_str = core::str::from_utf8(&header_buf[..header_len])
        .map_err(|_| HttpParseError::InvalidHeader)?;

    let mut lines = header_str.lines();

    // Parse request line
    let request_line = lines.next().ok_or(HttpParseError::InvalidRequestLine)?;
    let parts: Vec<&str> = request_line.split_whitespace().collect();
    if parts.len() < 2 {
        return Err(HttpParseError::InvalidRequestLine);
    }

    let method = HttpMethod::from_str(parts[0]).ok_or(HttpParseError::InvalidMethod)?;
    let path_and_query = parts[1];

    // Parse path and query
    let (path, query) = if let Some(idx) = path_and_query.find('?') {
        let (p, q) = path_and_query.split_at(idx);
        (p.to_string(), parse_query_string(&q[1..]))
    } else {
        (path_and_query.to_string(), BTreeMap::new())
    };

    // Parse headers
    let mut headers = BTreeMap::new();
    for line in lines {
        if line.is_empty() {
            break;
        }
        if let Some(idx) = line.find(':') {
            let name = line[..idx].trim().to_string();
            let value = line[idx + 1..].trim().to_string();
            headers.insert(name, value);
        }
    }

    // Read body if Content-Length is present
    let content_length: usize = headers
        .get("Content-Length")
        .or_else(|| headers.get("content-length"))
        .and_then(|s| s.parse().ok())
        .unwrap_or(0);

    if content_length > MAX_REQUEST_SIZE {
        return Err(HttpParseError::ContentTooLarge);
    }

    let mut body = vec![0u8; content_length];
    if content_length > 0 {
        let mut read = 0;
        while read < content_length {
            let n = stream.read(&mut body[read..])?;
            if n == 0 {
                break;
            }
            read += n;
        }
        body.truncate(read);
    }

    Ok(HttpRequest {
        method,
        path,
        query,
        headers,
        body,
    })
}

/// Parse query string into key-value pairs.
fn parse_query_string(query: &str) -> BTreeMap<String, String> {
    let mut params = BTreeMap::new();
    for pair in query.split('&') {
        if let Some(idx) = pair.find('=') {
            let key = url_decode(&pair[..idx]);
            let value = url_decode(&pair[idx + 1..]);
            params.insert(key, value);
        } else if !pair.is_empty() {
            params.insert(url_decode(pair), String::new());
        }
    }
    params
}

/// URL decode a string.
fn url_decode(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '%' {
            // Get next two hex digits
            let h1 = chars.next();
            let h2 = chars.next();
            if let (Some(h1), Some(h2)) = (h1, h2) {
                if let Ok(byte) = u8::from_str_radix(&format!("{}{}", h1, h2), 16) {
                    result.push(byte as char);
                    continue;
                }
            }
            result.push('%');
        } else if c == '+' {
            result.push(' ');
        } else {
            result.push(c);
        }
    }

    result
}

/// URL encode a string.
///
/// Uses percent-encoding crate for RFC 3986 compliant encoding.
pub fn url_encode(s: &str) -> String {
    utf8_percent_encode(s, URL_ENCODE_SET).to_string()
}

// ═══════════════════════════════════════════════════════════════════════════════
// HTTP WRITING
// ═══════════════════════════════════════════════════════════════════════════════

/// Write an HTTP response to a stream.
pub fn write_response<S: TcpStreamTrait>(
    stream: &mut S,
    response: &HttpResponse,
) -> Result<(), IoError> {
    // Status line
    let status_text = status_text(response.status);
    let status_line = alloc::format!("HTTP/1.1 {} {}\r\n", response.status, status_text);
    stream.write_all(status_line.as_bytes())?;

    // Content-Length header
    let content_length = alloc::format!("Content-Length: {}\r\n", response.body.len());
    stream.write_all(content_length.as_bytes())?;

    // Other headers
    for (name, value) in &response.headers {
        let header = alloc::format!("{}: {}\r\n", name, value);
        stream.write_all(header.as_bytes())?;
    }

    // Empty line
    stream.write_all(b"\r\n")?;

    // Body
    stream.write_all(&response.body)?;

    stream.flush()
}

/// Get status text for HTTP status code.
fn status_text(code: u16) -> &'static str {
    match code {
        100 => "Continue",
        200 => "OK",
        201 => "Created",
        204 => "No Content",
        206 => "Partial Content",
        301 => "Moved Permanently",
        302 => "Found",
        304 => "Not Modified",
        400 => "Bad Request",
        401 => "Unauthorized",
        403 => "Forbidden",
        404 => "Not Found",
        405 => "Method Not Allowed",
        409 => "Conflict",
        411 => "Length Required",
        412 => "Precondition Failed",
        413 => "Payload Too Large",
        416 => "Range Not Satisfiable",
        500 => "Internal Server Error",
        501 => "Not Implemented",
        503 => "Service Unavailable",
        _ => "Unknown",
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// HTTP CONNECTION HANDLER
// ═══════════════════════════════════════════════════════════════════════════════

/// HTTP connection.
pub struct HttpConnection<S: TcpStreamTrait> {
    /// The underlying stream.
    stream: S,
    /// Peer address.
    peer_addr: String,
}

impl<S: TcpStreamTrait> HttpConnection<S> {
    /// Create a new connection.
    pub fn new(mut stream: S) -> Result<Self, IoError> {
        let peer_addr = stream.peer_addr().unwrap_or_else(|_| "unknown".into());
        // Set timeouts
        stream.set_read_timeout(Some(30000))?;
        stream.set_write_timeout(Some(30000))?;
        Ok(Self { stream, peer_addr })
    }

    /// Get the peer address.
    pub fn peer_addr(&self) -> &str {
        &self.peer_addr
    }

    /// Read an HTTP request.
    pub fn read_request(&mut self) -> Result<HttpRequest, HttpParseError> {
        parse_request(&mut self.stream)
    }

    /// Write an HTTP response.
    pub fn write_response(&mut self, response: &HttpResponse) -> Result<(), IoError> {
        write_response(&mut self.stream, response)
    }

    /// Close the connection.
    pub fn close(mut self) -> Result<(), IoError> {
        self.stream.shutdown()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

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

    #[test]
    fn test_parse_query_string() {
        let params = parse_query_string("foo=bar&baz=qux");
        assert_eq!(params.get("foo"), Some(&"bar".to_string()));
        assert_eq!(params.get("baz"), Some(&"qux".to_string()));
    }

    #[test]
    fn test_parse_query_string_empty() {
        let params = parse_query_string("");
        assert!(params.is_empty());
    }

    #[test]
    fn test_parse_query_string_encoded() {
        let params = parse_query_string("path=%2Ftest%2Ffile");
        assert_eq!(params.get("path"), Some(&"/test/file".to_string()));
    }

    #[test]
    fn test_url_decode() {
        assert_eq!(url_decode("hello%20world"), "hello world");
        assert_eq!(url_decode("foo+bar"), "foo bar");
        assert_eq!(url_decode("test%2Fpath"), "test/path");
    }

    #[test]
    fn test_url_encode() {
        assert_eq!(url_encode("hello world"), "hello%20world");
        assert_eq!(url_encode("test/path"), "test%2Fpath");
        assert_eq!(url_encode("a-b_c.d~e"), "a-b_c.d~e");
    }

    #[test]
    fn test_status_text() {
        assert_eq!(status_text(200), "OK");
        assert_eq!(status_text(404), "Not Found");
        assert_eq!(status_text(500), "Internal Server Error");
    }

    #[test]
    fn test_io_error() {
        let err = IoError::new(IoErrorKind::ConnectionRefused, "connection refused");
        assert_eq!(err.kind, IoErrorKind::ConnectionRefused);
        assert_eq!(err.message, "connection refused");
    }

    /// Mock stream for testing.
    struct MockStream {
        read_data: Vec<u8>,
        read_pos: usize,
        write_data: Vec<u8>,
    }

    impl MockStream {
        fn new(data: &[u8]) -> Self {
            Self {
                read_data: data.to_vec(),
                read_pos: 0,
                write_data: Vec::new(),
            }
        }
    }

    impl TcpStreamTrait for MockStream {
        fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError> {
            if self.read_pos >= self.read_data.len() {
                return Ok(0);
            }
            let n = core::cmp::min(buf.len(), self.read_data.len() - self.read_pos);
            buf[..n].copy_from_slice(&self.read_data[self.read_pos..self.read_pos + n]);
            self.read_pos += n;
            Ok(n)
        }

        fn write(&mut self, buf: &[u8]) -> Result<usize, IoError> {
            self.write_data.extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> Result<(), IoError> {
            Ok(())
        }

        fn shutdown(&mut self) -> Result<(), IoError> {
            Ok(())
        }

        fn set_read_timeout(&mut self, _timeout_ms: Option<u64>) -> Result<(), IoError> {
            Ok(())
        }

        fn set_write_timeout(&mut self, _timeout_ms: Option<u64>) -> Result<(), IoError> {
            Ok(())
        }

        fn peer_addr(&self) -> Result<String, IoError> {
            Ok("127.0.0.1:12345".into())
        }
    }

    #[test]
    fn test_parse_request() {
        let request = b"GET /bucket/key?foo=bar HTTP/1.1\r\n\
                        Host: localhost\r\n\
                        Content-Length: 4\r\n\
                        \r\n\
                        test";

        let mut stream = MockStream::new(request);
        let req = parse_request(&mut stream).unwrap();

        assert_eq!(req.method, HttpMethod::Get);
        assert_eq!(req.path, "/bucket/key");
        assert_eq!(req.query.get("foo"), Some(&"bar".to_string()));
        assert_eq!(req.body, b"test");
    }

    #[test]
    fn test_parse_request_no_body() {
        let request = b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";

        let mut stream = MockStream::new(request);
        let req = parse_request(&mut stream).unwrap();

        assert_eq!(req.method, HttpMethod::Get);
        assert_eq!(req.path, "/");
        assert!(req.body.is_empty());
    }

    #[test]
    fn test_write_response() {
        let response = HttpResponse::ok()
            .with_header("X-Test", "value")
            .with_body(b"Hello".to_vec());

        let mut stream = MockStream::new(b"");
        write_response(&mut stream, &response).unwrap();

        let output = String::from_utf8(stream.write_data).unwrap();
        assert!(output.contains("HTTP/1.1 200 OK"));
        assert!(output.contains("Content-Length: 5"));
        assert!(output.contains("X-Test: value"));
        assert!(output.ends_with("Hello"));
    }
}