kinjo 0.1.0

Kinjo: mDNS TUI and commands launch for local network services
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
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use color_eyre::eyre::{Result, eyre};

use crate::discovery::Entry;

use super::{ActionMode, CommandAction};

#[derive(Debug, Clone)]
pub struct PreparedCommand {
    pub argv: Vec<String>,
    pub mode: ActionMode,
}

pub fn prepare(action: &CommandAction, record: &Entry) -> Result<PreparedCommand> {
    // Split the template into arguments *before* interpolating, so a service
    // field (which arrives from untrusted devices on the network) can only ever
    // fill in an argument — quotes or whitespace in a value cannot add, remove,
    // or reshape arguments.
    let argv = split_command_line(&action.command)?
        .iter()
        .map(|token| interpolate(token, record))
        .collect::<Result<Vec<_>>>()?;
    if argv.is_empty() {
        return Err(eyre!("action command expanded to an empty argv"));
    }
    Ok(PreparedCommand {
        argv,
        mode: action.mode,
    })
}

pub fn fork(command: &PreparedCommand) -> Result<()> {
    let mut child = Command::new(&command.argv[0])
        .args(&command.argv[1..])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .map_err(|err| spawn_error(&command.argv[0], err))?;
    // Reap the child once it exits so it does not linger as a zombie for the
    // lifetime of the TUI. The thread parks in `wait` and goes away with the
    // child; if the TUI exits first, orphans are re-parented and reaped by init.
    std::thread::spawn(move || {
        let _ = child.wait();
    });
    Ok(())
}

pub fn exec(command: PreparedCommand) -> Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;

        // `exec` only returns when the hand-off fails; on success the current
        // process image is replaced and control never comes back.
        let err = Command::new(&command.argv[0])
            .args(&command.argv[1..])
            .exec();
        Err(spawn_error(&command.argv[0], err))
    }

    #[cfg(not(unix))]
    {
        let status = Command::new(&command.argv[0])
            .args(&command.argv[1..])
            .status()
            .map_err(|err| spawn_error(&command.argv[0], err))?;
        if status.success() {
            Ok(())
        } else {
            Err(eyre!("process exited with status {status}"))
        }
    }
}

/// Turn a spawn/exec failure into a user-facing message, special-casing the
/// common "binary not on PATH" case so the report is actionable rather than a
/// bare OS error code.
fn spawn_error(program: &str, err: std::io::Error) -> color_eyre::eyre::Report {
    if err.kind() == std::io::ErrorKind::NotFound {
        eyre!("command `{program}` not found")
    } else {
        eyre!("could not start `{program}`: {err}")
    }
}

/// A declared dependency of a command, parsed from a `requirements` entry such
/// as `"xdg-open"` or `"browser, optional"`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Requirement {
    pub command: String,
    pub optional: bool,
}

/// Parse a single `requirements` entry. The optional `, optional` suffix marks a
/// dependency whose absence should not block the action.
pub fn parse_requirement(raw: &str) -> Requirement {
    let mut parts = raw.splitn(2, ',');
    let command = parts.next().unwrap_or("").trim().to_string();
    let optional = parts
        .next()
        .is_some_and(|rest| rest.trim().eq_ignore_ascii_case("optional"));
    Requirement { command, optional }
}

/// Name of the first mandatory requirement that cannot be resolved on `PATH`,
/// if any. Optional and blank requirements are ignored.
pub fn missing_requirement(requirements: &[String]) -> Option<String> {
    requirements
        .iter()
        .map(|raw| parse_requirement(raw))
        .filter(|req| !req.optional && !req.command.is_empty())
        .find(|req| locate(&req.command).is_none())
        .map(|req| req.command)
}

/// Resolve `program` the way the OS would when spawning it: an explicit path
/// (containing a separator) is checked directly, otherwise each `PATH` entry is
/// tried. Returns the resolved path when it names an executable file.
pub fn locate(program: &str) -> Option<PathBuf> {
    if program.is_empty() {
        return None;
    }
    if program.chars().any(std::path::is_separator) {
        let path = PathBuf::from(program);
        return is_executable(&path).then_some(path);
    }
    let paths = std::env::var_os("PATH")?;
    std::env::split_paths(&paths)
        .flat_map(|dir| candidates_in(&dir, program))
        .find(|candidate| is_executable(candidate))
}

/// The paths under `dir` that could resolve `program`: the bare name, plus — on
/// Windows — the name with each `PATHEXT` extension appended, mirroring how
/// `CreateProcess` resolves `ping` to `ping.exe`.
#[cfg(windows)]
fn candidates_in(dir: &Path, program: &str) -> Vec<PathBuf> {
    let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string());
    let mut candidates = vec![dir.join(program)];
    candidates.extend(
        pathext
            .split(';')
            .filter(|ext| !ext.is_empty())
            .map(|ext| dir.join(format!("{program}{ext}"))),
    );
    candidates
}

#[cfg(not(windows))]
fn candidates_in(dir: &Path, program: &str) -> Vec<PathBuf> {
    vec![dir.join(program)]
}

#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    std::fs::metadata(path)
        .map(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
        .unwrap_or(false)
}

#[cfg(not(unix))]
fn is_executable(path: &Path) -> bool {
    path.is_file()
}

fn interpolate(template: &str, record: &Entry) -> Result<String> {
    let mut output = String::new();
    let mut chars = template.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch != '{' {
            output.push(ch);
            continue;
        }
        let mut field = String::new();
        loop {
            let Some(next) = chars.next() else {
                return Err(eyre!("unterminated interpolation in `{template}`"));
            };
            if next == '}' {
                break;
            }
            field.push(next);
        }
        let Some(value) = record.field(&field) else {
            return Err(eyre!(
                "service field `{field}` is unavailable for `{}`",
                record.name
            ));
        };
        output.push_str(&value);
    }
    Ok(output)
}

fn split_command_line(command: &str) -> Result<Vec<String>> {
    let mut argv = Vec::new();
    let mut current = String::new();
    let mut chars = command.chars().peekable();
    let mut quote: Option<char> = None;

    while let Some(ch) = chars.next() {
        match (quote, ch) {
            (Some(q), c) if c == q => quote = None,
            (Some(_), '\\') => {
                if let Some(next) = chars.next() {
                    current.push(next);
                }
            }
            (Some(_), c) => current.push(c),
            (None, '"' | '\'') => quote = Some(ch),
            (None, '\\') => {
                if let Some(next) = chars.next() {
                    current.push(next);
                }
            }
            (None, c) if c.is_whitespace() => {
                if !current.is_empty() {
                    argv.push(std::mem::take(&mut current));
                }
            }
            (None, c) => current.push(c),
        }
    }

    if let Some(q) = quote {
        return Err(eyre!("unterminated `{q}` quote in command"));
    }
    if !current.is_empty() {
        argv.push(current);
    }
    Ok(argv)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plumber::ActionMode;
    use std::net::{IpAddr, Ipv4Addr};

    #[test]
    fn interpolates_and_splits() {
        let mut record = Entry::new("alpha", "_ssh._tcp", "local");
        record.hostname = Some("alpha.local".to_string());
        let action = CommandAction {
            description: None,
            command: "ssh '{hostname}'".to_string(),
            mode: ActionMode::Execute,
        };
        let prepared = prepare(&action, &record).unwrap();
        assert_eq!(prepared.argv, vec!["ssh", "alpha.local"]);
    }

    #[test]
    fn prepares_all_supported_service_fields() {
        let mut record = Entry::new("Kitchen Printer", "_ipp._tcp", "local");
        record.hostname = Some("printer.local".to_string());
        record.addresses = vec![IpAddr::V4(Ipv4Addr::new(192, 0, 2, 20))];
        record.port = Some(631);
        record
            .txt
            .insert("path".to_string(), "/ipp/print".to_string());
        let action = CommandAction {
            description: None,
            command: "open '{name}' {service_type} {domain} {hostname} {address} {port} {txt.path}"
                .to_string(),
            mode: ActionMode::Fork,
        };

        let prepared = prepare(&action, &record).unwrap();

        assert_eq!(prepared.mode, ActionMode::Fork);
        assert_eq!(
            prepared.argv,
            vec![
                "open",
                "Kitchen Printer",
                "_ipp._tcp",
                "local",
                "printer.local",
                "192.0.2.20",
                "631",
                "/ipp/print",
            ]
        );
    }

    #[test]
    fn splits_quoted_and_escaped_arguments() {
        let record = Entry::new("alpha", "_ssh._tcp", "local");
        let action = CommandAction {
            description: None,
            command: r#"printf "two words" one\ arg 'single quoted' "\\""#.to_string(),
            mode: ActionMode::Execute,
        };

        let prepared = prepare(&action, &record).unwrap();

        assert_eq!(
            prepared.argv,
            vec!["printf", "two words", "one arg", "single quoted", "\\"]
        );
    }

    #[test]
    fn interpolated_values_cannot_inject_arguments() {
        // Service fields arrive from untrusted devices on the network. Quotes
        // and whitespace in a value must land inside one argument, never create
        // new ones (e.g. an extra `-oProxyCommand=...` for ssh).
        let mut record = Entry::new("alpha", "_ssh._tcp", "local");
        record.hostname = Some("h.local' -oProxyCommand=evil '".to_string());
        let action = CommandAction {
            description: None,
            command: "ssh {hostname}".to_string(),
            mode: ActionMode::Execute,
        };

        let prepared = prepare(&action, &record).unwrap();

        assert_eq!(prepared.argv, vec!["ssh", "h.local' -oProxyCommand=evil '"]);
    }

    #[test]
    fn values_with_quotes_and_spaces_stay_single_arguments() {
        // A legitimate name like `O'Brien Printer` must not break tokenizing.
        let mut record = Entry::new("O'Brien Printer", "_ipp._tcp", "local");
        record.hostname = Some("printer.local".to_string());
        let action = CommandAction {
            description: None,
            command: "notify-send {name} {hostname}".to_string(),
            mode: ActionMode::Fork,
        };

        let prepared = prepare(&action, &record).unwrap();

        assert_eq!(
            prepared.argv,
            vec!["notify-send", "O'Brien Printer", "printer.local"]
        );
    }

    #[test]
    fn missing_interpolation_field_is_an_error() {
        let record = Entry::new("alpha", "_ssh._tcp", "local");
        let action = CommandAction {
            description: None,
            command: "ssh {hostname}".to_string(),
            mode: ActionMode::Execute,
        };

        let err = prepare(&action, &record).unwrap_err();

        assert!(err.to_string().contains("service field `hostname`"));
        assert!(err.to_string().contains("alpha"));
    }

    #[test]
    fn malformed_templates_and_quotes_are_errors() {
        let record = Entry::new("alpha", "_ssh._tcp", "local");
        let unterminated_interpolation = CommandAction {
            description: None,
            command: "echo {name".to_string(),
            mode: ActionMode::Execute,
        };
        let unterminated_quote = CommandAction {
            description: None,
            command: "echo 'alpha".to_string(),
            mode: ActionMode::Execute,
        };

        assert!(
            prepare(&unterminated_interpolation, &record)
                .unwrap_err()
                .to_string()
                .contains("unterminated interpolation")
        );
        assert!(
            prepare(&unterminated_quote, &record)
                .unwrap_err()
                .to_string()
                .contains("unterminated `'` quote")
        );
    }

    #[test]
    fn fork_spawns_a_real_process() {
        let record = Entry::new("alpha", "_ssh._tcp", "local");
        let action = CommandAction {
            description: None,
            command: "true".to_string(),
            mode: ActionMode::Fork,
        };

        let prepared = prepare(&action, &record).unwrap();
        assert_eq!(prepared.mode, ActionMode::Fork);
        // `true` exits 0 immediately; forking it should succeed without error.
        fork(&prepared).unwrap();
    }

    #[test]
    fn fork_reports_a_missing_binary() {
        let command = PreparedCommand {
            argv: vec!["kinjo-no-such-binary-xyz".to_string()],
            mode: ActionMode::Fork,
        };

        let err = fork(&command).unwrap_err();
        assert!(
            err.to_string()
                .contains("command `kinjo-no-such-binary-xyz` not found")
        );
    }

    #[test]
    fn interpolates_txt_record_fields() {
        let mut record = Entry::new("nas", "_http._tcp", "local");
        record.hostname = Some("nas.local".to_string());
        record.txt.insert("path".to_string(), "/admin".to_string());
        let action = CommandAction {
            description: None,
            command: "xdg-open http://{hostname}{txt.path}".to_string(),
            mode: ActionMode::Fork,
        };

        let prepared = prepare(&action, &record).unwrap();

        assert_eq!(prepared.argv, vec!["xdg-open", "http://nas.local/admin"]);
    }

    #[test]
    fn missing_txt_field_is_an_error() {
        let record = Entry::new("nas", "_http._tcp", "local");
        let action = CommandAction {
            description: None,
            command: "echo {txt.path}".to_string(),
            mode: ActionMode::Fork,
        };

        let err = prepare(&action, &record).unwrap_err();

        assert!(err.to_string().contains("service field `txt.path`"));
    }

    #[test]
    fn empty_command_after_splitting_is_an_error() {
        let record = Entry::new("alpha", "_ssh._tcp", "local");
        let action = CommandAction {
            description: None,
            command: "   ".to_string(),
            mode: ActionMode::Execute,
        };

        let err = prepare(&action, &record).unwrap_err();

        assert!(err.to_string().contains("empty argv"));
    }

    #[test]
    fn parse_requirement_detects_the_optional_marker() {
        assert_eq!(
            parse_requirement("xdg-open"),
            Requirement {
                command: "xdg-open".to_string(),
                optional: false,
            }
        );
        assert_eq!(
            parse_requirement("  browser ,  Optional "),
            Requirement {
                command: "browser".to_string(),
                optional: true,
            }
        );
        // A trailing word other than `optional` is not treated as the marker.
        assert!(!parse_requirement("foo, please").optional);
    }

    /// A command guaranteed to be on `PATH` for the current platform.
    #[cfg(windows)]
    const PRESENT_COMMAND: &str = "cmd.exe";
    #[cfg(not(windows))]
    const PRESENT_COMMAND: &str = "sh";

    #[test]
    fn locate_resolves_absolute_paths_and_path_lookups() {
        // The running test binary is an executable file at a known absolute path.
        let exe = std::env::current_exe().unwrap();
        assert!(locate(exe.to_str().unwrap()).is_some());

        // A shell interpreter is present on every supported platform.
        assert!(locate(PRESENT_COMMAND).is_some());

        assert!(locate("kinjo-no-such-binary-xyz").is_none());
        assert!(locate("/no/such/absolute/path/xyz").is_none());
        assert!(locate("").is_none());
    }

    /// Windows resolves bare names through `PATHEXT`; a requirement written as
    /// `cmd` (no extension) must still be found.
    #[cfg(windows)]
    #[test]
    fn locate_resolves_bare_names_via_pathext() {
        assert!(locate("cmd").is_some());
    }

    #[test]
    fn missing_requirement_skips_optional_and_present_commands() {
        assert_eq!(missing_requirement(&[]), None);
        assert_eq!(missing_requirement(&[PRESENT_COMMAND.to_string()]), None);
        assert_eq!(
            missing_requirement(&["definitely-absent-xyz, optional".to_string()]),
            None
        );
        assert_eq!(
            missing_requirement(&[
                PRESENT_COMMAND.to_string(),
                "definitely-absent-xyz".to_string()
            ]),
            Some("definitely-absent-xyz".to_string())
        );
    }
}