Skip to main content

pitchfork_cli/proxy/
hosts.rs

1//! /etc/hosts management for the reverse proxy.
2//!
3//! Automatically syncs registered slug hostnames into `/etc/hosts` so that
4//! browsers can resolve them (needed for Safari, which doesn't auto-resolve
5//! `.localhost` subdomains, and for custom TLDs like `.test`).
6//!
7//! Entries are managed inside a marked block delimited by
8//! `# pitchfork-start` / `# pitchfork-end`.  The block is replaced on each
9//! sync and removed entirely on proxy shutdown.
10
11use crate::settings::settings;
12use std::sync::OnceLock;
13
14/// Marker lines for the pitchfork-managed block in /etc/hosts.
15const MARKER_START: &str = "# pitchfork-start";
16const MARKER_END: &str = "# pitchfork-end";
17static BLANK_LINES_RE: OnceLock<regex::Regex> = OnceLock::new();
18
19/// Sync the given slug hostnames into /etc/hosts.
20///
21/// Builds the expected hosts block and replaces (or appends) the
22/// pitchfork-managed block.
23///
24/// Best-effort: logs a warning on failure (e.g. permission denied) and
25/// does not prevent proxy startup.
26fn sync_hosts_file_with_slugs(bind_ip: &str, tld: &str, slug_names: &[String]) {
27    write_hosts_block(&hosts_entries(bind_ip, tld, slug_names));
28}
29
30/// One `<ip> <slug>.<tld>` line per routable slug.
31///
32/// Slugs that collide with another by case are left out: host names are
33/// case-insensitive, so the proxy refuses to route them, and an entry here
34/// would point at an address it will not serve.
35fn hosts_entries(bind_ip: &str, tld: &str, slug_names: &[String]) -> Vec<String> {
36    let collisions = crate::proxy::ascii_case_collisions(slug_names.iter().map(String::as_str));
37    slug_names
38        .iter()
39        .filter(|slug| !collisions.contains(&slug.to_ascii_lowercase()))
40        .map(|slug| format!("{bind_ip} {slug}.{tld}"))
41        .collect()
42}
43
44/// Refresh `/etc/hosts` from the current settings if sync is enabled.
45///
46/// Used when slug registrations change while the proxy is already running.
47/// In LAN mode, entries are mapped to the detected LAN IP instead of 127.0.0.1.
48pub fn sync_hosts_from_settings() {
49    let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
50    let slug_names: Vec<String> = slugs.keys().cloned().collect();
51    sync_hosts_from_settings_with_slugs(&slug_names);
52}
53
54/// Like `sync_hosts_from_settings`, but with a caller-provided slug list.
55///
56/// Use this from code that holds the global config fslock: reading the slug
57/// registry here would re-acquire that lock via `PitchforkToml::read()`, and
58/// flock(2) is per open file description, so the same process would deadlock
59/// against its own held lock.
60pub fn sync_hosts_from_settings_with_slugs(slug_names: &[String]) {
61    let s = settings();
62    if s.proxy.enable && s.proxy.sync_hosts {
63        let lan_enabled = s.proxy.lan || !s.proxy.lan_ip.is_empty();
64        let tld = if lan_enabled { "local" } else { &s.proxy.tld };
65        // In LAN mode, map to the LAN IP (or configured lan_ip) so that
66        // /etc/hosts entries work for mDNS-resolved hostnames on the LAN.
67        let ip = if lan_enabled {
68            // Try the configured lan_ip first, otherwise fall back to the proxy.host.
69            if !s.proxy.lan_ip.is_empty() {
70                s.proxy.lan_ip.clone()
71            } else {
72                // Auto-detected LAN IP is async and not available here.
73                // Fall back to proxy.host (which defaults to 127.0.0.1
74                // but may be overridden by the user).  The mDNS records
75                // handle the actual resolution on the LAN.
76                s.proxy.host.clone()
77            }
78        } else {
79            s.proxy.host.clone()
80        };
81        sync_hosts_file_with_slugs(&ip, tld, slug_names);
82    }
83}
84
85/// Remove the pitchfork-managed block from /etc/hosts.
86///
87/// Called on proxy shutdown to clean up stale entries.
88pub fn clean_hosts_file() {
89    write_hosts_block(&[]);
90}
91
92/// Read /etc/hosts, replace the marked block, write back atomically.
93fn write_hosts_block(entries: &[String]) {
94    let path = crate::env::PITCHFORK_HOSTS_FILE.clone();
95
96    let content = match std::fs::read_to_string(&path) {
97        Ok(c) => c,
98        Err(e) => {
99            if !entries.is_empty() {
100                log::warn!(
101                    "Failed to read {} for hosts sync: {e}. \
102                     Set proxy.sync_hosts = false to suppress this warning.",
103                    path.display()
104                );
105            }
106            return;
107        }
108    };
109
110    let cleaned = remove_block(&content);
111
112    let new_content = if entries.is_empty() {
113        cleaned
114    } else {
115        let block = build_block(entries);
116        format!("{}\n{block}\n", cleaned.trim_end())
117    };
118
119    // Atomic write: write to a temp file in the same directory, then rename.
120    let parent = path.parent().unwrap_or(std::path::Path::new("/etc"));
121    let tmp_path = parent.join(format!(".pitchfork-hosts-tmp-{}", std::process::id()));
122
123    if let Err(e) = std::fs::write(&tmp_path, &new_content) {
124        log::warn!(
125            "Failed to write {} for hosts sync: {e}. \
126             Writing to /etc/hosts may require sudo. \
127             Set proxy.sync_hosts = false to suppress this warning.",
128            tmp_path.display()
129        );
130        let _ = std::fs::remove_file(&tmp_path);
131        return;
132    }
133
134    if let Err(e) = std::fs::rename(&tmp_path, &path) {
135        log::warn!(
136            "Failed to rename {} to {}: {e}. \
137             Writing to /etc/hosts may require sudo. \
138             Set proxy.sync_hosts = false to suppress this warning.",
139            tmp_path.display(),
140            path.display()
141        );
142        let _ = std::fs::remove_file(&tmp_path);
143    }
144}
145
146/// Build the pitchfork-managed block for the given entries.
147fn build_block(entries: &[String]) -> String {
148    if entries.is_empty() {
149        return String::new();
150    }
151    let lines = entries.join("\n");
152    format!("{MARKER_START}\n{lines}\n{MARKER_END}")
153}
154
155/// Remove the pitchfork-managed block from /etc/hosts content and return
156/// the cleaned content with trailing newlines normalized.
157fn remove_block(content: &str) -> String {
158    let start_idx = match content.find(MARKER_START) {
159        Some(i) => i,
160        None => return content.to_string(),
161    };
162    let end_idx = match content[start_idx..].find(MARKER_END) {
163        Some(i) => start_idx + i + MARKER_END.len(),
164        None => return content.to_string(),
165    };
166    let before = &content[..start_idx];
167    let after = &content[end_idx..];
168    let result = format!("{before}{after}");
169    // Normalize excessive blank lines caused by removing the block
170    let re = BLANK_LINES_RE.get_or_init(|| regex::Regex::new(r"\n{3,}").unwrap());
171    re.replace_all(&result, "\n\n").trim_end().to_string() + "\n"
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    #[test]
179    fn test_build_block() {
180        let entries = vec![
181            "127.0.0.1 myapp.localhost".to_string(),
182            "127.0.0.1 api.myapp.localhost".to_string(),
183        ];
184        let block = build_block(&entries);
185        assert!(block.starts_with("# pitchfork-start\n"));
186        assert!(block.ends_with("\n# pitchfork-end"));
187        assert!(block.contains("127.0.0.1 myapp.localhost"));
188        assert!(block.contains("127.0.0.1 api.myapp.localhost"));
189    }
190
191    #[test]
192    fn test_hosts_entries_omits_case_collisions() {
193        let slugs = ["myapp".to_string(), "API".to_string(), "api".to_string()];
194        let entries = hosts_entries("127.0.0.1", "localhost", &slugs);
195        // Neither spelling of the colliding slug is published.
196        assert_eq!(entries, vec!["127.0.0.1 myapp.localhost".to_string()]);
197    }
198
199    #[test]
200    fn test_build_block_empty() {
201        assert!(build_block(&[]).is_empty());
202    }
203
204    #[test]
205    fn test_remove_block() {
206        let content =
207            "127.0.0.1 localhost\n# pitchfork-start\n127.0.0.1 myapp.localhost\n# pitchfork-end\n";
208        let cleaned = remove_block(content);
209        assert!(!cleaned.contains("pitchfork-start"));
210        assert!(!cleaned.contains("myapp.localhost"));
211        assert!(cleaned.contains("127.0.0.1 localhost"));
212    }
213
214    #[test]
215    fn test_remove_block_no_markers() {
216        let content = "127.0.0.1 localhost\n";
217        let cleaned = remove_block(content);
218        assert_eq!(cleaned, content);
219    }
220
221    #[test]
222    fn test_remove_block_normalizes_blank_lines() {
223        let content = "127.0.0.1 localhost\n\n\n# pitchfork-start\n127.0.0.1 myapp.localhost\n# pitchfork-end\n\n\n";
224        let cleaned = remove_block(content);
225        assert!(!cleaned.contains("\n\n\n"));
226    }
227
228    #[test]
229    fn test_remove_block_ignores_end_marker_before_start_marker() {
230        let content = "127.0.0.1 localhost\n# pitchfork-end\n# pitchfork-start\n127.0.0.1 myapp.localhost\n# pitchfork-end\n";
231        let cleaned = remove_block(content);
232        assert_eq!(cleaned, "127.0.0.1 localhost\n# pitchfork-end\n");
233    }
234}