| 1 | //! Raw ESC/POS over TCP (JetDirect / port 9100). No CUPS/IPP.
|
| 2 |
|
| 3 | use std::io::{self, Write};
|
| 4 | use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream, UdpSocket};
|
| 5 | use std::sync::mpsc;
|
| 6 | use std::thread;
|
| 7 | use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
| 8 |
|
| 9 | use super::{PrintError, PrinterDevice, PrinterTarget, PrinterTransport};
|
| 10 |
|
| 11 | /// Default raw ESC/POS TCP port (Epson / Star / most thermal POS).
|
| 12 | pub const DEFAULT_PORT: u16 = 9100;
|
| 13 |
|
| 14 | /// Connect timeout when opening for print.
|
| 15 | pub const PRINT_CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
|
| 16 |
|
| 17 | /// Short connect timeout used while probing the LAN.
|
| 18 | pub const PROBE_TIMEOUT: Duration = Duration::from_millis(250);
|
| 19 |
|
| 20 | /// How many probe workers to run in parallel during a subnet scan.
|
| 21 | const SCAN_WORKERS: usize = 64;
|
| 22 |
|
| 23 | pub struct NetworkTransport {
|
| 24 | stream: TcpStream,
|
| 25 | }
|
| 26 |
|
| 27 | impl NetworkTransport {
|
| 28 | pub fn open(host: &str, port: u16) -> Result<Self, PrintError> {
|
| 29 | let addr = resolve_socket_addr(host, port)?;
|
| 30 | let stream = TcpStream::connect_timeout(&addr, PRINT_CONNECT_TIMEOUT).map_err(|e| {
|
| 31 | PrintError::Open(format!("TCP {host}:{port}: {e}"))
|
| 32 | })?;
|
| 33 | let _ = stream.set_nodelay(true);
|
| 34 | let _ = stream.set_write_timeout(Some(Duration::from_secs(10)));
|
| 35 | Ok(Self { stream })
|
| 36 | }
|
| 37 | }
|
| 38 |
|
| 39 | impl PrinterTransport for NetworkTransport {
|
| 40 | fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
|
| 41 | self.stream.write_all(data)
|
| 42 | }
|
| 43 |
|
| 44 | fn flush(&mut self) -> io::Result<()> {
|
| 45 | self.stream.flush()
|
| 46 | }
|
| 47 | }
|
| 48 |
|
| 49 | /// Parse `host`, `host:port`, or `tcp://host:port` into (host, port).
|
| 50 | pub fn parse_network_target(raw: &str) -> Option<(String, u16)> {
|
| 51 | let s = raw.trim();
|
| 52 | if s.is_empty() {
|
| 53 | return None;
|
| 54 | }
|
| 55 | let s = s
|
| 56 | .strip_prefix("tcp://")
|
| 57 | .or_else(|| s.strip_prefix("TCP://"))
|
| 58 | .unwrap_or(s)
|
| 59 | .trim();
|
| 60 |
|
| 61 | // [ipv6]:port — not required for typical POS; skip for now.
|
| 62 | if s.starts_with('[') {
|
| 63 | return None;
|
| 64 | }
|
| 65 |
|
| 66 | if let Some((host, port_str)) = s.rsplit_once(':') {
|
| 67 | // Avoid treating IPv4 as host:port when there are multiple colons.
|
| 68 | if host.parse::<Ipv4Addr>().is_ok() || (!host.is_empty() && !host.contains(':')) {
|
| 69 | if let Ok(port) = port_str.parse::<u16>() {
|
| 70 | if port != 0 && !host.is_empty() {
|
| 71 | return Some((host.to_string(), port));
|
| 72 | }
|
| 73 | }
|
| 74 | }
|
| 75 | }
|
| 76 |
|
| 77 | // Bare hostname / IPv4 → default port.
|
| 78 | if s.parse::<Ipv4Addr>().is_ok() || (!s.is_empty() && !s.contains('/')) {
|
| 79 | return Some((s.to_string(), DEFAULT_PORT));
|
| 80 | }
|
| 81 | None
|
| 82 | }
|
| 83 |
|
| 84 | pub fn network_device(host: &str, port: u16) -> PrinterDevice {
|
| 85 | let port = if port == 0 { DEFAULT_PORT } else { port };
|
| 86 | PrinterDevice {
|
| 87 | id: format!("net:{host}:{port}"),
|
| 88 | display_name: format!("{host}:{port} — LAN (TCP)"),
|
| 89 | target: PrinterTarget::Network {
|
| 90 | host: host.to_string(),
|
| 91 | port,
|
| 92 | },
|
| 93 | }
|
| 94 | }
|
| 95 |
|
| 96 | pub fn probe_host(host: &str, port: u16, timeout: Duration) -> bool {
|
| 97 | let Ok(addr) = resolve_socket_addr(host, port) else {
|
| 98 | return false;
|
| 99 | };
|
| 100 | TcpStream::connect_timeout(&addr, timeout).is_ok()
|
| 101 | }
|
| 102 |
|
| 103 | fn resolve_socket_addr(host: &str, port: u16) -> Result<SocketAddr, PrintError> {
|
| 104 | if let Ok(ip) = host.parse::<IpAddr>() {
|
| 105 | return Ok(SocketAddr::new(ip, port));
|
| 106 | }
|
| 107 | // Hostname: use blocking resolve with first result.
|
| 108 | let mut addrs = std::net::ToSocketAddrs::to_socket_addrs(&(host, port)).map_err(|e| {
|
| 109 | PrintError::Open(format!("resolve {host}: {e}"))
|
| 110 | })?;
|
| 111 | addrs
|
| 112 | .next()
|
| 113 | .ok_or_else(|| PrintError::Open(format!("resolve {host}: no addresses")))
|
| 114 | }
|
| 115 |
|
| 116 | /// Cached LAN printer entry (persisted in `AppConfig`).
|
| 117 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
| 118 | pub struct LanPrinterCacheEntry {
|
| 119 | pub host: String,
|
| 120 | pub port: u16,
|
| 121 | #[serde(default)]
|
| 122 | pub last_seen_unix: u64,
|
| 123 | }
|
| 124 |
|
| 125 | impl LanPrinterCacheEntry {
|
| 126 | pub fn new(host: impl Into<String>, port: u16) -> Self {
|
| 127 | Self {
|
| 128 | host: host.into(),
|
| 129 | port: if port == 0 { DEFAULT_PORT } else { port },
|
| 130 | last_seen_unix: unix_now(),
|
| 131 | }
|
| 132 | }
|
| 133 | }
|
| 134 |
|
| 135 | fn unix_now() -> u64 {
|
| 136 | SystemTime::now()
|
| 137 | .duration_since(UNIX_EPOCH)
|
| 138 | .map(|d| d.as_secs())
|
| 139 | .unwrap_or(0)
|
| 140 | }
|
| 141 |
|
| 142 | /// Re-check cached hosts; return only those that still accept TCP on the port.
|
| 143 | pub fn validate_cache(cache: &[LanPrinterCacheEntry]) -> Vec<PrinterDevice> {
|
| 144 | let (tx, rx) = mpsc::channel();
|
| 145 | let mut handles = Vec::new();
|
| 146 | for entry in cache {
|
| 147 | let host = entry.host.clone();
|
| 148 | let port = if entry.port == 0 {
|
| 149 | DEFAULT_PORT
|
| 150 | } else {
|
| 151 | entry.port
|
| 152 | };
|
| 153 | let tx = tx.clone();
|
| 154 | handles.push(thread::spawn(move || {
|
| 155 | if probe_host(&host, port, PROBE_TIMEOUT) {
|
| 156 | let _ = tx.send(network_device(&host, port));
|
| 157 | }
|
| 158 | }));
|
| 159 | }
|
| 160 | drop(tx);
|
| 161 | for h in handles {
|
| 162 | let _ = h.join();
|
| 163 | }
|
| 164 | let mut out: Vec<_> = rx.into_iter().collect();
|
| 165 | out.sort_by(|a, b| a.display_name.cmp(&b.display_name));
|
| 166 | out.dedup_by(|a, b| a.id == b.id);
|
| 167 | out
|
| 168 | }
|
| 169 |
|
| 170 | /// Scan local IPv4 /24 subnets for open TCP `port`.
|
| 171 | pub fn scan_local_subnets(port: u16) -> Vec<PrinterDevice> {
|
| 172 | let port = if port == 0 { DEFAULT_PORT } else { port };
|
| 173 | let mut targets: Vec<Ipv4Addr> = Vec::new();
|
| 174 | for (ip, prefix) in local_ipv4_subnets() {
|
| 175 | targets.extend(hosts_in_subnet(ip, prefix));
|
| 176 | }
|
| 177 | targets.sort();
|
| 178 | targets.dedup();
|
| 179 |
|
| 180 | if targets.is_empty() {
|
| 181 | return Vec::new();
|
| 182 | }
|
| 183 |
|
| 184 | let (job_tx, job_rx) = mpsc::channel::<Ipv4Addr>();
|
| 185 | let (hit_tx, hit_rx) = mpsc::channel::<PrinterDevice>();
|
| 186 |
|
| 187 | let workers = SCAN_WORKERS.min(targets.len()).max(1);
|
| 188 | let job_rx = std::sync::Arc::new(std::sync::Mutex::new(job_rx));
|
| 189 | let mut handles = Vec::with_capacity(workers);
|
| 190 | for _ in 0..workers {
|
| 191 | let job_rx = std::sync::Arc::clone(&job_rx);
|
| 192 | let hit_tx = hit_tx.clone();
|
| 193 | handles.push(thread::spawn(move || {
|
| 194 | loop {
|
| 195 | let ip = {
|
| 196 | let Ok(rx) = job_rx.lock() else {
|
| 197 | break;
|
| 198 | };
|
| 199 | match rx.recv() {
|
| 200 | Ok(ip) => ip,
|
| 201 | Err(_) => break,
|
| 202 | }
|
| 203 | };
|
| 204 | let host = ip.to_string();
|
| 205 | if probe_host(&host, port, PROBE_TIMEOUT) {
|
| 206 | let _ = hit_tx.send(network_device(&host, port));
|
| 207 | }
|
| 208 | }
|
| 209 | }));
|
| 210 | }
|
| 211 | drop(hit_tx);
|
| 212 |
|
| 213 | for ip in targets {
|
| 214 | let _ = job_tx.send(ip);
|
| 215 | }
|
| 216 | drop(job_tx);
|
| 217 |
|
| 218 | for h in handles {
|
| 219 | let _ = h.join();
|
| 220 | }
|
| 221 |
|
| 222 | let mut out: Vec<_> = hit_rx.into_iter().collect();
|
| 223 | out.sort_by(|a, b| a.display_name.cmp(&b.display_name));
|
| 224 | out.dedup_by(|a, b| a.id == b.id);
|
| 225 | out
|
| 226 | }
|
| 227 |
|
| 228 | /// Merge validated cache hits with a fresh scan; refresh `last_seen` for survivors.
|
| 229 | pub fn merge_lan_devices(
|
| 230 | validated_cache: &[PrinterDevice],
|
| 231 | scanned: &[PrinterDevice],
|
| 232 | ) -> Vec<PrinterDevice> {
|
| 233 | let mut out = Vec::new();
|
| 234 | for d in validated_cache.iter().chain(scanned.iter()) {
|
| 235 | if !out.iter().any(|x: &PrinterDevice| x.id == d.id) {
|
| 236 | out.push(d.clone());
|
| 237 | }
|
| 238 | }
|
| 239 | out.sort_by(|a, b| a.display_name.cmp(&b.display_name));
|
| 240 | out
|
| 241 | }
|
| 242 |
|
| 243 | pub fn cache_entries_from_devices(devices: &[PrinterDevice]) -> Vec<LanPrinterCacheEntry> {
|
| 244 | let now = unix_now();
|
| 245 | let mut entries = Vec::new();
|
| 246 | for d in devices {
|
| 247 | if let PrinterTarget::Network { host, port } = &d.target {
|
| 248 | entries.push(LanPrinterCacheEntry {
|
| 249 | host: host.clone(),
|
| 250 | port: *port,
|
| 251 | last_seen_unix: now,
|
| 252 | });
|
| 253 | }
|
| 254 | }
|
| 255 | entries.sort_by(|a, b| (&a.host, a.port).cmp(&(&b.host, b.port)));
|
| 256 | entries.dedup_by(|a, b| a.host == b.host && a.port == b.port);
|
| 257 | entries
|
| 258 | }
|
| 259 |
|
| 260 | /// Remember a successful network print in the durable LAN cache.
|
| 261 | pub fn remember_in_cache(cache: &mut Vec<LanPrinterCacheEntry>, host: &str, port: u16) {
|
| 262 | let port = if port == 0 { DEFAULT_PORT } else { port };
|
| 263 | let now = unix_now();
|
| 264 | if let Some(existing) = cache.iter_mut().find(|e| e.host == host && e.port == port) {
|
| 265 | existing.last_seen_unix = now;
|
| 266 | return;
|
| 267 | }
|
| 268 | cache.push(LanPrinterCacheEntry {
|
| 269 | host: host.to_string(),
|
| 270 | port,
|
| 271 | last_seen_unix: now,
|
| 272 | });
|
| 273 | cache.sort_by(|a, b| (&a.host, a.port).cmp(&(&b.host, b.port)));
|
| 274 | }
|
| 275 |
|
| 276 | fn local_ipv4_subnets() -> Vec<(Ipv4Addr, u8)> {
|
| 277 | let mut out = Vec::new();
|
| 278 |
|
| 279 | #[cfg(unix)]
|
| 280 | {
|
| 281 | out.extend(unix_ipv4_subnets());
|
| 282 | }
|
| 283 |
|
| 284 | // Always include the default-route interface /24 when available.
|
| 285 | if let Some(ip) = primary_ipv4() {
|
| 286 | if !ip.is_loopback() && !is_link_local(ip) {
|
| 287 | out.push((ip, 24));
|
| 288 | }
|
| 289 | }
|
| 290 |
|
| 291 | out.sort_by_key(|(ip, p)| (u32::from(*ip), *p));
|
| 292 | out.dedup();
|
| 293 | out
|
| 294 | }
|
| 295 |
|
| 296 | fn primary_ipv4() -> Option<Ipv4Addr> {
|
| 297 | let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
|
| 298 | // No packets need to be sent; connect selects a route and local address.
|
| 299 | socket.connect("8.8.8.8:80").ok()?;
|
| 300 | match socket.local_addr().ok()?.ip() {
|
| 301 | IpAddr::V4(ip) => Some(ip),
|
| 302 | IpAddr::V6(_) => None,
|
| 303 | }
|
| 304 | }
|
| 305 |
|
| 306 | fn is_link_local(ip: Ipv4Addr) -> bool {
|
| 307 | ip.octets()[0] == 169 && ip.octets()[1] == 254
|
| 308 | }
|
| 309 |
|
| 310 | fn hosts_in_subnet(ip: Ipv4Addr, prefix: u8) -> Vec<Ipv4Addr> {
|
| 311 | let prefix = prefix.min(30);
|
| 312 | let ip_u = u32::from(ip);
|
| 313 | let mask = if prefix == 0 {
|
| 314 | 0
|
| 315 | } else {
|
| 316 | !0u32 << (32 - prefix)
|
| 317 | };
|
| 318 | let network = ip_u & mask;
|
| 319 | let broadcast = network | !mask;
|
| 320 | let mut hosts = Vec::new();
|
| 321 | // Skip network and broadcast addresses.
|
| 322 | let mut cur = network.saturating_add(1);
|
| 323 | while cur < broadcast {
|
| 324 | let host = Ipv4Addr::from(cur);
|
| 325 | if host != ip && !host.is_loopback() && !is_link_local(host) {
|
| 326 | hosts.push(host);
|
| 327 | }
|
| 328 | cur = cur.saturating_add(1);
|
| 329 | }
|
| 330 | hosts
|
| 331 | }
|
| 332 |
|
| 333 | #[cfg(unix)]
|
| 334 | fn unix_ipv4_subnets() -> Vec<(Ipv4Addr, u8)> {
|
| 335 | use std::ptr;
|
| 336 |
|
| 337 | let mut out = Vec::new();
|
| 338 | unsafe {
|
| 339 | let mut ifap: *mut libc::ifaddrs = ptr::null_mut();
|
| 340 | if libc::getifaddrs(&mut ifap) != 0 {
|
| 341 | return out;
|
| 342 | }
|
| 343 | let mut cursor = ifap;
|
| 344 | while !cursor.is_null() {
|
| 345 | let entry = &*cursor;
|
| 346 | if !entry.ifa_addr.is_null()
|
| 347 | && (*entry.ifa_addr).sa_family as i32 == libc::AF_INET
|
| 348 | && !entry.ifa_netmask.is_null()
|
| 349 | {
|
| 350 | let addr = &*(entry.ifa_addr as *const libc::sockaddr_in);
|
| 351 | let mask = &*(entry.ifa_netmask as *const libc::sockaddr_in);
|
| 352 | let ip = Ipv4Addr::from(u32::from_be(addr.sin_addr.s_addr));
|
| 353 | let mask_u = u32::from_be(mask.sin_addr.s_addr);
|
| 354 | if !ip.is_loopback() && !is_link_local(ip) && mask_u != 0 {
|
| 355 | let prefix = mask_u.count_ones() as u8;
|
| 356 | // Cap scan size: only /24 or narrower (more specific).
|
| 357 | if (16..=30).contains(&prefix) {
|
| 358 | out.push((ip, prefix.min(24)));
|
| 359 | }
|
| 360 | }
|
| 361 | }
|
| 362 | cursor = entry.ifa_next;
|
| 363 | }
|
| 364 | libc::freeifaddrs(ifap);
|
| 365 | }
|
| 366 | out
|
| 367 | }
|
| 368 |
|
| 369 | /// Approximate wall time for a full /24 probe (for tests / UI hints).
|
| 370 | #[allow(dead_code)]
|
| 371 | pub fn estimate_scan_budget(host_count: usize) -> Duration {
|
| 372 | let batches = host_count.div_ceil(SCAN_WORKERS).max(1);
|
| 373 | PROBE_TIMEOUT * batches as u32 + Duration::from_millis(50)
|
| 374 | }
|
| 375 |
|
| 376 | #[cfg(test)]
|
| 377 | mod tests {
|
| 378 | use super::*;
|
| 379 | use std::net::TcpListener;
|
| 380 | use std::thread;
|
| 381 |
|
| 382 | #[test]
|
| 383 | fn parse_host_and_optional_port() {
|
| 384 | assert_eq!(
|
| 385 | parse_network_target("192.168.1.50"),
|
| 386 | Some(("192.168.1.50".into(), 9100))
|
| 387 | );
|
| 388 | assert_eq!(
|
| 389 | parse_network_target("192.168.1.50:9100"),
|
| 390 | Some(("192.168.1.50".into(), 9100))
|
| 391 | );
|
| 392 | assert_eq!(
|
| 393 | parse_network_target("tcp://pos.local:9101"),
|
| 394 | Some(("pos.local".into(), 9101))
|
| 395 | );
|
| 396 | assert_eq!(parse_network_target(""), None);
|
| 397 | assert_eq!(parse_network_target(" "), None);
|
| 398 | }
|
| 399 |
|
| 400 | #[test]
|
| 401 | fn probe_finds_local_listener() {
|
| 402 | let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
| 403 | let port = listener.local_addr().unwrap().port();
|
| 404 | let accept = thread::spawn(move || {
|
| 405 | let _ = listener.accept();
|
| 406 | });
|
| 407 | assert!(probe_host("127.0.0.1", port, Duration::from_secs(1)));
|
| 408 | let _ = accept.join();
|
| 409 | }
|
| 410 |
|
| 411 | #[test]
|
| 412 | fn network_transport_writes_to_listener() {
|
| 413 | let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
| 414 | let port = listener.local_addr().unwrap().port();
|
| 415 | let accept = thread::spawn(move || {
|
| 416 | let (mut stream, _) = listener.accept().unwrap();
|
| 417 | let mut buf = [0u8; 4];
|
| 418 | use std::io::Read;
|
| 419 | stream.read_exact(&mut buf).unwrap();
|
| 420 | buf
|
| 421 | });
|
| 422 | let mut transport = NetworkTransport::open("127.0.0.1", port).unwrap();
|
| 423 | transport.write_all(&[1, 2, 3, 4]).unwrap();
|
| 424 | transport.flush().unwrap();
|
| 425 | assert_eq!(accept.join().unwrap(), [1, 2, 3, 4]);
|
| 426 | }
|
| 427 |
|
| 428 | #[test]
|
| 429 | fn hosts_in_slash24_skips_network_and_broadcast() {
|
| 430 | let hosts = hosts_in_subnet(Ipv4Addr::new(192, 168, 1, 10), 24);
|
| 431 | assert!(!hosts.contains(&Ipv4Addr::new(192, 168, 1, 0)));
|
| 432 | assert!(!hosts.contains(&Ipv4Addr::new(192, 168, 1, 255)));
|
| 433 | assert!(!hosts.contains(&Ipv4Addr::new(192, 168, 1, 10))); // self
|
| 434 | assert!(hosts.contains(&Ipv4Addr::new(192, 168, 1, 1)));
|
| 435 | assert_eq!(hosts.len(), 253);
|
| 436 | }
|
| 437 |
|
| 438 | #[test]
|
| 439 | fn merge_dedupes_by_id() {
|
| 440 | let a = network_device("192.168.0.5", 9100);
|
| 441 | let b = network_device("192.168.0.5", 9100);
|
| 442 | let c = network_device("192.168.0.6", 9100);
|
| 443 | let merged = merge_lan_devices(&[a.clone()], &[b, c.clone()]);
|
| 444 | assert_eq!(merged.len(), 2);
|
| 445 | assert!(merged.iter().any(|d| d.id == a.id));
|
| 446 | assert!(merged.iter().any(|d| d.id == c.id));
|
| 447 | }
|
| 448 |
|
| 449 | #[test]
|
| 450 | fn cache_roundtrip_helpers() {
|
| 451 | let devices = vec![network_device("10.0.0.8", 9100)];
|
| 452 | let entries = cache_entries_from_devices(&devices);
|
| 453 | assert_eq!(entries.len(), 1);
|
| 454 | assert_eq!(entries[0].host, "10.0.0.8");
|
| 455 | let mut cache = entries;
|
| 456 | remember_in_cache(&mut cache, "10.0.0.9", 9100);
|
| 457 | assert_eq!(cache.len(), 2);
|
| 458 | remember_in_cache(&mut cache, "10.0.0.8", 9100);
|
| 459 | assert_eq!(cache.len(), 2);
|
| 460 | }
|
| 461 |
|
| 462 | #[test]
|
| 463 | fn estimate_scan_budget_is_finite() {
|
| 464 | assert!(estimate_scan_budget(254) > Duration::from_millis(0));
|
| 465 | }
|
| 466 | }
|