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
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
//! tftp - trivial file transfer protocol client
//!
//! Simple TFTP client for file transfers.

use crate::io;
use super::get_arg;

// TFTP opcodes
const TFTP_RRQ: u16 = 1;   // Read request
const TFTP_WRQ: u16 = 2;   // Write request
const TFTP_DATA: u16 = 3;  // Data packet
const TFTP_ACK: u16 = 4;   // Acknowledgment
const TFTP_ERROR: u16 = 5; // Error packet

// TFTP constants
const TFTP_PORT: u16 = 69;
const TFTP_BLOCK_SIZE: usize = 512;

/// tftp - trivial file transfer protocol client
///
/// # Synopsis
/// ```text
/// tftp [-g|-p] -l LOCAL -r REMOTE HOST
/// ```
///
/// # Description
/// Transfer files using TFTP protocol.
///
/// # Options
/// - `-g`: Get file from server
/// - `-p`: Put file to server
/// - `-l LOCAL`: Local filename
/// - `-r REMOTE`: Remote filename
///
/// # Exit Status
/// - 0: Success
/// - 1: Error
#[cfg(target_os = "linux")]
pub fn tftp(argc: i32, argv: *const *const u8) -> i32 {
    let mut get_mode = false;
    let mut put_mode = false;
    let mut local_file: Option<&[u8]> = None;
    let mut remote_file: Option<&[u8]> = None;
    let mut host: Option<&[u8]> = None;

    // 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"-g" {
            get_mode = true;
        } else if arg == b"-p" {
            put_mode = true;
        } else if arg == b"-l" {
            i += 1;
            local_file = unsafe { get_arg(argv, i as i32) };
        } else if arg == b"-r" {
            i += 1;
            remote_file = unsafe { get_arg(argv, i as i32) };
        } else if !arg.starts_with(b"-") {
            host = Some(arg);
        }
        i += 1;
    }

    let host = match host {
        Some(h) => h,
        None => {
            io::write_str(2, b"Usage: tftp [-g|-p] -l LOCAL -r REMOTE HOST\n");
            return 1;
        }
    };

    if !get_mode && !put_mode {
        io::write_str(2, b"tftp: must specify -g (get) or -p (put)\n");
        return 1;
    }

    let local = match local_file {
        Some(f) => f,
        None => {
            io::write_str(2, b"tftp: missing local filename (-l)\n");
            return 1;
        }
    };

    let remote = match remote_file {
        Some(f) => f,
        None => local,
    };

    // Resolve host
    let server_addr = match resolve_host(host) {
        Some(a) => a,
        None => {
            io::write_str(2, b"tftp: cannot resolve host\n");
            return 1;
        }
    };

    // Create UDP socket
    let sock = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0) };
    if sock < 0 {
        io::write_str(2, b"tftp: cannot create socket\n");
        return 1;
    }

    // Set receive timeout
    let tv = libc::timeval {
        tv_sec: 5,
        tv_usec: 0,
    };
    unsafe {
        libc::setsockopt(
            sock,
            libc::SOL_SOCKET,
            libc::SO_RCVTIMEO,
            &tv as *const _ as *const libc::c_void,
            core::mem::size_of::<libc::timeval>() as libc::socklen_t,
        );
    }

    let result = if get_mode {
        tftp_get(sock, &server_addr, remote, local)
    } else {
        tftp_put(sock, &server_addr, remote, local)
    };

    unsafe { libc::close(sock) };

    result
}

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

/// Download file from TFTP server
#[cfg(target_os = "linux")]
fn tftp_get(sock: i32, server: &libc::sockaddr_in, remote: &[u8], local: &[u8]) -> i32 {
    // Build RRQ packet
    let mut packet = [0u8; 516];
    packet[0] = 0;
    packet[1] = TFTP_RRQ as u8;

    let mut pos = 2;
    for &b in remote {
        if pos < 512 {
            packet[pos] = b;
            pos += 1;
        }
    }
    packet[pos] = 0;
    pos += 1;

    for &b in b"octet" {
        packet[pos] = b;
        pos += 1;
    }
    packet[pos] = 0;
    pos += 1;

    // Send RRQ
    let mut dest = *server;
    dest.sin_port = TFTP_PORT.to_be();

    let sent = unsafe {
        libc::sendto(
            sock,
            packet.as_ptr() as *const libc::c_void,
            pos,
            0,
            &dest as *const _ as *const libc::sockaddr,
            core::mem::size_of::<libc::sockaddr_in>() as libc::socklen_t,
        )
    };

    if sent < 0 {
        io::write_str(2, b"tftp: send failed\n");
        return 1;
    }

    // Open local file
    let fd = io::open(local, libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC, 0o644);
    if fd < 0 {
        io::write_str(2, b"tftp: cannot create local file\n");
        return 1;
    }

    let mut expected_block: u16 = 1;
    let mut total_bytes: u64 = 0;

    loop {
        let mut recv_buf = [0u8; 516];
        let mut from: libc::sockaddr_in = unsafe { core::mem::zeroed() };
        let mut from_len: libc::socklen_t = core::mem::size_of::<libc::sockaddr_in>() as libc::socklen_t;

        let n = unsafe {
            libc::recvfrom(
                sock,
                recv_buf.as_mut_ptr() as *mut libc::c_void,
                recv_buf.len(),
                0,
                &mut from as *mut _ as *mut libc::sockaddr,
                &mut from_len,
            )
        };

        if n < 4 {
            io::write_str(2, b"tftp: timeout or invalid packet\n");
            io::close(fd);
            return 1;
        }

        let opcode = ((recv_buf[0] as u16) << 8) | (recv_buf[1] as u16);
        let block_num = ((recv_buf[2] as u16) << 8) | (recv_buf[3] as u16);

        if opcode == TFTP_ERROR {
            io::write_str(2, b"tftp: server error\n");
            io::close(fd);
            return 1;
        }

        if opcode != TFTP_DATA || block_num != expected_block {
            continue;
        }

        let data_len = (n as usize) - 4;
        if data_len > 0 {
            io::write_all(fd, &recv_buf[4..4 + data_len]);
            total_bytes += data_len as u64;
        }

        // Send ACK
        let ack = [0u8, TFTP_ACK as u8, recv_buf[2], recv_buf[3]];
        unsafe {
            libc::sendto(
                sock,
                ack.as_ptr() as *const libc::c_void,
                4,
                0,
                &from as *const _ as *const libc::sockaddr,
                from_len,
            );
        }

        if data_len < TFTP_BLOCK_SIZE {
            break;
        }

        expected_block = expected_block.wrapping_add(1);
    }

    io::close(fd);

    io::write_str(1, b"Received ");
    io::write_num(1, total_bytes);
    io::write_str(1, b" bytes\n");

    0
}

/// Upload file to TFTP server
#[cfg(target_os = "linux")]
fn tftp_put(sock: i32, server: &libc::sockaddr_in, remote: &[u8], local: &[u8]) -> i32 {
    let fd = io::open(local, libc::O_RDONLY, 0);
    if fd < 0 {
        io::write_str(2, b"tftp: cannot open local file\n");
        return 1;
    }

    // Build WRQ packet
    let mut packet = [0u8; 516];
    packet[0] = 0;
    packet[1] = TFTP_WRQ as u8;

    let mut pos = 2;
    for &b in remote {
        if pos < 512 {
            packet[pos] = b;
            pos += 1;
        }
    }
    packet[pos] = 0;
    pos += 1;

    for &b in b"octet" {
        packet[pos] = b;
        pos += 1;
    }
    packet[pos] = 0;
    pos += 1;

    let mut dest = *server;
    dest.sin_port = TFTP_PORT.to_be();

    unsafe {
        libc::sendto(
            sock,
            packet.as_ptr() as *const libc::c_void,
            pos,
            0,
            &dest as *const _ as *const libc::sockaddr,
            core::mem::size_of::<libc::sockaddr_in>() as libc::socklen_t,
        );
    }

    // Wait for ACK 0
    let mut recv_buf = [0u8; 516];
    let mut from: libc::sockaddr_in = unsafe { core::mem::zeroed() };
    let mut from_len: libc::socklen_t = core::mem::size_of::<libc::sockaddr_in>() as libc::socklen_t;

    let n = unsafe {
        libc::recvfrom(
            sock,
            recv_buf.as_mut_ptr() as *mut libc::c_void,
            recv_buf.len(),
            0,
            &mut from as *mut _ as *mut libc::sockaddr,
            &mut from_len,
        )
    };

    if n < 4 {
        io::write_str(2, b"tftp: no response from server\n");
        io::close(fd);
        return 1;
    }

    let opcode = ((recv_buf[0] as u16) << 8) | (recv_buf[1] as u16);
    if opcode != TFTP_ACK {
        io::write_str(2, b"tftp: server error\n");
        io::close(fd);
        return 1;
    }

    let mut block_num: u16 = 1;
    let mut total_bytes: u64 = 0;
    let mut data_buf = [0u8; TFTP_BLOCK_SIZE];

    loop {
        let n_read = io::read(fd, &mut data_buf);
        let data_len = if n_read > 0 { n_read as usize } else { 0 };

        packet[0] = 0;
        packet[1] = TFTP_DATA as u8;
        packet[2] = (block_num >> 8) as u8;
        packet[3] = (block_num & 0xFF) as u8;

        if data_len > 0 {
            packet[4..4 + data_len].copy_from_slice(&data_buf[..data_len]);
        }

        unsafe {
            libc::sendto(
                sock,
                packet.as_ptr() as *const libc::c_void,
                4 + data_len,
                0,
                &from as *const _ as *const libc::sockaddr,
                from_len,
            );
        }

        total_bytes += data_len as u64;

        let n = unsafe {
            libc::recvfrom(
                sock,
                recv_buf.as_mut_ptr() as *mut libc::c_void,
                recv_buf.len(),
                0,
                &mut from as *mut _ as *mut libc::sockaddr,
                &mut from_len,
            )
        };

        if n < 4 {
            io::write_str(2, b"tftp: timeout\n");
            io::close(fd);
            return 1;
        }

        let opcode = ((recv_buf[0] as u16) << 8) | (recv_buf[1] as u16);
        let ack_block = ((recv_buf[2] as u16) << 8) | (recv_buf[3] as u16);

        if opcode != TFTP_ACK || ack_block != block_num {
            io::write_str(2, b"tftp: invalid ACK\n");
            io::close(fd);
            return 1;
        }

        if data_len < TFTP_BLOCK_SIZE {
            break;
        }

        block_num = block_num.wrapping_add(1);
    }

    io::close(fd);

    io::write_str(1, b"Sent ");
    io::write_num(1, total_bytes);
    io::write_str(1, b" bytes\n");

    0
}

#[cfg(target_os = "linux")]
fn resolve_host(host: &[u8]) -> Option<libc::sockaddr_in> {
    if let Some(ip) = parse_ipv4(host) {
        let mut addr: libc::sockaddr_in = unsafe { core::mem::zeroed() };
        addr.sin_family = libc::AF_INET as u16;
        addr.sin_addr.s_addr = ip.to_be();
        return Some(addr);
    }

    let mut host_cstr = [0u8; 256];
    let len = core::cmp::min(host.len(), 255);
    host_cstr[..len].copy_from_slice(&host[..len]);
    host_cstr[len] = 0;

    let mut hints: libc::addrinfo = unsafe { core::mem::zeroed() };
    hints.ai_family = libc::AF_INET;
    hints.ai_socktype = libc::SOCK_DGRAM;

    let mut result: *mut libc::addrinfo = core::ptr::null_mut();

    let ret = unsafe {
        libc::getaddrinfo(
            host_cstr.as_ptr() as *const libc::c_char,
            core::ptr::null(),
            &hints,
            &mut result,
        )
    };

    if ret != 0 || result.is_null() {
        return None;
    }

    let addr = unsafe {
        let ai = &*result;
        if ai.ai_family == libc::AF_INET && !ai.ai_addr.is_null() {
            Some(*(ai.ai_addr as *const libc::sockaddr_in))
        } else {
            None
        }
    };

    unsafe { libc::freeaddrinfo(result) };
    addr
}

#[cfg(target_os = "linux")]
fn parse_ipv4(s: &[u8]) -> Option<u32> {
    let mut parts = [0u8; 4];
    let mut part_idx = 0;
    let mut current: u16 = 0;
    let mut has_digit = false;

    for &c in s {
        if c == b'.' {
            if !has_digit || part_idx >= 3 || current > 255 {
                return None;
            }
            parts[part_idx] = current as u8;
            part_idx += 1;
            current = 0;
            has_digit = false;
        } else if c >= b'0' && c <= b'9' {
            current = current * 10 + (c - b'0') as u16;
            has_digit = true;
            if current > 255 {
                return None;
            }
        } else {
            return None;
        }
    }

    if !has_digit || part_idx != 3 || current > 255 {
        return None;
    }
    parts[3] = current as u8;

    Some(((parts[0] as u32) << 24) |
         ((parts[1] as u32) << 16) |
         ((parts[2] as u32) << 8) |
         (parts[3] as u32))
}

#[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_tftp_no_args() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["tftp"])
            .output()
            .unwrap();

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

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

        let output = Command::new(&armybox)
            .args(["tftp", "-l", "file", "-r", "file", "host"])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(1));
        let stderr = std::string::String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("must specify -g"));
    }
}