//! Raw ESC/POS over TCP (JetDirect / port 9100). No CUPS/IPP. use std::io::{self, Write}; use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream, UdpSocket}; use std::sync::mpsc; use std::thread; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use super::{PrintError, PrinterDevice, PrinterTarget, PrinterTransport}; /// Default raw ESC/POS TCP port (Epson / Star / most thermal POS). pub const DEFAULT_PORT: u16 = 9100; /// Connect timeout when opening for print. pub const PRINT_CONNECT_TIMEOUT: Duration = Duration::from_secs(3); /// Short connect timeout used while probing the LAN. pub const PROBE_TIMEOUT: Duration = Duration::from_millis(250); /// How many probe workers to run in parallel during a subnet scan. const SCAN_WORKERS: usize = 64; pub struct NetworkTransport { stream: TcpStream, } impl NetworkTransport { pub fn open(host: &str, port: u16) -> Result { let addr = resolve_socket_addr(host, port)?; let stream = TcpStream::connect_timeout(&addr, PRINT_CONNECT_TIMEOUT).map_err(|e| { PrintError::Open(format!("TCP {host}:{port}: {e}")) })?; let _ = stream.set_nodelay(true); let _ = stream.set_write_timeout(Some(Duration::from_secs(10))); Ok(Self { stream }) } } impl PrinterTransport for NetworkTransport { fn write_all(&mut self, data: &[u8]) -> io::Result<()> { self.stream.write_all(data) } fn flush(&mut self) -> io::Result<()> { self.stream.flush() } } /// Parse `host`, `host:port`, or `tcp://host:port` into (host, port). pub fn parse_network_target(raw: &str) -> Option<(String, u16)> { let s = raw.trim(); if s.is_empty() { return None; } let s = s .strip_prefix("tcp://") .or_else(|| s.strip_prefix("TCP://")) .unwrap_or(s) .trim(); // [ipv6]:port — not required for typical POS; skip for now. if s.starts_with('[') { return None; } if let Some((host, port_str)) = s.rsplit_once(':') { // Avoid treating IPv4 as host:port when there are multiple colons. if host.parse::().is_ok() || (!host.is_empty() && !host.contains(':')) { if let Ok(port) = port_str.parse::() { if port != 0 && !host.is_empty() { return Some((host.to_string(), port)); } } } } // Bare hostname / IPv4 → default port. if s.parse::().is_ok() || (!s.is_empty() && !s.contains('/')) { return Some((s.to_string(), DEFAULT_PORT)); } None } pub fn network_device(host: &str, port: u16) -> PrinterDevice { let port = if port == 0 { DEFAULT_PORT } else { port }; PrinterDevice { id: format!("net:{host}:{port}"), display_name: format!("{host}:{port} — LAN (TCP)"), target: PrinterTarget::Network { host: host.to_string(), port, }, } } pub fn probe_host(host: &str, port: u16, timeout: Duration) -> bool { let Ok(addr) = resolve_socket_addr(host, port) else { return false; }; TcpStream::connect_timeout(&addr, timeout).is_ok() } fn resolve_socket_addr(host: &str, port: u16) -> Result { if let Ok(ip) = host.parse::() { return Ok(SocketAddr::new(ip, port)); } // Hostname: use blocking resolve with first result. let mut addrs = std::net::ToSocketAddrs::to_socket_addrs(&(host, port)).map_err(|e| { PrintError::Open(format!("resolve {host}: {e}")) })?; addrs .next() .ok_or_else(|| PrintError::Open(format!("resolve {host}: no addresses"))) } /// Cached LAN printer entry (persisted in `AppConfig`). #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct LanPrinterCacheEntry { pub host: String, pub port: u16, #[serde(default)] pub last_seen_unix: u64, } impl LanPrinterCacheEntry { pub fn new(host: impl Into, port: u16) -> Self { Self { host: host.into(), port: if port == 0 { DEFAULT_PORT } else { port }, last_seen_unix: unix_now(), } } } fn unix_now() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0) } /// Re-check cached hosts; return only those that still accept TCP on the port. pub fn validate_cache(cache: &[LanPrinterCacheEntry]) -> Vec { let (tx, rx) = mpsc::channel(); let mut handles = Vec::new(); for entry in cache { let host = entry.host.clone(); let port = if entry.port == 0 { DEFAULT_PORT } else { entry.port }; let tx = tx.clone(); handles.push(thread::spawn(move || { if probe_host(&host, port, PROBE_TIMEOUT) { let _ = tx.send(network_device(&host, port)); } })); } drop(tx); for h in handles { let _ = h.join(); } let mut out: Vec<_> = rx.into_iter().collect(); out.sort_by(|a, b| a.display_name.cmp(&b.display_name)); out.dedup_by(|a, b| a.id == b.id); out } /// Scan local IPv4 /24 subnets for open TCP `port`. pub fn scan_local_subnets(port: u16) -> Vec { let port = if port == 0 { DEFAULT_PORT } else { port }; let mut targets: Vec = Vec::new(); for (ip, prefix) in local_ipv4_subnets() { targets.extend(hosts_in_subnet(ip, prefix)); } targets.sort(); targets.dedup(); if targets.is_empty() { return Vec::new(); } let (job_tx, job_rx) = mpsc::channel::(); let (hit_tx, hit_rx) = mpsc::channel::(); let workers = SCAN_WORKERS.min(targets.len()).max(1); let job_rx = std::sync::Arc::new(std::sync::Mutex::new(job_rx)); let mut handles = Vec::with_capacity(workers); for _ in 0..workers { let job_rx = std::sync::Arc::clone(&job_rx); let hit_tx = hit_tx.clone(); handles.push(thread::spawn(move || { loop { let ip = { let Ok(rx) = job_rx.lock() else { break; }; match rx.recv() { Ok(ip) => ip, Err(_) => break, } }; let host = ip.to_string(); if probe_host(&host, port, PROBE_TIMEOUT) { let _ = hit_tx.send(network_device(&host, port)); } } })); } drop(hit_tx); for ip in targets { let _ = job_tx.send(ip); } drop(job_tx); for h in handles { let _ = h.join(); } let mut out: Vec<_> = hit_rx.into_iter().collect(); out.sort_by(|a, b| a.display_name.cmp(&b.display_name)); out.dedup_by(|a, b| a.id == b.id); out } /// Merge validated cache hits with a fresh scan; refresh `last_seen` for survivors. pub fn merge_lan_devices( validated_cache: &[PrinterDevice], scanned: &[PrinterDevice], ) -> Vec { let mut out = Vec::new(); for d in validated_cache.iter().chain(scanned.iter()) { if !out.iter().any(|x: &PrinterDevice| x.id == d.id) { out.push(d.clone()); } } out.sort_by(|a, b| a.display_name.cmp(&b.display_name)); out } pub fn cache_entries_from_devices(devices: &[PrinterDevice]) -> Vec { let now = unix_now(); let mut entries = Vec::new(); for d in devices { if let PrinterTarget::Network { host, port } = &d.target { entries.push(LanPrinterCacheEntry { host: host.clone(), port: *port, last_seen_unix: now, }); } } entries.sort_by(|a, b| (&a.host, a.port).cmp(&(&b.host, b.port))); entries.dedup_by(|a, b| a.host == b.host && a.port == b.port); entries } /// Remember a successful network print in the durable LAN cache. pub fn remember_in_cache(cache: &mut Vec, host: &str, port: u16) { let port = if port == 0 { DEFAULT_PORT } else { port }; let now = unix_now(); if let Some(existing) = cache.iter_mut().find(|e| e.host == host && e.port == port) { existing.last_seen_unix = now; return; } cache.push(LanPrinterCacheEntry { host: host.to_string(), port, last_seen_unix: now, }); cache.sort_by(|a, b| (&a.host, a.port).cmp(&(&b.host, b.port))); } fn local_ipv4_subnets() -> Vec<(Ipv4Addr, u8)> { let mut out = Vec::new(); #[cfg(unix)] { out.extend(unix_ipv4_subnets()); } // Always include the default-route interface /24 when available. if let Some(ip) = primary_ipv4() { if !ip.is_loopback() && !is_link_local(ip) { out.push((ip, 24)); } } out.sort_by_key(|(ip, p)| (u32::from(*ip), *p)); out.dedup(); out } fn primary_ipv4() -> Option { let socket = UdpSocket::bind("0.0.0.0:0").ok()?; // No packets need to be sent; connect selects a route and local address. socket.connect("8.8.8.8:80").ok()?; match socket.local_addr().ok()?.ip() { IpAddr::V4(ip) => Some(ip), IpAddr::V6(_) => None, } } fn is_link_local(ip: Ipv4Addr) -> bool { ip.octets()[0] == 169 && ip.octets()[1] == 254 } fn hosts_in_subnet(ip: Ipv4Addr, prefix: u8) -> Vec { let prefix = prefix.min(30); let ip_u = u32::from(ip); let mask = if prefix == 0 { 0 } else { !0u32 << (32 - prefix) }; let network = ip_u & mask; let broadcast = network | !mask; let mut hosts = Vec::new(); // Skip network and broadcast addresses. let mut cur = network.saturating_add(1); while cur < broadcast { let host = Ipv4Addr::from(cur); if host != ip && !host.is_loopback() && !is_link_local(host) { hosts.push(host); } cur = cur.saturating_add(1); } hosts } #[cfg(unix)] fn unix_ipv4_subnets() -> Vec<(Ipv4Addr, u8)> { use std::ptr; let mut out = Vec::new(); unsafe { let mut ifap: *mut libc::ifaddrs = ptr::null_mut(); if libc::getifaddrs(&mut ifap) != 0 { return out; } let mut cursor = ifap; while !cursor.is_null() { let entry = &*cursor; if !entry.ifa_addr.is_null() && (*entry.ifa_addr).sa_family as i32 == libc::AF_INET && !entry.ifa_netmask.is_null() { let addr = &*(entry.ifa_addr as *const libc::sockaddr_in); let mask = &*(entry.ifa_netmask as *const libc::sockaddr_in); let ip = Ipv4Addr::from(u32::from_be(addr.sin_addr.s_addr)); let mask_u = u32::from_be(mask.sin_addr.s_addr); if !ip.is_loopback() && !is_link_local(ip) && mask_u != 0 { let prefix = mask_u.count_ones() as u8; // Cap scan size: only /24 or narrower (more specific). if (16..=30).contains(&prefix) { out.push((ip, prefix.min(24))); } } } cursor = entry.ifa_next; } libc::freeifaddrs(ifap); } out } /// Approximate wall time for a full /24 probe (for tests / UI hints). #[allow(dead_code)] pub fn estimate_scan_budget(host_count: usize) -> Duration { let batches = host_count.div_ceil(SCAN_WORKERS).max(1); PROBE_TIMEOUT * batches as u32 + Duration::from_millis(50) } #[cfg(test)] mod tests { use super::*; use std::net::TcpListener; use std::thread; #[test] fn parse_host_and_optional_port() { assert_eq!( parse_network_target("192.168.1.50"), Some(("192.168.1.50".into(), 9100)) ); assert_eq!( parse_network_target("192.168.1.50:9100"), Some(("192.168.1.50".into(), 9100)) ); assert_eq!( parse_network_target("tcp://pos.local:9101"), Some(("pos.local".into(), 9101)) ); assert_eq!(parse_network_target(""), None); assert_eq!(parse_network_target(" "), None); } #[test] fn probe_finds_local_listener() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); let accept = thread::spawn(move || { let _ = listener.accept(); }); assert!(probe_host("127.0.0.1", port, Duration::from_secs(1))); let _ = accept.join(); } #[test] fn network_transport_writes_to_listener() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); let accept = thread::spawn(move || { let (mut stream, _) = listener.accept().unwrap(); let mut buf = [0u8; 4]; use std::io::Read; stream.read_exact(&mut buf).unwrap(); buf }); let mut transport = NetworkTransport::open("127.0.0.1", port).unwrap(); transport.write_all(&[1, 2, 3, 4]).unwrap(); transport.flush().unwrap(); assert_eq!(accept.join().unwrap(), [1, 2, 3, 4]); } #[test] fn hosts_in_slash24_skips_network_and_broadcast() { let hosts = hosts_in_subnet(Ipv4Addr::new(192, 168, 1, 10), 24); assert!(!hosts.contains(&Ipv4Addr::new(192, 168, 1, 0))); assert!(!hosts.contains(&Ipv4Addr::new(192, 168, 1, 255))); assert!(!hosts.contains(&Ipv4Addr::new(192, 168, 1, 10))); // self assert!(hosts.contains(&Ipv4Addr::new(192, 168, 1, 1))); assert_eq!(hosts.len(), 253); } #[test] fn merge_dedupes_by_id() { let a = network_device("192.168.0.5", 9100); let b = network_device("192.168.0.5", 9100); let c = network_device("192.168.0.6", 9100); let merged = merge_lan_devices(&[a.clone()], &[b, c.clone()]); assert_eq!(merged.len(), 2); assert!(merged.iter().any(|d| d.id == a.id)); assert!(merged.iter().any(|d| d.id == c.id)); } #[test] fn cache_roundtrip_helpers() { let devices = vec![network_device("10.0.0.8", 9100)]; let entries = cache_entries_from_devices(&devices); assert_eq!(entries.len(), 1); assert_eq!(entries[0].host, "10.0.0.8"); let mut cache = entries; remember_in_cache(&mut cache, "10.0.0.9", 9100); assert_eq!(cache.len(), 2); remember_in_cache(&mut cache, "10.0.0.8", 9100); assert_eq!(cache.len(), 2); } #[test] fn estimate_scan_budget_is_finite() { assert!(estimate_scan_budget(254) > Duration::from_millis(0)); } }