Line data Source code
1 : import 'dart:async';
2 : import 'dart:isolate';
3 : import 'dart:math';
4 :
5 : import 'package:dart_ping/dart_ping.dart';
6 : import 'package:network_tools/network_tools.dart';
7 : import 'package:network_tools/src/concurrency.dart';
8 : import 'package:network_tools/src/injection.dart';
9 : import 'package:network_tools/src/network_tools_utils.dart';
10 : import 'package:network_tools/src/repository/repository.dart';
11 : import 'package:universal_io/io.dart';
12 :
13 : /// Spawns the host scan isolate with its error and exit ports wired up.
14 3 : Future<Isolate> _spawnHostScanIsolate(
15 : void Function(SendPort) entryPoint,
16 : SendPort sendPort,
17 : SendPort errorPort,
18 : SendPort exitPort,
19 3 : ) => Isolate.spawn(entryPoint, sendPort, onError: errorPort, onExit: exitPort);
20 :
21 : /// Scans for all hosts in a subnet.
22 : class HostScannerServiceImpl extends HostScannerService {
23 7 : HostScannerServiceImpl({
24 : Future<Isolate> Function(
25 : void Function(SendPort) entryPoint,
26 : SendPort sendPort,
27 : SendPort errorPort,
28 : SendPort exitPort,
29 : )?
30 : spawnScanIsolate,
31 : }) : _spawnScanIsolate = spawnScanIsolate ?? _spawnHostScanIsolate;
32 :
33 : /// Spawns the isolate behind [getAllPingableDevicesAsync].
34 : ///
35 : /// Replaceable so tests can simulate an isolate that crashes or exits before
36 : /// the scan finishes.
37 : final Future<Isolate> Function(
38 : void Function(SendPort) entryPoint,
39 : SendPort sendPort,
40 : SendPort errorPort,
41 : SendPort exitPort,
42 : )
43 : _spawnScanIsolate;
44 :
45 : /// Upper bound for concurrent per-host verification and name lookups.
46 : /// Mobile platforms get lower concurrency to avoid overwhelming their network stacks.
47 3 : static int get hostLookupConcurrency {
48 6 : if (Platform.isAndroid || Platform.isIOS) {
49 : return 32;
50 : }
51 : return 128;
52 : }
53 :
54 : /// `ECONNREFUSED` values that prove a host answered with a RST, so the
55 : /// address is alive even though the port is closed.
56 : ///
57 : /// The code is platform specific — 111 on Linux/Android, 61 on Darwin
58 : /// (macOS and iOS), 10061 on Windows — so leaving Darwin out makes the TCP
59 : /// sweep blind to every closed-port host on iOS while Android still sees
60 : /// them.
61 : static const Set<int> refusalErrorCodes = <int>{111, 61, 10061};
62 :
63 : /// Scans for all hosts in a particular subnet (e.g., 192.168.1.0/24)
64 : /// Set maxHost to higher value if you are not getting results.
65 : /// It won't firstHostId again unless previous scan is completed due to heavy
66 : /// resource consumption.
67 : /// Use hostIds to limit subnet scan to hosts given.
68 : /// [resultsInAddressAscendingOrder] = false will return results faster but not in
69 : /// ascending order and without [progressCallback].
70 2 : @override
71 : Stream<ActiveHost> getAllPingableDevices(
72 : String subnet, {
73 : int firstHostId = HostScannerService.defaultFirstHostId,
74 : int lastHostId = HostScannerService.defaultLastHostId,
75 : List<int> hostIds = const [],
76 : int timeoutInSeconds = 2,
77 : ProgressCallback? progressCallback,
78 : bool resultsInAddressAscendingOrder = true,
79 : }) async* {
80 : // Start the mDNS scan in parallel with the host scan. The results are
81 : // merged by IP address so that devices like Android phones that don't
82 : // register reverse DNS records can still get their names from mDNS
83 : // advertisements.
84 2 : final Future<Map<String, MdnsInfo>> mdnsMapFuture = _buildMdnsMap();
85 :
86 2 : final stream = getAllSendablePingableDevices(
87 : subnet,
88 : firstHostId: firstHostId,
89 : lastHostId: lastHostId,
90 : hostIds: hostIds,
91 : timeoutInSeconds: timeoutInSeconds,
92 : progressCallback: progressCallback,
93 : resultsInAddressAscendingOrder: resultsInAddressAscendingOrder,
94 : );
95 :
96 : // Wait for the mDNS scan to complete before yielding hosts, so that every
97 : // host can be enriched with mDNS info if available.
98 : final Map<String, MdnsInfo> mdnsMap = await mdnsMapFuture;
99 :
100 4 : await for (final sendableActiveHost in stream) {
101 : // Host details (host name, ARP, vendor) resolve lazily, so they do not
102 : // delay discovery. Awaiting each host's resolveInfo() here used to
103 : // serialize a reverse DNS lookup per device.
104 2 : final host = ActiveHost.fromSendableActiveHost(
105 : sendableActiveHost: sendableActiveHost,
106 : );
107 : // Attach mDNS info if we found this host in the mDNS scan.
108 4 : final mdnsInfo = mdnsMap[host.address];
109 : if (mdnsInfo != null) {
110 0 : host.attachMdnsInfo(mdnsInfo);
111 : }
112 : yield host;
113 : }
114 : }
115 :
116 : /// Runs an mDNS scan and returns a map of IP address to [MdnsInfo].
117 : ///
118 : /// This is used to enrich hosts found by the regular scan with mDNS
119 : /// advertisements, so that devices like Android phones can get their names
120 : /// even when reverse DNS fails.
121 2 : Future<Map<String, MdnsInfo>> _buildMdnsMap() async {
122 : try {
123 3 : final mdnsHosts = await MdnsScannerService.instance.searchMdnsDevices();
124 1 : final map = <String, MdnsInfo>{};
125 1 : for (final host in mdnsHosts) {
126 0 : final mdnsInfo = await host.mdnsInfo;
127 : if (mdnsInfo != null) {
128 0 : map[host.address] = mdnsInfo;
129 : }
130 : }
131 : return map;
132 : } catch (e, stackTrace) {
133 2 : logger.warning(
134 1 : 'mDNS scan failed during host discovery: $e',
135 : e,
136 : stackTrace,
137 : );
138 1 : return {};
139 : }
140 : }
141 :
142 : /// Same as [getAllPingableDevices] but can be called or run inside isolate.
143 3 : @override
144 : Stream<SendableActiveHost> getAllSendablePingableDevices(
145 : String subnet, {
146 : int firstHostId = HostScannerService.defaultFirstHostId,
147 : int lastHostId = HostScannerService.defaultLastHostId,
148 : List<int> hostIds = const [],
149 : int timeoutInSeconds = 2,
150 : ProgressCallback? progressCallback,
151 : bool resultsInAddressAscendingOrder = true,
152 : }) async* {
153 3 : final int lastValidSubnet = validateAndGetLastValidSubnet(
154 : subnet,
155 : firstHostId,
156 : lastHostId,
157 : );
158 3 : final List<int> idsToScan = <int>[
159 6 : for (int i = firstHostId; i <= lastValidSubnet; i++)
160 8 : if (hostIds.isEmpty || hostIds.contains(i)) i,
161 : ];
162 3 : if (idsToScan.isEmpty) {
163 : return;
164 : }
165 :
166 : // Use TCP-connect sweep on all platforms for consistent results.
167 : // The ARP fast path was unreliable on some platforms (macOS) and caused
168 : // inconsistent device counts between mobile and desktop.
169 : // ARP is still used to enrich results with MAC addresses when available.
170 3 : yield* _yieldTCPConnectResults(
171 : subnet: subnet,
172 : idsToScan: idsToScan,
173 : firstHostId: firstHostId,
174 : lastValidSubnet: lastValidSubnet,
175 : timeoutInSeconds: timeoutInSeconds,
176 : progressCallback: progressCallback,
177 : resultsInAddressAscendingOrder: resultsInAddressAscendingOrder,
178 : );
179 : }
180 :
181 : /// TCP-connect sweep: no process spawns, works on all platforms.
182 : ///
183 : /// Tries to connect to common ports on each host. Connection-refused (see
184 : /// [refusalErrorCodes]) means the host is up but the port is closed; timeout
185 : /// or other errors mean the host is down.
186 : ///
187 : /// After TCP-connect completes, runs ICMP ping as a fallback for hosts that
188 : /// didn't respond to TCP. This ensures we find devices that block TCP but
189 : /// respond to ping (like some routers and IoT devices).
190 3 : Stream<SendableActiveHost> _yieldTCPConnectResults({
191 : required String subnet,
192 : required List<int> idsToScan,
193 : required int firstHostId,
194 : required int lastValidSubnet,
195 : required int timeoutInSeconds,
196 : required bool resultsInAddressAscendingOrder,
197 : ProgressCallback? progressCallback,
198 : }) async* {
199 6 : final stopwatch = Stopwatch()..start();
200 3 : final timeout = Duration(seconds: timeoutInSeconds);
201 : final StreamController<SendableActiveHost>? activeHostsController =
202 : resultsInAddressAscendingOrder
203 : ? null
204 1 : : StreamController<SendableActiveHost>();
205 :
206 6 : logger.info(
207 6 : 'TCP-connect sweep: starting scan of ${idsToScan.length} hosts',
208 : );
209 : // Report 0% immediately so the UI shows progress has started
210 1 : progressCallback?.call(0);
211 : int hostsFound = 0;
212 : final Set<int> foundHostIds = {};
213 :
214 : // Use bounded concurrency for TCP probes to avoid overwhelming mobile devices
215 6 : final tcpResults = mapConcurrently<int, SendableActiveHost?>(idsToScan, (
216 : int id,
217 : ) async {
218 3 : final host = await _probeHostViaTCP(
219 3 : '$subnet.$id',
220 : timeout,
221 : activeHostsController,
222 : );
223 : if (host != null) {
224 3 : hostsFound++;
225 3 : foundHostIds.add(id);
226 3 : final elapsed = stopwatch.elapsedMilliseconds;
227 6 : logger.info(
228 3 : 'TCP-connect: found $subnet.$id at ${elapsed}ms (total: $hostsFound)',
229 : );
230 : }
231 : return host;
232 3 : }, maxConcurrency: hostLookupConcurrency);
233 :
234 : if (!resultsInAddressAscendingOrder) {
235 : // Track progress for unordered mode
236 : int completedProbes = 0;
237 1 : final totalProbes = idsToScan.length;
238 :
239 : // Process TCP results as they complete and emit to stream
240 1 : unawaited(
241 : tcpResults
242 2 : .forEach((result) {
243 1 : completedProbes++;
244 1 : if (progressCallback != null && totalProbes > 0) {
245 : // TCP phase covers 0-95% since it finds almost all devices
246 2 : final tcpProgress = (completedProbes / totalProbes) * 95;
247 1 : progressCallback(tcpProgress);
248 : }
249 : })
250 1 : .then(
251 1 : (_) async {
252 : // After TCP-connect completes, run ICMP ping fallback for missing
253 : // hosts with bounded concurrency so Android is not overwhelmed.
254 : final missingHostIds = idsToScan
255 3 : .where((id) => !foundHostIds.contains(id))
256 1 : .toList();
257 1 : if (missingHostIds.isEmpty) {
258 : // No ping fallback needed, jump to 100%
259 : if (progressCallback != null) {
260 1 : progressCallback(100);
261 : }
262 1 : activeHostsController?.close();
263 : return;
264 : }
265 :
266 0 : logger.info(
267 0 : 'Ping fallback: probing ${missingHostIds.length} hosts',
268 : );
269 : int completedPings = 0;
270 0 : final totalPings = missingHostIds.length;
271 :
272 0 : final pingResults = mapConcurrently<int, SendableActiveHost?>(
273 : missingHostIds,
274 0 : (int id) async {
275 0 : final host = '$subnet.$id';
276 0 : final pingResult = await getHostFromPing(
277 : activeHostsController: activeHostsController,
278 : host: host,
279 : timeoutInSeconds: timeoutInSeconds,
280 : );
281 : if (pingResult != null) {
282 0 : logger.info('Ping fallback: found $host');
283 : }
284 0 : completedPings++;
285 0 : if (progressCallback != null && totalPings > 0) {
286 : // Ping fallback covers 95-100%
287 : final pingProgress =
288 0 : 95 + (completedPings / totalPings) * 5;
289 0 : progressCallback(pingProgress);
290 : }
291 : return pingResult;
292 : },
293 0 : maxConcurrency: hostLookupConcurrency,
294 : );
295 :
296 0 : await for (final _ in pingResults) {
297 : // drain the stream to completion
298 : }
299 0 : activeHostsController?.close();
300 0 : final elapsed = stopwatch.elapsedMilliseconds;
301 0 : logger.info(
302 0 : 'TCP-connect sweep completed: $hostsFound hosts found in ${elapsed}ms',
303 : );
304 : },
305 0 : onError: (Object _) async {
306 : final missingHostIds = idsToScan
307 0 : .where((id) => !foundHostIds.contains(id))
308 0 : .toList();
309 0 : if (missingHostIds.isEmpty) {
310 0 : activeHostsController?.close();
311 : return;
312 : }
313 :
314 0 : logger.info(
315 0 : 'Ping fallback: probing ${missingHostIds.length} hosts',
316 : );
317 : int completedPings = 0;
318 0 : final totalPings = missingHostIds.length;
319 :
320 0 : final pingResults = mapConcurrently<int, SendableActiveHost?>(
321 : missingHostIds,
322 0 : (int id) async {
323 0 : final host = '$subnet.$id';
324 0 : final pingResult = await getHostFromPing(
325 : activeHostsController: activeHostsController,
326 : host: host,
327 : timeoutInSeconds: timeoutInSeconds,
328 : );
329 : if (pingResult != null) {
330 0 : logger.info('Ping fallback: found $host');
331 : }
332 0 : completedPings++;
333 0 : if (progressCallback != null && totalPings > 0) {
334 : // Ping fallback covers 95-100%
335 : final pingProgress =
336 0 : 95 + (completedPings / totalPings) * 5;
337 0 : progressCallback(pingProgress);
338 : }
339 : return pingResult;
340 : },
341 0 : maxConcurrency: hostLookupConcurrency,
342 : );
343 :
344 0 : await for (final _ in pingResults) {
345 : // drain the stream to completion
346 : }
347 0 : activeHostsController?.close();
348 0 : final elapsed = stopwatch.elapsedMilliseconds;
349 0 : logger.info(
350 0 : 'TCP-connect sweep completed: $hostsFound hosts found in ${elapsed}ms',
351 : );
352 : },
353 : ),
354 : );
355 1 : yield* activeHostsController!.stream;
356 : return;
357 : }
358 :
359 : // Ordered mode: collect all TCP results, then yield in order
360 3 : final tcpResultsMap = <int, SendableActiveHost?>{};
361 : int tcpIndex = 0;
362 6 : await for (final concurrentResult in tcpResults) {
363 3 : final id = idsToScan[tcpIndex];
364 3 : tcpResultsMap[id] = concurrentResult.value;
365 2 : progressCallback?.call(_progressFor(id, firstHostId, lastValidSubnet));
366 3 : tcpIndex++;
367 : }
368 :
369 : // Yield TCP results in order
370 6 : for (final id in idsToScan) {
371 3 : final tempHost = tcpResultsMap[id];
372 : if (tempHost != null) {
373 : yield tempHost;
374 : }
375 : }
376 :
377 : // After TCP-connect completes, run ICMP ping fallback for missing hosts
378 : // with bounded concurrency.
379 : final missingHostIds = idsToScan
380 9 : .where((id) => !foundHostIds.contains(id))
381 3 : .toList();
382 3 : if (missingHostIds.isNotEmpty) {
383 8 : logger.info('Ping fallback: probing ${missingHostIds.length} hosts');
384 :
385 2 : final pingFutures = <int, Future<SendableActiveHost?>>{};
386 2 : final pingResults = mapConcurrently<int, SendableActiveHost?>(
387 : missingHostIds,
388 2 : (int id) {
389 2 : final host = '$subnet.$id';
390 2 : final future = getHostFromPing(
391 : activeHostsController: null,
392 : host: host,
393 : timeoutInSeconds: timeoutInSeconds,
394 : );
395 2 : pingFutures[id] = future;
396 : return future;
397 : },
398 2 : maxConcurrency: hostLookupConcurrency,
399 : );
400 :
401 : // Drain the concurrent stream to let all pings run
402 4 : await for (final _ in pingResults) {
403 : // results are collected in pingFutures
404 : }
405 :
406 : // Yield results in order
407 4 : for (final id in missingHostIds) {
408 2 : final pingResult = await pingFutures[id];
409 : if (pingResult != null) {
410 0 : progressCallback?.call(
411 0 : _progressFor(id, firstHostId, lastValidSubnet),
412 : );
413 3 : logger.info('Ping fallback: found $subnet.$id');
414 : yield pingResult;
415 : }
416 : }
417 : }
418 :
419 : // Ensure progress reaches 100% at the end
420 1 : progressCallback?.call(100);
421 :
422 3 : final elapsed = stopwatch.elapsedMilliseconds;
423 6 : logger.info(
424 3 : 'TCP-connect sweep completed (ordered): $hostsFound hosts found in ${elapsed}ms',
425 : );
426 : }
427 :
428 : /// Probes a host via TCP-connect to common ports.
429 : ///
430 : /// Tries multiple common ports in parallel. Returns a
431 : /// [SendableActiveHost] if the host is up (any connection succeeded or
432 : /// connection-refused), or null if the host is down (all ports timed out).
433 3 : Future<SendableActiveHost?> _probeHostViaTCP(
434 : String host,
435 : Duration timeout,
436 : StreamController<SendableActiveHost>? activeHostsController,
437 : ) async {
438 : // Try multiple common ports in parallel. If ANY responds, the host is up.
439 : // Includes web, shell, network service, printer, and Windows ports.
440 : const ports = [
441 : 21, // FTP (NAS, routers)
442 : 22, // SSH
443 : 23, // Telnet
444 : 53, // DNS
445 : 80, // HTTP
446 : 161, // SNMP
447 : 443, // HTTPS
448 : 445, // SMB (Windows file sharing)
449 : 631, // IPP (printers)
450 : 3389, // RDP (Windows remote desktop)
451 : 5900, // VNC
452 : 8080, // HTTP-alt
453 : 8443, // HTTPS-alt
454 : 9100, // JetDirect (network printers)
455 : ];
456 9 : final futures = ports.map((port) => _tryConnect(host, port, timeout));
457 3 : final results = await Future.wait(futures);
458 :
459 : // Collect all open ports
460 3 : final openPorts = <OpenPort>[];
461 9 : for (int i = 0; i < ports.length; i++) {
462 3 : if (results[i]) {
463 9 : openPorts.add(OpenPort(ports[i]));
464 : }
465 : }
466 :
467 : // If any port responded (success or connection-refused), host is up.
468 3 : final isUp = openPorts.isNotEmpty;
469 :
470 : if (isUp) {
471 6 : final respondedPort = openPorts.first.port;
472 9 : logger.fine('[TCP Probe] $host is UP (port $respondedPort responded)');
473 3 : final result = SendableActiveHost(
474 : host,
475 : openPorts: openPorts,
476 3 : deviceType: _inferDeviceType(openPorts),
477 : );
478 1 : if (activeHostsController != null && !activeHostsController.isClosed) {
479 1 : activeHostsController.add(result);
480 : }
481 : return result;
482 : }
483 :
484 4 : logger.fine(
485 6 : '[TCP Probe] $host is DOWN (all ${ports.length} ports timed out after ${timeout.inMilliseconds}ms)',
486 : );
487 : return null;
488 : }
489 :
490 : /// Infers device type based on open port patterns.
491 : ///
492 : /// Uses common port combinations to identify device types like routers,
493 : /// printers, Windows PCs, etc.
494 4 : String _inferDeviceType(List<OpenPort> openPorts) {
495 16 : final portNumbers = openPorts.map((p) => p.port).toSet();
496 :
497 : // Printer: IPP (631) or JetDirect (9100) - most specific
498 5 : if (portNumbers.contains(631) || portNumbers.contains(9100)) {
499 : return 'Printer';
500 : }
501 :
502 : // NAS: FTP (21) + SMB (445) - check before Windows PC
503 2 : if (portNumbers.contains(21) && portNumbers.contains(445)) {
504 : return 'NAS';
505 : }
506 :
507 : // Router/Gateway: DNS (53) + typically SNMP (161) or multiple web ports
508 1 : if (portNumbers.contains(53) &&
509 1 : (portNumbers.contains(161) ||
510 1 : portNumbers.contains(80) ||
511 1 : portNumbers.contains(443) ||
512 1 : portNumbers.contains(8080) ||
513 1 : portNumbers.contains(8443))) {
514 : return 'Router';
515 : }
516 :
517 : // Generic server: SSH (22) + both HTTP and HTTPS (3+ ports total)
518 1 : if (portNumbers.contains(22) &&
519 1 : portNumbers.contains(80) &&
520 1 : portNumbers.contains(443)) {
521 : return 'Server';
522 : }
523 :
524 : // Linux/Unix server: SSH (22) + web services (HTTP or HTTPS, not both)
525 1 : if (portNumbers.contains(22) &&
526 1 : (portNumbers.contains(80) ||
527 1 : portNumbers.contains(443) ||
528 1 : portNumbers.contains(8080))) {
529 : return 'Linux Server';
530 : }
531 :
532 : // Windows PC: SMB (445) and/or RDP (3389) - after NAS check
533 2 : if (portNumbers.contains(445) || portNumbers.contains(3389)) {
534 : return 'Windows PC';
535 : }
536 :
537 : // Device with only SSH
538 3 : if (portNumbers.contains(22) && portNumbers.length == 1) {
539 : return 'Linux/Unix Device';
540 : }
541 :
542 : // Web Device: HTTP + HTTPS specifically (2 ports)
543 1 : if (portNumbers.contains(80) &&
544 1 : portNumbers.contains(443) &&
545 2 : portNumbers.length == 2) {
546 : return 'Web Device';
547 : }
548 :
549 : // IoT device: limited ports (1-2), often just HTTP or HTTP-alt
550 2 : if (portNumbers.length <= 2 &&
551 1 : (portNumbers.contains(80) ||
552 1 : portNumbers.contains(443) ||
553 1 : portNumbers.contains(8080))) {
554 : return 'IoT Device';
555 : }
556 :
557 : // VNC-only device (remote display/management)
558 3 : if (portNumbers.contains(5900) && portNumbers.length == 1) {
559 : return 'Remote Display';
560 : }
561 :
562 : return 'Unknown Device';
563 : }
564 :
565 : /// Tries to connect to a specific port. Returns true if the host responded
566 : /// (connection succeeded or connection-refused), false if timed out.
567 3 : Future<bool> _tryConnect(String host, int port, Duration timeout) async {
568 : try {
569 : // The deadline has to be an argument to `connect`, not `Future.timeout` on
570 : // the returned future: abandoning the future leaves the pending socket
571 : // open with nothing left to close it. Every timed-out probe then holds a
572 : // descriptor for the life of the isolate, so a whole-subnet sweep keeps
573 : // the VM running after the scan finishes and accumulates across repeated
574 : // scans. `destroy()` rather than `close()` because a probe never reads,
575 : // and a half-closed socket to a host that keeps the connection open holds
576 : // a descriptor the same way.
577 3 : final socket = await Socket.connect(host, port, timeout: timeout);
578 3 : socket.destroy();
579 : return true; // Port open
580 3 : } on SocketException catch (e) {
581 : // A refusal means the host answered, so it is up even with the port
582 : // closed. See [refusalErrorCodes] for the per-platform codes.
583 9 : return refusalErrorCodes.contains(e.osError?.errorCode);
584 0 : } on TimeoutException {
585 : return false; // Host down or port filtered
586 : } catch (e) {
587 : return false;
588 : }
589 : }
590 :
591 1 : double _progressFor(int hostId, int firstHostId, int lastValidSubnet) {
592 1 : final int span = lastValidSubnet - firstHostId;
593 1 : if (span <= 0) {
594 : return 100;
595 : }
596 3 : return (hostId - firstHostId) * 100 / span;
597 : }
598 :
599 2 : static PingResponse? _extractPingResponse(Object? event) {
600 2 : if (event is PingResponse) {
601 : return event;
602 : }
603 : if (event == null) {
604 : return null;
605 : }
606 :
607 : // dart_ping changed its stream payload type across versions.
608 : // Some versions emit PingSummary or other payloads instead of a response.
609 : try {
610 : final dynamic dynamicEvent = event;
611 : // ignore: avoid_dynamic_calls
612 2 : final Object? response = dynamicEvent.response;
613 0 : return response is PingResponse ? response : null;
614 : } catch (error) {
615 : return null;
616 : }
617 : }
618 :
619 2 : Future<PingResponse?> _pingHost(String host, int timeoutInSeconds) async {
620 : try {
621 4 : await for (final Object? event in Ping(
622 : host,
623 : count: 1,
624 : timeout: timeoutInSeconds,
625 2 : forceCodepage: Platform.isWindows,
626 4 : ).stream) {
627 2 : final PingResponse? pingResponse = _extractPingResponse(event);
628 0 : if (pingResponse != null && pingResponse.time != null) {
629 : return pingResponse;
630 : }
631 : }
632 : } catch (error, stackTrace) {
633 : // A failing ping for one host must not abort the whole subnet scan.
634 3 : logger.warning("Ping failed for $host: $error", error, stackTrace);
635 : }
636 : return null;
637 : }
638 :
639 2 : Future<SendableActiveHost?> getHostFromPing({
640 : required String host,
641 : required StreamController<SendableActiveHost>? activeHostsController,
642 : int timeoutInSeconds = 2,
643 : }) async {
644 : SendableActiveHost? tempSendableActivateHost;
645 :
646 2 : final PingResponse? pingResponse = await _pingHost(host, timeoutInSeconds);
647 : if (pingResponse != null) {
648 : // Check if ping succeeded
649 0 : logger.fine("Pingable device found: $host");
650 0 : tempSendableActivateHost = SendableActiveHost(
651 : host,
652 : pingData: pingResponse,
653 : );
654 : } else {
655 6 : logger.fine("Non pingable device found: $host");
656 : // Check if it's there in arp table
657 : try {
658 6 : final data = await getIt<Repository<ARPData>>().entryFor(host);
659 : if (data != null) {
660 3 : logger.fine("Successfully fetched arp entry for $host as $data");
661 1 : tempSendableActivateHost = SendableActiveHost(
662 : host,
663 1 : macAddress: data.macAddress,
664 : );
665 : } else {
666 6 : logger.fine("Problem in fetching arp entry for $host");
667 : }
668 : } catch (error, stackTrace) {
669 2 : logger.warning(
670 1 : "Failed to fetch arp entry for $host: $error",
671 : error,
672 : stackTrace,
673 : );
674 : }
675 : }
676 :
677 : if (tempSendableActivateHost != null) {
678 3 : logger.fine("Successfully added to result $host");
679 0 : if (activeHostsController != null && !activeHostsController.isClosed) {
680 0 : activeHostsController.add(tempSendableActivateHost);
681 : }
682 : }
683 :
684 : return tempSendableActivateHost;
685 : }
686 :
687 5 : @override
688 : int validateAndGetLastValidSubnet(
689 : String subnet,
690 : int firstHostId,
691 : int lastHostId,
692 : ) {
693 5 : final int maxEnd = maxHost;
694 5 : if (firstHostId > lastHostId ||
695 5 : firstHostId < HostScannerService.defaultFirstHostId ||
696 5 : lastHostId < HostScannerService.defaultFirstHostId ||
697 5 : firstHostId > maxEnd ||
698 5 : lastHostId > maxEnd) {
699 : throw 'Invalid subnet range or firstHostId < lastHostId is not true';
700 : }
701 5 : return min(lastHostId, maxEnd);
702 : }
703 :
704 : /// Works same as [getAllPingableDevices] but does everything inside
705 : /// isolate out of the box.
706 3 : @override
707 : Stream<ActiveHost> getAllPingableDevicesAsync(
708 : String subnet, {
709 : int firstHostId = HostScannerService.defaultFirstHostId,
710 : int lastHostId = HostScannerService.defaultLastHostId,
711 : List<int> hostIds = const [],
712 : int timeoutInSeconds = 2,
713 : ProgressCallback? progressCallback,
714 : bool resultsInAddressAscendingOrder = true,
715 : }) async* {
716 3 : final int lastValidSubnet = validateAndGetLastValidSubnet(
717 : subnet,
718 : firstHostId,
719 : lastHostId,
720 : );
721 : // The whole scan happens in a single isolate. Previously the range was
722 : // split into 51-host chunks, which meant spawning up to five isolates and
723 : // running configureNetworkTools (database setup) in each of them.
724 9 : logger.fine('Scanning from $firstHostId to $lastValidSubnet');
725 :
726 3 : final receivePort = ReceivePort();
727 3 : final errorPort = ReceivePort();
728 3 : final exitPort = ReceivePort();
729 : // An isolate that dies before sending 'Done' would otherwise leave this
730 : // stream waiting forever, so both failure channels feed the message stream.
731 4 : final errorSubscription = errorPort.listen((dynamic error) {
732 3 : receivePort.sendPort.send(<Object?>['runtimeError', error]);
733 : });
734 4 : final exitSubscription = exitPort.listen((dynamic _) {
735 3 : receivePort.sendPort.send(<Object?>['runtimeError', 'isolate exited']);
736 : });
737 : Isolate? isolate;
738 :
739 : try {
740 6 : isolate = await _spawnScanIsolate(
741 : _startSearchingDevices,
742 3 : receivePort.sendPort,
743 3 : errorPort.sendPort,
744 3 : exitPort.sendPort,
745 : );
746 :
747 6 : await for (final message in receivePort) {
748 3 : if (message is SendPort) {
749 6 : message.send(<String>[
750 : subnet,
751 3 : firstHostId.toString(),
752 3 : lastValidSubnet.toString(),
753 3 : timeoutInSeconds.toString(),
754 3 : resultsInAddressAscendingOrder.toString(),
755 3 : dbDirectory,
756 6 : enableDebugging.toString(),
757 3 : hostIds.join(','),
758 : ]);
759 3 : } else if (message is SendableActiveHost) {
760 2 : final activeHostFound = ActiveHost.fromSendableActiveHost(
761 : sendableActiveHost: message,
762 : );
763 4 : final j = int.tryParse(activeHostFound.hostId) ?? firstHostId;
764 2 : progressCallback?.call(_progressFor(j, firstHostId, lastValidSubnet));
765 : yield activeHostFound;
766 5 : } else if (message is List && message.first == 'runtimeError') {
767 3 : throw Exception('Host scan isolate failed: ${message[1]}');
768 6 : } else if (message is String && message == 'Done') {
769 : // The isolate sends one message per host, so the scan can finish on
770 : // host ids below 254 without the last host reporting 100.
771 1 : progressCallback?.call(100);
772 : break;
773 2 : } else if (message is String && message.startsWith('Error:')) {
774 1 : throw Exception(
775 3 : 'Host scan isolate failed: ${message.substring(6).trim()}',
776 : );
777 : }
778 : }
779 : } finally {
780 : // Also runs when the consumer cancels the stream early.
781 3 : await errorSubscription.cancel();
782 3 : await exitSubscription.cancel();
783 3 : errorPort.close();
784 3 : exitPort.close();
785 3 : isolate?.kill();
786 3 : receivePort.close();
787 : }
788 : }
789 :
790 : /// Will search devices in the network inside new isolate
791 3 : @pragma('vm:entry-point')
792 : static Future<void> _startSearchingDevices(SendPort sendPort) async {
793 3 : final port = ReceivePort();
794 6 : sendPort.send(port.sendPort);
795 :
796 6 : await for (final message in port) {
797 3 : if (message is List<String>) {
798 : try {
799 3 : final String subnetIsolate = message[0];
800 6 : final int firstSubnetIsolate = int.parse(message[1]);
801 6 : final int lastSubnetIsolate = int.parse(message[2]);
802 6 : final int timeoutInSeconds = int.parse(message[3]);
803 6 : final bool resultsInAddressAscendingOrder = message[4] == "true";
804 3 : final String dbDirectory = message[5];
805 6 : final bool enableDebugging = message[6] == "true";
806 3 : final String joinedIds = message[7];
807 : final List<int> hostIds = joinedIds
808 3 : .split(',')
809 9 : .where((e) => e.isNotEmpty)
810 3 : .map(int.parse)
811 3 : .toList();
812 : // Configure again. The vendor table is skipped here: building it can
813 : // trigger a multi-second first-use download, and vendor lookups run in
814 : // the isolate that receives the hosts, not in this one.
815 3 : await configureNetworkTools(
816 : dbDirectory,
817 : enableDebugging: enableDebugging,
818 : buildVendorTable: false,
819 : );
820 :
821 : /// Will contain all the hosts that got discovered in the network, will
822 : /// be use inorder to cancel on dispose of the page.
823 : final Stream<SendableActiveHost> hostsDiscoveredInNetwork =
824 4 : HostScannerService.instance.getAllSendablePingableDevices(
825 : subnetIsolate,
826 : firstHostId: firstSubnetIsolate,
827 : lastHostId: lastSubnetIsolate,
828 : hostIds: hostIds,
829 : timeoutInSeconds: timeoutInSeconds,
830 : resultsInAddressAscendingOrder: resultsInAddressAscendingOrder,
831 : );
832 :
833 2 : await for (final SendableActiveHost activeHostFound
834 2 : in hostsDiscoveredInNetwork) {
835 2 : sendPort.send(activeHostFound);
836 : }
837 2 : sendPort.send('Done');
838 : } catch (error) {
839 2 : sendPort.send('Error: $error');
840 : }
841 : }
842 : }
843 : }
844 :
845 : /// Scans for all hosts that have the specific port that was given.
846 : /// [resultsInAddressAscendingOrder] = false will return results faster but
847 : /// not in ascending order.
848 : /// [maxConcurrency] limits how many hosts are probed at the same time.
849 3 : @override
850 : Stream<ActiveHost> scanDevicesForSinglePort(
851 : String subnet,
852 : int port, {
853 : int firstHostId = HostScannerService.defaultFirstHostId,
854 : int lastHostId = HostScannerService.defaultLastHostId,
855 : Duration timeout = const Duration(milliseconds: 2000),
856 : ProgressCallback? progressCallback,
857 : bool resultsInAddressAscendingOrder = true,
858 : int maxConcurrency = PortScannerService.defaultMaxConcurrency,
859 : }) async* {
860 3 : final int lastValidSubnet = validateAndGetLastValidSubnet(
861 : subnet,
862 : firstHostId,
863 : lastHostId,
864 : );
865 3 : final List<int> hostIds = <int>[
866 9 : for (int i = firstHostId; i <= lastValidSubnet; i++) i,
867 : ];
868 3 : if (hostIds.isEmpty) {
869 : return;
870 : }
871 :
872 : // Bound the number of concurrent connections so a /24 scan does not open a
873 : // socket for every host at once.
874 : final Stream<ConcurrentResult<ActiveHost>> results =
875 3 : mapConcurrently<int, ActiveHost>(
876 : hostIds,
877 9 : (int id) => PortScannerService.instance.connectToPort(
878 3 : address: '$subnet.$id',
879 : port: port,
880 : timeout: timeout,
881 : ),
882 : maxConcurrency: maxConcurrency,
883 3 : onCompleted: (int completed) =>
884 4 : progressCallback?.call(completed * 100 / hostIds.length),
885 : );
886 :
887 : if (!resultsInAddressAscendingOrder) {
888 4 : await for (final ConcurrentResult<ActiveHost> result in results) {
889 : final ActiveHost? activeHost = result.value;
890 : if (activeHost != null) {
891 : yield activeHost;
892 : }
893 : }
894 : return;
895 : }
896 :
897 : // Keep the ascending-order contract even though connections finish out of
898 : // order by buffering results until every earlier host has been emitted.
899 3 : final Map<int, ActiveHost?> pending = <int, ActiveHost?>{};
900 : int nextIndex = 0;
901 6 : await for (final ConcurrentResult<ActiveHost> result in results) {
902 3 : pending[result.index] = result.value;
903 3 : while (pending.containsKey(nextIndex)) {
904 3 : final ActiveHost? activeHost = pending.remove(nextIndex);
905 3 : nextIndex++;
906 : if (activeHost != null) {
907 : yield activeHost;
908 : }
909 : }
910 : }
911 : }
912 :
913 : /// Defines total number of subnets in class A network
914 : final classASubnets = 16777216;
915 :
916 : /// Defines total number of subnets in class B network
917 : final classBSubnets = 65536;
918 :
919 : /// Defines total number of subnets in class C network
920 : final classCSubnets = 256;
921 :
922 : /// Minimum value of first octet in IPv4 address used by getMaxHost
923 : final int minNetworkId = 1;
924 :
925 : /// Maximum value of first octect in IPv4 address used by getMaxHost
926 : final int maxNetworkId = 223;
927 :
928 : /// returns the max number of hosts a subnet can have excluding network Id and broadcast Id
929 1 : @Deprecated(
930 : "Implementation is wrong, since we only append in last octet, max host can only be 254. Use maxHost getter",
931 : )
932 : int getMaxHost(String subnet) {
933 1 : if (subnet.isEmpty) {
934 1 : throw ArgumentError('Invalid subnet address, address can not be empty.');
935 : }
936 1 : final List<String> firstOctetStr = subnet.split('.');
937 1 : if (firstOctetStr.isEmpty) {
938 0 : throw ArgumentError(
939 : 'Invalid subnet address, address should be in IPv4 format x.x.x',
940 : );
941 : }
942 :
943 2 : final int firstOctet = int.parse(firstOctetStr[0]);
944 :
945 3 : if (firstOctet >= minNetworkId && firstOctet < 128) {
946 1 : return classASubnets;
947 2 : } else if (firstOctet >= 128 && firstOctet < 192) {
948 1 : return classBSubnets;
949 3 : } else if (firstOctet >= 192 && firstOctet <= maxNetworkId) {
950 1 : return classCSubnets;
951 : }
952 : // Out of range for first octet
953 1 : throw RangeError.range(
954 : firstOctet,
955 1 : minNetworkId,
956 1 : maxNetworkId,
957 : 'subnet',
958 : 'Out of range for first octet',
959 : );
960 : }
961 :
962 5 : int get maxHost => HostScannerService.defaultLastHostId;
963 :
964 : /// Test-only accessor for device type inference logic.
965 1 : String testInferDeviceType(List<OpenPort> openPorts) =>
966 1 : _inferDeviceType(openPorts);
967 : }
|