reeve-cli 1.0.1

Localhost web dev stack manager: web servers, per-vhost PHP versions, SSL, and DNS — RunCloud, scaled down.
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
//! Stack diagnostics. Aggregates the health of every moving part — Homebrew,
//! web servers, FPM masters, DNS resolvers, the mkcert CA, and port usage —
//! into a flat list of pass/warn/fail checks shared by the `doctor` CLI command
//! and (as a one-line summary) the TUI.

use crate::backends::backend_for;
use crate::brew::Brew;
use crate::config::Config;
use crate::daemon::{self, Status};
use crate::dns;
use crate::ops::ServeState;
use crate::php;
use crate::services;
use crate::ssl;
use crate::state::State;
use std::collections::HashMap;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Health {
    Ok,
    Warn,
    Fail,
}

impl Health {
    pub fn symbol(&self) -> &'static str {
        match self {
            Health::Ok => "✓",
            Health::Warn => "⚠",
            Health::Fail => "✗",
        }
    }
}

/// A single diagnostic line.
pub struct Check {
    pub name: String,
    pub health: Health,
    pub detail: String,
}

impl Check {
    fn new(name: impl Into<String>, health: Health, detail: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            health,
            detail: detail.into(),
        }
    }
}

/// Run every diagnostic and return the results in display order. `brew` is
/// optional because Homebrew detection can itself fail (the first check).
pub fn run(brew: Option<&Brew>, cfg: &Config, state: &State) -> Vec<Check> {
    let mut checks = Vec::new();

    // Homebrew.
    match brew {
        Some(b) => checks.push(Check::new(
            "Homebrew",
            Health::Ok,
            b.prefix.display().to_string(),
        )),
        None => {
            checks.push(Check::new(
                "Homebrew",
                Health::Fail,
                "not found — install from https://brew.sh",
            ));
        }
    }

    // Port conflicts among enabled servers.
    for conflict in port_conflicts(state) {
        checks.push(Check::new("Ports", Health::Fail, conflict));
    }

    // Web servers: formula installed + launchd status.
    for s in &state.servers {
        let backend = backend_for(s.backend);
        if let Some(b) = brew {
            if !b.is_installed(backend.formula()) {
                checks.push(Check::new(
                    format!("server {}", s.name),
                    Health::Warn,
                    format!(
                        "{} not installed (`reeve apply` will install it)",
                        backend.formula()
                    ),
                ));
                continue;
            }
        }
        // Honest, port-aware status: launchd "running" is not enough — the
        // process must actually be bound, and no foreign process may hold the
        // port (checked even for disabled servers, to catch e.g. a stray
        // `brew services` httpd sitting on :80).
        let (health, detail) = match crate::ops::serve_state(s) {
            ServeState::Serving => {
                let ports = crate::ops::serving_ports(s);
                let list = if ports.is_empty() {
                    format!(":{}/:{}", s.http_port, s.https_port)
                } else {
                    ports
                        .iter()
                        .map(|p| format!(":{p}"))
                        .collect::<Vec<_>>()
                        .join("/")
                };
                (Health::Ok, format!("running on {list}"))
            }
            // A stopped server with sites pointing at it is why they refuse
            // connections, so don't pass it as healthy — it's the whole reason
            // someone is running `doctor`. With nothing to serve, stopped is
            // simply idle.
            ServeState::Stopped => {
                if crate::park::effective_vhosts_for(state, &s.name).is_empty() {
                    (Health::Ok, "stopped (no sites)".to_string())
                } else {
                    (
                        Health::Warn,
                        format!(
                            "stopped — its sites won't answer until you run \
                             `reeve server start {}` (TUI: enter)",
                            s.name
                        ),
                    )
                }
            }
            ServeState::LoadedNotBound => (
                Health::Fail,
                format!(
                    "loaded but not listening — empty config or failed bind (`reeve logs server-{}`)",
                    s.name
                ),
            ),
            ServeState::PortConflict { port, holder, pid } => (
                Health::Fail,
                format!("port {port} held by '{holder}' (pid {pid}) — not managed by reeve"),
            ),
            ServeState::Crashed => {
                (Health::Fail, "crashed — check `reeve logs`".to_string())
            }
        };
        checks.push(Check::new(format!("server {}", s.name), health, detail));
    }

    // Which series Homebrew's unversioned `php` currently holds. Reported on its
    // own because it is the moving part behind every "it was installed
    // yesterday" PHP failure, and knowing where it sits explains the rest.
    if let Some(b) = brew {
        if let Some(v) = php::default_version(b) {
            checks.push(Check::new(
                "brew php",
                Health::Ok,
                format!("unversioned keg is {v} — it moves on at each series bump"),
            ));
        }
    }

    // PHP: a keg still resolves + FPM socket alive.
    for p in &state.php_versions {
        // Appended to the socket line for a version running off the keg that
        // moves, so it never looks like an ordinary pinned one.
        let mut note = String::new();
        if let Some(b) = brew {
            match php::keg(b, &p.version) {
                php::Keg::Missing => {
                    let mut detail = php::missing_message(b, &p.version);
                    // A master started before the keg moved keeps running off
                    // the same path — which now holds a different PHP. Sites on
                    // this version are being served the wrong one, quietly, so
                    // this is the one case worth spelling out.
                    if daemon::socket_alive(std::path::Path::new(&p.fpm_socket)) {
                        detail.push_str(
                            " Its FPM master is still up on the old path and may now be \
                             serving a different PHP version.",
                        );
                    }
                    checks.push(Check::new(
                        format!("php {}", p.version),
                        Health::Fail,
                        detail,
                    ));
                    continue;
                }
                php::Keg::Floating { actual, .. } => {
                    note = format!(" — {}", php::floating_note(&p.version, &actual));
                }
                php::Keg::Pinned { .. } => {}
            }
        }
        let socket = std::path::Path::new(&p.fpm_socket);
        if daemon::socket_alive(socket) {
            checks.push(Check::new(
                format!("php {}", p.version),
                Health::Ok,
                format!("FPM socket live{note}"),
            ));
        } else {
            checks.push(Check::new(
                format!("php {}", p.version),
                Health::Warn,
                format!("FPM socket not present — master stopped?{note}"),
            ));
        }
    }

    // CLI php shim: only reported once the user has opted in by setting one.
    if let Some(cli_ver) = php::current_cli_php() {
        let on_path = brew.map(php::shim_on_path).unwrap_or(false);
        if php::cli_shim_dangling() {
            // The shimmed keg went away underneath us. Worth its own Fail: a
            // dangling ~/.reeve/bin/php breaks `php` in every shell on PATH,
            // not just reeve's own commands.
            checks.push(Check::new(
                "cli php",
                Health::Fail,
                format!(
                    "shim points at {cli_ver}, whose keg is gone — `php` is broken in every \
                     shell; run `reeve php pin {cli_ver}`"
                ),
            ));
        } else if on_path {
            checks.push(Check::new(
                "cli php",
                Health::Ok,
                format!("{cli_ver} (~/.reeve/bin on PATH)"),
            ));
        } else {
            checks.push(Check::new(
                "cli php",
                Health::Warn,
                format!(
                    "shim set to {cli_ver} but ~/.reeve/bin isn't ahead of Homebrew on PATH — add it to use it"
                ),
            ));
        }
    }

    // Managed services: formula installed + launchd status + port reachable.
    for svc in &state.services {
        let id = services::service_id(svc.kind);
        if let Some(b) = brew {
            if !services::is_installed(b, svc.kind) {
                checks.push(Check::new(
                    format!("service {}", svc.kind),
                    Health::Warn,
                    format!(
                        "{} not installed (`reeve service start {}` installs it)",
                        services::formula(svc.kind),
                        svc.kind
                    ),
                ));
                continue;
            }
        }
        if svc.enabled {
            let (health, detail) = match daemon::status(&id) {
                Status::Running if services::health(svc.kind) => (
                    Health::Ok,
                    format!("running, port {} open", services::port(svc.kind)),
                ),
                Status::Running => (
                    Health::Warn,
                    format!("up but port {} not answering yet", services::port(svc.kind)),
                ),
                Status::Stopped => (Health::Warn, "enabled but not running".to_string()),
                Status::Error => (Health::Fail, "crashed — check `reeve logs`".to_string()),
            };
            checks.push(Check::new(format!("service {}", svc.kind), health, detail));
        } else {
            checks.push(Check::new(
                format!("service {}", svc.kind),
                Health::Ok,
                "stopped".to_string(),
            ));
        }
    }

    // DNS resolvers, one per configured TLD.
    let dnsmasq = daemon::status(dns::service_id());
    for tld in &cfg.local_tlds {
        if dns::resolver_ok(tld) && dnsmasq == Status::Running {
            checks.push(Check::new(
                format!("dns .{tld}"),
                Health::Ok,
                "resolving → 127.0.0.1".to_string(),
            ));
        } else if !dns::resolver_ready(tld) {
            checks.push(Check::new(
                format!("dns .{tld}"),
                Health::Warn,
                "no system resolver entry — run `reeve dns setup`".to_string(),
            ));
        } else {
            checks.push(Check::new(
                format!("dns .{tld}"),
                Health::Warn,
                format!("resolver present but dnsmasq is {}", dnsmasq.as_str()),
            ));
        }
    }

    // mkcert CA: generated on disk AND actually in the trust store.
    let generated = brew
        .and_then(|b| ssl::ca_cert(b).ok())
        .map(|p| p.exists())
        .unwrap_or(false);
    let trusted = brew.map(ssl::is_trusted).unwrap_or(false);
    match (generated, trusted) {
        (_, true) => {
            checks.push(Check::new(
                "SSL CA",
                Health::Ok,
                "mkcert root trusted (local HTTPS works)".to_string(),
            ));
            // On Linux, browsers read an NSS database rather than the system
            // anchors, so curl can verify happily while Chromium still says
            // "Not secure". Report the two stores separately.
            #[cfg(target_os = "linux")]
            if !ssl::is_browser_trusted() {
                checks.push(Check::new(
                    "SSL browsers",
                    Health::Warn,
                    "CA missing from the browser (NSS) store — run `reeve ssl trust`, \
                     then fully quit and reopen the browser"
                        .to_string(),
                ));
            }
        }
        (true, false) => checks.push(Check::new(
            "SSL CA",
            Health::Warn,
            "generated but not trusted — run `reeve ssl trust` (TUI: T)".to_string(),
        )),
        (false, false) => checks.push(Check::new(
            "SSL CA",
            Health::Warn,
            "not installed — run `reeve ssl trust`".to_string(),
        )),
    }

    #[cfg(target_os = "linux")]
    linux_checks(&mut checks, state);

    checks
}

/// Linux-only host checks: user session bus reachability, login lingering (boot
/// persistence), and the unprivileged-low-port sysctl when any enabled server
/// is configured on a port below 1024.
#[cfg(target_os = "linux")]
fn linux_checks(checks: &mut Vec<Check>, state: &State) {
    if daemon::user_bus_ok() {
        checks.push(Check::new(
            "systemd user bus",
            Health::Ok,
            "`systemctl --user` responding".to_string(),
        ));
    } else {
        checks.push(Check::new(
            "systemd user bus",
            Health::Fail,
            "`systemctl --user` not responding — no user session bus (needed to run services)"
                .to_string(),
        ));
    }

    if daemon::linger_enabled() {
        checks.push(Check::new(
            "login lingering",
            Health::Ok,
            "enabled — services persist across logout / reboot".to_string(),
        ));
    } else {
        checks.push(Check::new(
            "login lingering",
            Health::Warn,
            "off — services stop at logout; run `loginctl enable-linger` (reeve init offers this)"
                .to_string(),
        ));
    }

    let low_ports: Vec<u16> = state
        .servers
        .iter()
        .filter(|s| s.enabled)
        .flat_map(|s| [s.http_port, s.https_port])
        .filter(|&p| p < 1024)
        .collect();
    if !low_ports.is_empty() && !privileged_ports_allowed() {
        checks.push(Check::new(
            "privileged ports",
            Health::Fail,
            "servers use ports < 1024 but unprivileged binding isn't allowed — \
             `reeve init` offers the sysctl fix"
                .to_string(),
        ));
    }
}

/// Current `net.ipv4.ip_unprivileged_port_start`; low enough to bind :80?
#[cfg(target_os = "linux")]
fn privileged_ports_allowed() -> bool {
    std::fs::read_to_string("/proc/sys/net/ipv4/ip_unprivileged_port_start")
        .ok()
        .and_then(|s| s.trim().parse::<u16>().ok())
        .map(|start| start <= 80)
        .unwrap_or(false)
}

/// Duplicate http/https ports across enabled servers. Mirrors the guard in
/// `State::add_server` but reports every clashing pair for the report.
pub fn port_conflicts(state: &State) -> Vec<String> {
    let mut seen: HashMap<u16, String> = HashMap::new();
    let mut out = Vec::new();
    for s in state.servers.iter().filter(|s| s.enabled) {
        for port in [s.http_port, s.https_port] {
            if let Some(other) = seen.get(&port) {
                if other != &s.name {
                    out.push(format!(
                        "port {port} used by both '{other}' and '{}'",
                        s.name
                    ));
                }
            } else {
                seen.insert(port, s.name.clone());
            }
        }
    }
    out
}

/// Worst health across all checks (for a one-line summary).
pub fn summary(checks: &[Check]) -> Health {
    if checks.iter().any(|c| c.health == Health::Fail) {
        Health::Fail
    } else if checks.iter().any(|c| c.health == Health::Warn) {
        Health::Warn
    } else {
        Health::Ok
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::{Backend, Server};

    fn srv(name: &str, http: u16, https: u16, enabled: bool) -> Server {
        Server {
            name: name.into(),
            backend: Backend::Caddy,
            http_port: http,
            https_port: https,
            enabled,
            default_site: false,
            default_preset: Default::default(),
            default_root: None,
            settings: Default::default(),
        }
    }

    #[test]
    fn detects_port_conflicts_only_for_enabled() {
        let mut state = State::default();
        state.servers.push(srv("a", 80, 443, true));
        state.servers.push(srv("b", 80, 9443, true));
        state.servers.push(srv("c", 8080, 443, false)); // disabled — ignored
        let conflicts = port_conflicts(&state);
        assert_eq!(conflicts.len(), 1);
        assert!(conflicts[0].contains("port 80"));
    }
}