1pub const TCP_RULE_NAME: &str = "AgentMux LAN (TCP)";
11pub const UDP_RULE_NAME: &str = "AgentMux LAN (UDP)";
13pub const TCP_PORTS: &str = "29700-29799";
15pub const UDP_PORTS: &str = "5353,29700,47891";
17pub const PROFILES_PRIVATE_DOMAIN: i32 = 1 | 2;
20pub const REMOTE_LOCAL_SUBNET: &str = "LocalSubnet";
22pub const PROTO_TCP: i32 = 6;
24pub const PROTO_UDP: i32 = 17;
25
26pub const CONFIGURE_FLAG: &str = "--configure-lan-firewall";
29pub const EXIT_OK: i32 = 0;
31pub const EXIT_CANCELLED: i32 = 1223;
33pub const EXIT_MANAGED: i32 = 2;
35pub const EXIT_FAILED: i32 = 3;
37pub const EXIT_UNVERIFIED: i32 = 4;
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Spec {
44 pub name: &'static str,
45 pub protocol: i32,
46 pub local_ports: &'static str,
47}
48
49pub const SPECS: [Spec; 2] = [
51 Spec { name: TCP_RULE_NAME, protocol: PROTO_TCP, local_ports: TCP_PORTS },
52 Spec { name: UDP_RULE_NAME, protocol: PROTO_UDP, local_ports: UDP_PORTS },
53];
54
55#[derive(Debug, Clone, Default, PartialEq, Eq)]
57pub struct Existing {
58 pub name: String,
59 pub enabled: bool,
60 pub inbound: bool,
61 pub allow: bool,
62 pub profiles: i32,
64 pub program: String,
66 pub protocol: i32,
67 pub local_ports: String,
68 pub remote: String,
69 pub local_addresses: String,
71 pub interfaces_named: bool,
73 pub interface_types: String,
75 pub bound: bool,
78 pub program_exists: bool,
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum Mode {
85 Configure,
88 Remove,
90}
91
92#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum Op {
95 RemoveNamed(&'static str),
97 Delete(usize),
100 Add(Spec),
102}
103
104pub fn is_agentmux_program(path: &str) -> bool {
106 let base = path.rsplit(['\\', '/']).next().unwrap_or("").to_ascii_lowercase();
107 base.starts_with("agentmux") && base.ends_with(".exe")
108}
109
110fn same_ports(a: &str, b: &str) -> bool {
111 let norm = |s: &str| s.split_whitespace().collect::<String>().to_ascii_lowercase();
112 !a.trim().is_empty() && norm(a) == norm(b)
113}
114
115fn any_address(s: &str) -> bool {
117 matches!(s.trim(), "" | "*")
118}
119
120fn any_interface_type(s: &str) -> bool {
122 s.trim().is_empty() || s.trim().eq_ignore_ascii_case("all")
123}
124
125fn satisfied(spec: &Spec, rules: &[&Existing]) -> bool {
129 match rules {
130 [r] => {
131 any_address(&r.local_addresses)
132 && !r.interfaces_named
133 && any_interface_type(&r.interface_types)
134 && !r.bound
135 && r.enabled
136 && r.inbound
137 && r.allow
138 && r.profiles == PROFILES_PRIVATE_DOMAIN
139 && r.program.trim().is_empty()
140 && r.protocol == spec.protocol
141 && same_ports(&r.local_ports, spec.local_ports)
142 && r.remote.trim().eq_ignore_ascii_case(REMOTE_LOCAL_SUBNET)
143 }
144 _ => false,
145 }
146}
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub enum Settled {
151 Done,
153 Unverifiable { unreadable: u32 },
156 Differs,
158}
159
160pub fn settled(left: &[Op], unreadable: u32) -> Settled {
162 if !left.is_empty() {
163 Settled::Differs
164 } else if unreadable > 0 {
165 Settled::Unverifiable { unreadable }
166 } else {
167 Settled::Done
168 }
169}
170
171pub fn plan(mode: Mode, existing: &[Existing]) -> Vec<Op> {
174 let mut removals = Vec::new();
175 let mut additions = Vec::new();
176 for spec in &SPECS {
177 let ours: Vec<&Existing> = existing.iter().filter(|e| e.name == spec.name).collect();
178 match mode {
179 Mode::Remove if !ours.is_empty() => removals.push(Op::RemoveNamed(spec.name)),
180 Mode::Configure if !satisfied(spec, &ours) => {
181 if !ours.is_empty() {
182 removals.push(Op::RemoveNamed(spec.name));
183 }
184 additions.push(Op::Add(spec.clone()));
185 }
186 _ => {}
187 }
188 }
189 if mode == Mode::Configure {
190 let is_ours = |e: &Existing| SPECS.iter().any(|s| s.name == e.name);
191 for (i, e) in existing.iter().enumerate() {
192 if is_ours(e) || !e.enabled || !e.inbound || !is_agentmux_program(&e.program) {
194 continue;
195 }
196 if !e.allow || !e.program_exists {
199 removals.push(Op::Delete(i));
200 }
201 }
202 }
203 removals.extend(additions);
204 removals
205}
206
207#[cfg(test)]
208mod tests {
209 use super::*;
210
211 const SRV: &str = r"C:\Users\user\AppData\Local\AgentMux\runtime\agentmux-srv-0.60.49-windows.x64.exe";
212
213 fn ours(spec: &Spec) -> Existing {
214 Existing {
215 name: spec.name.into(),
216 enabled: true,
217 inbound: true,
218 allow: true,
219 profiles: PROFILES_PRIVATE_DOMAIN,
220 program: String::new(),
221 protocol: spec.protocol,
222 local_ports: spec.local_ports.into(),
223 remote: REMOTE_LOCAL_SUBNET.into(),
224 local_addresses: "*".into(),
225 interfaces_named: false,
226 interface_types: "All".into(),
227 bound: false,
228 program_exists: false,
229 }
230 }
231
232 fn both() -> Vec<Existing> {
233 SPECS.iter().map(ours).collect()
234 }
235
236 fn prompt_rule(allow: bool, exists: bool) -> Existing {
237 Existing {
238 name: "agentmux-srv-0.60.49-windows.x64.exe".into(),
239 enabled: true,
240 inbound: true,
241 allow,
242 profiles: 4,
243 program: SRV.into(),
244 protocol: 256,
245 local_ports: "*".into(),
246 remote: "*".into(),
247 local_addresses: "*".into(),
248 interfaces_named: false,
249 interface_types: "All".into(),
250 bound: false,
251 program_exists: exists,
252 }
253 }
254
255 fn apply(rules: Vec<Existing>, ops: &[Op]) -> Vec<Existing> {
259 let before = rules.clone();
260 let mut rules = rules;
261 let mut gone = Vec::new();
262 for op in ops {
263 if let Op::Delete(i) = op {
264 if before.iter().filter(|r| r.name == before[*i].name).count() == 1 {
265 gone.push(*i);
266 } else {
267 rules[*i].enabled = false;
268 }
269 }
270 }
271 let mut rules: Vec<Existing> = rules.into_iter().enumerate().filter(|(i, _)| !gone.contains(i)).map(|(_, r)| r).collect();
272 for op in ops {
273 match op {
274 Op::RemoveNamed(n) => rules.retain(|r| r.name != *n),
275 Op::Add(s) => rules.push(ours(s)),
276 Op::Delete(_) => {}
277 }
278 }
279 rules
280 }
281
282 #[test]
283 fn a_machine_with_no_rules_gets_both_and_a_second_run_changes_nothing() {
284 let first = plan(Mode::Configure, &[]);
285 assert_eq!(first, vec![Op::Add(SPECS[0].clone()), Op::Add(SPECS[1].clone())]);
286 let after = apply(Vec::new(), &first);
287 assert_eq!(plan(Mode::Configure, &after), Vec::new(), "idempotent");
288 }
289
290 #[test]
291 fn the_rules_already_right_ask_for_nothing_so_no_elevation_is_asked() {
292 assert_eq!(plan(Mode::Configure, &both()), Vec::new());
293 }
294
295 #[test]
296 fn a_rule_that_differs_in_any_way_is_replaced_not_kept() {
297 let wrong: Vec<(&str, Box<dyn Fn(&mut Existing)>)> = vec![
298 ("public added", Box::new(|e| e.profiles = 7)),
299 ("private only", Box::new(|e| e.profiles = 2)),
300 ("disabled", Box::new(|e| e.enabled = false)),
301 ("outbound", Box::new(|e| e.inbound = false)),
302 ("block", Box::new(|e| e.allow = false)),
303 ("one program", Box::new(|e| e.program = SRV.into())),
304 ("other ports", Box::new(|e| e.local_ports = "29700-29710".into())),
305 ("any remote", Box::new(|e| e.remote = "*".into())),
306 ("other protocol", Box::new(|e| e.protocol = 256)),
307 ("one local address", Box::new(|e| e.local_addresses = "198.51.100.7".into())),
308 ("a named adapter", Box::new(|e| e.interfaces_named = true)),
309 ("one kind of adapter", Box::new(|e| e.interface_types = "Wireless".into())),
310 ("a service, package or user", Box::new(|e| e.bound = true)),
311 ];
312 for (what, change) in wrong {
313 let mut rules = both();
314 change(&mut rules[0]);
315 let ops = plan(Mode::Configure, &rules);
316 assert!(ops.contains(&Op::RemoveNamed(TCP_RULE_NAME)) && ops.contains(&Op::Add(SPECS[0].clone())), "{what}: {ops:?}");
317 assert!(!ops.iter().any(|o| matches!(o, Op::Add(s) if s.name == UDP_RULE_NAME)), "{what}: the other rule is right");
318 assert_eq!(plan(Mode::Configure, &apply(rules, &ops)), Vec::new(), "{what}: not idempotent");
319 }
320 }
321
322 #[test]
323 fn the_spellings_of_any_are_any() {
324 for (address, kind) in [("", ""), ("*", "All"), (" * ", "all"), ("", "ALL")] {
325 let mut rules = both();
326 rules[0].local_addresses = address.into();
327 rules[0].interface_types = kind.into();
328 assert_eq!(plan(Mode::Configure, &rules), Vec::new(), "{address:?} {kind:?}");
329 }
330 }
331
332 #[test]
333 fn a_run_is_done_only_when_nothing_is_left_and_nothing_was_unreadable() {
334 assert_eq!(settled(&[], 0), Settled::Done);
335 assert_eq!(settled(&[], 3), Settled::Unverifiable { unreadable: 3 });
336 let left = vec![Op::RemoveNamed(TCP_RULE_NAME)];
337 assert_eq!(settled(&left, 0), Settled::Differs);
338 assert_eq!(settled(&left, 3), Settled::Differs, "a change that did not take is the worse news");
339 }
340
341 #[test]
342 fn two_rules_of_our_name_are_one_after_a_run() {
343 let mut rules = both();
344 rules.push(rules[0].clone());
345 let ops = plan(Mode::Configure, &rules);
346 assert_eq!(apply(rules, &ops).iter().filter(|r| r.name == TCP_RULE_NAME).count(), 1);
347 }
348
349 #[test]
350 fn a_block_a_cancelled_prompt_left_is_removed_and_a_live_allow_is_kept() {
351 let mut rules = both();
352 rules.push(prompt_rule(false, true));
353 rules.push(prompt_rule(true, true));
354 let ops = plan(Mode::Configure, &rules);
355 assert_eq!(ops, vec![Op::Delete(2)], "{ops:?}");
356 }
357
358 #[test]
359 fn rules_that_share_a_name_are_switched_off_and_the_next_plan_asks_for_nothing() {
360 let mut rules = both();
362 rules.push(prompt_rule(false, true));
363 rules.push(prompt_rule(false, true));
364 rules.push(prompt_rule(true, false));
365 let ops = plan(Mode::Configure, &rules);
366 assert_eq!(ops, vec![Op::Delete(2), Op::Delete(3), Op::Delete(4)]);
367 let after = apply(rules, &ops);
368 assert_eq!(after.len(), 5, "a shared name cannot be removed one rule at a time, so none was");
369 assert!(after[2..].iter().all(|r| !r.enabled));
370 assert_eq!(plan(Mode::Configure, &after), Vec::new(), "idempotent: a rule that is off is not planned again");
371 }
372
373 #[test]
374 fn an_allow_for_a_program_that_is_gone_is_removed() {
375 let mut rules = both();
376 rules.push(prompt_rule(true, false));
377 assert_eq!(plan(Mode::Configure, &rules), vec![Op::Delete(2)]);
378 }
379
380 #[test]
381 fn rules_of_other_programs_are_never_touched() {
382 let mut rules = both();
383 for program in [r"C:\Program Files\Google\Chrome\Application\chrome.exe", r"C:\tools\agentmuxish.dll", r"C:\x\my-agentmux.exe", ""] {
384 rules.push(Existing { program: program.into(), allow: false, program_exists: false, ..prompt_rule(false, false) });
385 }
386 assert_eq!(plan(Mode::Configure, &rules), Vec::new());
387 rules.push(Existing { inbound: false, ..prompt_rule(false, true) });
389 assert_eq!(plan(Mode::Configure, &rules), Vec::new());
390 }
391
392 #[test]
393 fn a_program_name_is_ours_by_its_file_name_whatever_the_slash() {
394 assert!(is_agentmux_program(SRV));
395 assert!(is_agentmux_program("C:/x/AgentMux.EXE"));
396 assert!(!is_agentmux_program(r"C:\agentmux\tools\other.exe"));
397 assert!(!is_agentmux_program(""));
398 }
399
400 #[test]
401 fn remove_takes_our_two_rules_and_nothing_else() {
402 let mut rules = both();
403 rules.push(prompt_rule(false, false));
404 let ops = plan(Mode::Remove, &rules);
405 assert_eq!(ops, vec![Op::RemoveNamed(TCP_RULE_NAME), Op::RemoveNamed(UDP_RULE_NAME)]);
406 assert_eq!(plan(Mode::Remove, &apply(rules, &ops)), Vec::new());
407 assert_eq!(plan(Mode::Remove, &[]), Vec::new(), "nothing to remove asks for no elevation");
408 }
409
410 #[test]
411 fn the_port_lists_are_the_ones_the_listeners_use() {
412 assert_eq!(TCP_PORTS, "29700-29799");
415 assert_eq!(UDP_PORTS, "5353,29700,47891");
416 }
417}