Line data Source code
1 : import 'dart:async';
2 : import 'dart:io';
3 :
4 : import 'package:logging/logging.dart';
5 : import 'package:network_tools/network_tools.dart' as packages_page;
6 : import 'package:network_tools/src/database/drfit_database_service.dart';
7 : import 'package:network_tools/src/database/drift_database.dart';
8 : import 'package:network_tools/src/injection.dart';
9 : import 'package:network_tools/src/models/arp_data.dart';
10 : import 'package:network_tools/src/models/vendor.dart';
11 : import 'package:network_tools/src/repository/repository.dart';
12 : import 'package:network_tools/src/services/impls/host_scanner_service_impl.dart';
13 : import 'package:network_tools/src/services/impls/mdns_scanner_service_impl.dart';
14 : import 'package:network_tools/src/services/impls/port_scanner_service_impl.dart';
15 :
16 : /// Handler installed by [configureNetworkTools] when debugging is enabled.
17 : ///
18 : /// `Logger.root.onRecord` is a broadcast stream, so a listener that is never
19 : /// removed prints every record again each time the package is configured.
20 : StreamSubscription<LogRecord>? _debugLogSubscription;
21 :
22 : /// Releases what [configureNetworkTools] opened and forgets it.
23 : ///
24 : /// Without it the process outlives the app's work: the database connection owns
25 : /// a background isolate that only terminates once the connection is closed.
26 : /// Calling [configureNetworkTools] again afterwards works, so this is safe at the
27 : /// end of a CLI or a test, not just before the app exits.
28 1 : Future<void> closeNetworkTools() async {
29 : final AppDatabase? database = DriftDatabaseService.appDatabase;
30 : // The cache is dropped before the close is awaited so a scan that starts while
31 : // this is still running builds a fresh connection instead of writing to one
32 : // being torn down.
33 1 : DriftDatabaseService.reset();
34 : final StreamSubscription<LogRecord>? subscription = _debugLogSubscription;
35 : _debugLogSubscription = null;
36 0 : await subscription?.cancel();
37 1 : await database?.close();
38 : }
39 :
40 : /// Configures the network tools package for Dart native platforms.
41 : ///
42 : /// Sets up the database directory, enables debugging if specified, and initializes
43 : /// all required service implementations and vendor tables for network operations.
44 : ///
45 : /// Call this once before using any scanner, usually from `main` after resolving
46 : /// a writable [dbDirectory] such as the application documents directory.
47 : /// [enableDebugging] forwards package logs to [Logger.root] at [Level.FINE];
48 : /// [rebuildData] clears stale cached ARP entries before rebuilding the table.
49 : ///
50 : /// [buildVendorTable] should stay `false` in worker isolates. Decoding the
51 : /// vendor table costs a few milliseconds on first use, vendor lookups happen in
52 : /// the isolate that created the host objects, and host discovery only needs the
53 : /// ARP repository.
54 5 : Future<void> configureNetworkTools(
55 : String dbDirectory, {
56 : bool enableDebugging = false,
57 : bool rebuildData = false,
58 : bool buildVendorTable = true,
59 : }) async {
60 5 : final logger = Logger('configure_network_tools');
61 : packages_page.enableDebugging = enableDebugging;
62 : packages_page.dbDirectory = dbDirectory;
63 :
64 10 : final Directory newDirectory = Directory(packages_page.dbDirectory);
65 5 : await newDirectory.create(recursive: true);
66 15 : logger.fine('Directory created successfully: ${newDirectory.path}');
67 :
68 5 : if (packages_page.enableDebugging) {
69 4 : Logger.root.level = Level.FINE;
70 1 : await _debugLogSubscription?.cancel();
71 8 : _debugLogSubscription = Logger.root.onRecord.listen((record) {
72 6 : if (record.loggerName == logger.name) {
73 : // When debugging is enabled, log only the network_tools logger
74 : // ignore: avoid_print
75 1 : print(
76 7 : '${record.time.toLocal()}: ${record.level.name}: ${record.loggerName}: ${record.message}',
77 : );
78 : }
79 : });
80 : } else {
81 : // A reconfigure with debugging off must not leave the previous listener
82 : // printing.
83 1 : await _debugLogSubscription?.cancel();
84 : _debugLogSubscription = null;
85 : }
86 :
87 : // Setting dart native classes implementations
88 5 : HostScannerServiceImpl();
89 5 : PortScannerServiceImpl();
90 5 : MdnsScannerServiceImpl();
91 :
92 5 : await initializeNetworkTools(rebuildData, buildVendorTable: buildVendorTable);
93 : }
94 :
95 : /// Initializes the ARP table and vendor table map for network operations.
96 : ///
97 : /// Prefer [configureNetworkTools], which also registers the service instances
98 : /// and sets up logging. [buildVendorTable] is forwarded from there; pass
99 : /// `false` in worker isolates so the vendor CSV is not downloaded there.
100 5 : Future<void> initializeNetworkTools(
101 : bool rebuildData, {
102 : bool buildVendorTable = true,
103 : }) async {
104 : // Configuring twice has to work: `closeNetworkTools` releases the database but
105 : // leaves the service locator alone, and the generated registrations throw when
106 : // a type is already there. Unregistering instead is not an option because this
107 : // is the app's own `GetIt.instance`, which holds its services too.
108 10 : if (!getIt.isRegistered<Repository<ARPData>>()) {
109 5 : configureDependencies(Env.prod);
110 : }
111 : if (rebuildData) {
112 3 : await getIt<Repository<ARPData>>().clear();
113 : }
114 15 : await getIt<Repository<ARPData>>().build();
115 : if (buildVendorTable) {
116 9 : await getIt<Repository<Vendor>>().build();
117 : }
118 : }
|