armybox 0.3.0

A memory-safe #[no_std] BusyBox/Toybox clone in Rust - 299 Unix utilities in ~500KB
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
//! httpd - simple HTTP daemon
//!
//! Minimal HTTP server.

extern crate alloc;
use alloc::vec::Vec;
use crate::io;
use crate::sys;
use super::get_arg;

/// httpd - simple HTTP daemon
///
/// # Synopsis
/// ```text
/// httpd [-f] [-p PORT] [-h HOME]
/// ```
///
/// # Description
/// Simple HTTP web server daemon. Serves static files from the specified
/// directory (default: current directory).
///
/// # Options
/// - `-f`: Don't daemonize, stay in foreground
/// - `-p PORT`: Listen on PORT (default: 80)
/// - `-h HOME`: Document root directory (default: .)
/// - `-v`: Verbose mode
///
/// # Supported Features
/// - GET requests
/// - Directory index (index.html)
/// - MIME type detection
/// - Basic error pages (404, 403)
///
/// # Exit Status
/// - 0: Success
/// - 1: Error
#[cfg(target_os = "linux")]
pub fn httpd(argc: i32, argv: *const *const u8) -> i32 {
    let mut foreground = false;
    let mut port: u16 = 80;
    let mut doc_root: &[u8] = b".";
    let mut verbose = false;

    // Parse arguments
    let mut i = 1;
    while i < argc as usize {
        let arg = match unsafe { get_arg(argv, i as i32) } {
            Some(a) => a,
            None => break,
        };

        if arg == b"-f" {
            foreground = true;
        } else if arg == b"-p" {
            i += 1;
            if let Some(p) = unsafe { get_arg(argv, i as i32) } {
                port = sys::parse_u64(p).unwrap_or(80) as u16;
            }
        } else if arg == b"-h" {
            i += 1;
            if let Some(h) = unsafe { get_arg(argv, i as i32) } {
                doc_root = h;
            }
        } else if arg == b"-v" {
            verbose = true;
        } else if arg == b"--help" {
            print_usage();
            return 0;
        }
        i += 1;
    }

    // Change to document root
    if io::chdir(doc_root) < 0 {
        io::write_str(2, b"httpd: cannot chdir to ");
        io::write_all(2, doc_root);
        io::write_str(2, b"\n");
        return 1;
    }

    // Create listening socket
    let listen_fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0) };
    if listen_fd < 0 {
        io::write_str(2, b"httpd: socket failed\n");
        return 1;
    }

    // Set SO_REUSEADDR
    let opt: i32 = 1;
    unsafe {
        libc::setsockopt(listen_fd, libc::SOL_SOCKET, libc::SO_REUSEADDR,
                         &opt as *const _ as *const libc::c_void,
                         core::mem::size_of::<i32>() as u32);
    }

    // Bind
    let mut addr: libc::sockaddr_in = unsafe { core::mem::zeroed() };
    addr.sin_family = libc::AF_INET as u16;
    addr.sin_port = port.to_be();
    addr.sin_addr.s_addr = 0; // INADDR_ANY

    if unsafe { libc::bind(listen_fd, &addr as *const _ as *const libc::sockaddr,
                           core::mem::size_of::<libc::sockaddr_in>() as u32) } < 0 {
        io::write_str(2, b"httpd: bind failed (port ");
        let mut buf = [0u8; 16];
        io::write_all(2, sys::format_u64(port as u64, &mut buf));
        io::write_str(2, b")\n");
        io::close(listen_fd);
        return 1;
    }

    // Listen
    if unsafe { libc::listen(listen_fd, 10) } < 0 {
        io::write_str(2, b"httpd: listen failed\n");
        io::close(listen_fd);
        return 1;
    }

    // Daemonize unless -f
    if !foreground {
        let pid = unsafe { libc::fork() };
        if pid < 0 {
            io::write_str(2, b"httpd: fork failed\n");
            io::close(listen_fd);
            return 1;
        }
        if pid > 0 {
            // Parent exits
            return 0;
        }

        // Create new session
        unsafe { libc::setsid() };

        // Close standard streams
        io::close(0);
        io::close(1);
        io::close(2);

        // Redirect to /dev/null
        let null_fd = io::open(b"/dev/null", libc::O_RDWR, 0);
        if null_fd >= 0 {
            io::dup2(null_fd, 0);
            io::dup2(null_fd, 1);
            io::dup2(null_fd, 2);
            if null_fd > 2 {
                io::close(null_fd);
            }
        }
    } else if verbose {
        io::write_str(1, b"httpd: listening on port ");
        let mut buf = [0u8; 16];
        io::write_all(1, sys::format_u64(port as u64, &mut buf));
        io::write_str(1, b"\n");
    }

    // Accept loop
    loop {
        let mut client_addr: libc::sockaddr_in = unsafe { core::mem::zeroed() };
        let mut addr_len = core::mem::size_of::<libc::sockaddr_in>() as u32;

        let client_fd = unsafe {
            libc::accept(listen_fd, &mut client_addr as *mut _ as *mut libc::sockaddr, &mut addr_len)
        };

        if client_fd < 0 {
            continue;
        }

        // Fork to handle request
        let pid = unsafe { libc::fork() };
        if pid == 0 {
            // Child - handle request
            io::close(listen_fd);
            handle_request(client_fd, verbose);
            io::close(client_fd);
            unsafe { libc::_exit(0) };
        } else {
            // Parent - close client fd and continue
            io::close(client_fd);

            // Reap zombies
            unsafe {
                libc::waitpid(-1, core::ptr::null_mut(), libc::WNOHANG);
            }
        }
    }
}

#[cfg(target_os = "linux")]
fn handle_request(fd: i32, _verbose: bool) {
    let mut buf = [0u8; 4096];
    let n = io::read(fd, &mut buf);
    if n <= 0 {
        return;
    }

    // Parse request line: GET /path HTTP/1.x
    let request = &buf[..n as usize];

    // Find method
    let mut pos = 0;
    while pos < request.len() && request[pos] != b' ' {
        pos += 1;
    }
    let method = &request[..pos];

    // Skip space
    while pos < request.len() && request[pos] == b' ' {
        pos += 1;
    }

    // Find path
    let path_start = pos;
    while pos < request.len() && request[pos] != b' ' && request[pos] != b'?' {
        pos += 1;
    }
    let path = &request[path_start..pos];

    // Only support GET
    if method != b"GET" {
        send_error(fd, 405, b"Method Not Allowed");
        return;
    }

    // Decode path (basic - just handle %20 for spaces)
    let decoded_path = decode_url(path);

    // Security: reject paths with ..
    if has_dotdot(&decoded_path) {
        send_error(fd, 403, b"Forbidden");
        return;
    }

    // Remove leading slash and handle root
    let file_path = if decoded_path.len() <= 1 {
        b"index.html".to_vec()
    } else {
        decoded_path[1..].to_vec()
    };

    // Check if directory, append index.html
    let final_path = if is_directory(&file_path) {
        let mut p = file_path.clone();
        if !p.ends_with(b"/") {
            p.push(b'/');
        }
        p.extend_from_slice(b"index.html");
        p
    } else {
        file_path
    };

    // Try to open file
    let file_fd = io::open(&final_path, libc::O_RDONLY, 0);
    if file_fd < 0 {
        send_error(fd, 404, b"Not Found");
        return;
    }

    // Get file size
    let mut stat_buf = io::stat_zeroed();
    if io::fstat(file_fd, &mut stat_buf) < 0 {
        io::close(file_fd);
        send_error(fd, 500, b"Internal Server Error");
        return;
    }

    let content_length = stat_buf.st_size as u64;
    let content_type = get_mime_type(&final_path);

    // Send response headers
    io::write_all(fd, b"HTTP/1.0 200 OK\r\n");
    io::write_all(fd, b"Server: armybox httpd\r\n");
    io::write_all(fd, b"Content-Type: ");
    io::write_all(fd, content_type);
    io::write_all(fd, b"\r\n");
    io::write_all(fd, b"Content-Length: ");
    let mut len_buf = [0u8; 20];
    io::write_all(fd, sys::format_u64(content_length, &mut len_buf));
    io::write_all(fd, b"\r\n");
    io::write_all(fd, b"Connection: close\r\n");
    io::write_all(fd, b"\r\n");

    // Send file content
    let mut send_buf = [0u8; 8192];
    loop {
        let n = io::read(file_fd, &mut send_buf);
        if n <= 0 {
            break;
        }
        io::write_all(fd, &send_buf[..n as usize]);
    }

    io::close(file_fd);
}

#[cfg(target_os = "linux")]
fn send_error(fd: i32, code: u32, message: &[u8]) {
    let mut buf = [0u8; 16];

    io::write_all(fd, b"HTTP/1.0 ");
    io::write_all(fd, sys::format_u64(code as u64, &mut buf));
    io::write_all(fd, b" ");
    io::write_all(fd, message);
    io::write_all(fd, b"\r\n");
    io::write_all(fd, b"Content-Type: text/html\r\n");
    io::write_all(fd, b"Connection: close\r\n");
    io::write_all(fd, b"\r\n");
    io::write_all(fd, b"<html><body><h1>");
    io::write_all(fd, sys::format_u64(code as u64, &mut buf));
    io::write_all(fd, b" ");
    io::write_all(fd, message);
    io::write_all(fd, b"</h1></body></html>\n");
}

fn decode_url(url: &[u8]) -> Vec<u8> {
    let mut result = Vec::with_capacity(url.len());
    let mut i = 0;
    while i < url.len() {
        if url[i] == b'%' && i + 2 < url.len() {
            // Decode hex
            let h1 = hex_digit(url[i + 1]);
            let h2 = hex_digit(url[i + 2]);
            if let (Some(d1), Some(d2)) = (h1, h2) {
                result.push((d1 << 4) | d2);
                i += 3;
                continue;
            }
        }
        result.push(url[i]);
        i += 1;
    }
    result
}

fn hex_digit(c: u8) -> Option<u8> {
    match c {
        b'0'..=b'9' => Some(c - b'0'),
        b'a'..=b'f' => Some(c - b'a' + 10),
        b'A'..=b'F' => Some(c - b'A' + 10),
        _ => None,
    }
}

fn has_dotdot(path: &[u8]) -> bool {
    let mut i = 0;
    while i < path.len() {
        if path[i] == b'.' && i + 1 < path.len() && path[i + 1] == b'.' {
            // Check if it's a path component
            let before_ok = i == 0 || path[i - 1] == b'/';
            let after_ok = i + 2 >= path.len() || path[i + 2] == b'/';
            if before_ok && after_ok {
                return true;
            }
        }
        i += 1;
    }
    false
}

fn is_directory(path: &[u8]) -> bool {
    let mut stat_buf = io::stat_zeroed();
    if io::stat(path, &mut stat_buf) < 0 {
        return false;
    }
    (stat_buf.st_mode & libc::S_IFMT) == libc::S_IFDIR
}

fn get_mime_type(path: &[u8]) -> &'static [u8] {
    // Find extension
    let mut ext_start = path.len();
    for i in (0..path.len()).rev() {
        if path[i] == b'.' {
            ext_start = i + 1;
            break;
        }
        if path[i] == b'/' {
            break;
        }
    }

    if ext_start >= path.len() {
        return b"application/octet-stream";
    }

    let ext = &path[ext_start..];

    // Common MIME types
    if ext == b"html" || ext == b"htm" {
        b"text/html"
    } else if ext == b"css" {
        b"text/css"
    } else if ext == b"js" {
        b"application/javascript"
    } else if ext == b"json" {
        b"application/json"
    } else if ext == b"txt" {
        b"text/plain"
    } else if ext == b"xml" {
        b"application/xml"
    } else if ext == b"png" {
        b"image/png"
    } else if ext == b"jpg" || ext == b"jpeg" {
        b"image/jpeg"
    } else if ext == b"gif" {
        b"image/gif"
    } else if ext == b"svg" {
        b"image/svg+xml"
    } else if ext == b"ico" {
        b"image/x-icon"
    } else if ext == b"pdf" {
        b"application/pdf"
    } else if ext == b"zip" {
        b"application/zip"
    } else if ext == b"tar" {
        b"application/x-tar"
    } else if ext == b"gz" {
        b"application/gzip"
    } else if ext == b"mp3" {
        b"audio/mpeg"
    } else if ext == b"mp4" {
        b"video/mp4"
    } else if ext == b"webm" {
        b"video/webm"
    } else if ext == b"woff" {
        b"font/woff"
    } else if ext == b"woff2" {
        b"font/woff2"
    } else {
        b"application/octet-stream"
    }
}

fn print_usage() {
    io::write_str(1, b"Usage: httpd [-f] [-p PORT] [-h HOME]\n\n");
    io::write_str(1, b"Simple HTTP server.\n\n");
    io::write_str(1, b"Options:\n");
    io::write_str(1, b"  -f        Stay in foreground\n");
    io::write_str(1, b"  -p PORT   Listen on PORT (default: 80)\n");
    io::write_str(1, b"  -h HOME   Document root (default: .)\n");
    io::write_str(1, b"  -v        Verbose mode\n");
}

#[cfg(not(target_os = "linux"))]
pub fn httpd(_argc: i32, _argv: *const *const u8) -> i32 {
    io::write_str(2, b"httpd: only available on Linux\n");
    1
}

#[cfg(test)]
mod tests {
    extern crate std;
    use std::process::Command;
    use std::path::PathBuf;

    fn get_armybox_path() -> PathBuf {
        if let Ok(path) = std::env::var("ARMYBOX_PATH") {
            return PathBuf::from(path);
        }
        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|_| std::env::current_dir().unwrap());
        let release = manifest_dir.join("target/release/armybox");
        if release.exists() { return release; }
        manifest_dir.join("target/debug/armybox")
    }

    #[test]
    fn test_httpd_help() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["httpd", "--help"])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));
        let stdout = std::string::String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains("Usage"));
    }

    #[test]
    fn test_mime_types() {
        use super::get_mime_type;

        assert_eq!(get_mime_type(b"index.html"), b"text/html");
        assert_eq!(get_mime_type(b"style.css"), b"text/css");
        assert_eq!(get_mime_type(b"app.js"), b"application/javascript");
        assert_eq!(get_mime_type(b"image.png"), b"image/png");
        assert_eq!(get_mime_type(b"data.json"), b"application/json");
    }

    #[test]
    fn test_has_dotdot() {
        use super::has_dotdot;

        assert!(has_dotdot(b".."));
        assert!(has_dotdot(b"/../"));
        assert!(has_dotdot(b"/foo/../bar"));
        assert!(!has_dotdot(b"/foo/bar"));
        assert!(!has_dotdot(b"/foo..bar"));
    }

    #[test]
    fn test_decode_url() {
        use super::decode_url;

        assert_eq!(decode_url(b"hello%20world"), b"hello world");
        assert_eq!(decode_url(b"test%2Fpath"), b"test/path");
        assert_eq!(decode_url(b"normal"), b"normal");
    }
}