pitchfork_cli/proxy/
hosts.rs1use crate::settings::settings;
12use std::sync::OnceLock;
13
14const MARKER_START: &str = "# pitchfork-start";
16const MARKER_END: &str = "# pitchfork-end";
17static BLANK_LINES_RE: OnceLock<regex::Regex> = OnceLock::new();
18
19fn 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
30fn 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
44pub 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
54pub 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 let ip = if lan_enabled {
68 if !s.proxy.lan_ip.is_empty() {
70 s.proxy.lan_ip.clone()
71 } else {
72 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
85pub fn clean_hosts_file() {
89 write_hosts_block(&[]);
90}
91
92fn 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 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
146fn 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
155fn 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 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 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}