Line data Source code
1 : import 'dart:async';
2 :
3 : import 'package:dart_ping/dart_ping.dart';
4 : import 'package:network_tools/network_tools.dart';
5 : import 'package:network_tools/src/injection.dart';
6 : import 'package:network_tools/src/network_tools_utils.dart';
7 : import 'package:network_tools/src/repository/repository.dart';
8 : import 'package:universal_io/io.dart';
9 :
10 : /// A device found on the network.
11 : ///
12 : /// Host details are resolved lazily and cached: [hostName], [deviceName],
13 : /// [mdnsInfo], [arpData], [vendor] and [getMacAddress] only perform their
14 : /// lookup when first accessed, unless discovery already filled them in.
15 : /// Implements [Comparable] ordering by host id ascending.
16 : class ActiveHost {
17 6 : ActiveHost({
18 : required this.internetAddress,
19 : this.openPorts = const [],
20 : String? macAddress,
21 : PingResponse? pingData,
22 : MdnsInfo? mdnsInfoVar,
23 : String? hostName,
24 : this.deviceType,
25 : }) {
26 6 : _macAddress = macAddress;
27 12 : final String tempAddress = internetAddress.address;
28 :
29 6 : if (tempAddress.contains('.')) {
30 10 : hostId = tempAddress.substring(
31 10 : tempAddress.lastIndexOf('.') + 1,
32 5 : tempAddress.length,
33 : );
34 2 : } else if (tempAddress.contains(':')) {
35 4 : hostId = tempAddress.substring(
36 4 : tempAddress.lastIndexOf(':') + 1,
37 2 : tempAddress.length,
38 : );
39 : } else {
40 0 : hostId = '-1';
41 : }
42 6 : _pingData = pingData;
43 :
44 : // Resolution (reverse DNS, ARP and vendor lookups) is intentionally lazy so
45 : // that discovery returns hosts as fast as the network scan allows. The
46 : // futures below are started on first access.
47 18 : weirdHostName = internetAddress.host;
48 :
49 6 : if (_isUsefulName(hostName)) {
50 2 : _hostName = Future.value(hostName);
51 : }
52 :
53 : if (mdnsInfoVar != null) {
54 4 : _mdnsInfo = Future.value(mdnsInfoVar);
55 : }
56 : }
57 5 : factory ActiveHost.buildWithAddress({
58 : required String address,
59 : String? macAddress,
60 : List<OpenPort> openPorts = const [],
61 : PingResponse? pingData,
62 : MdnsInfo? mdnsInfo,
63 : }) {
64 5 : final InternetAddress? internetAddressTemp = InternetAddress.tryParse(
65 : address,
66 : );
67 : if (internetAddressTemp == null) {
68 1 : throw 'Cant parse address $address to InternetAddress';
69 : }
70 5 : return ActiveHost(
71 : internetAddress: internetAddressTemp,
72 : macAddress: macAddress,
73 : openPorts: openPorts,
74 : pingData: pingData,
75 : mdnsInfoVar: mdnsInfo,
76 : );
77 : }
78 :
79 5 : factory ActiveHost.fromSendableActiveHost({
80 : required SendableActiveHost sendableActiveHost,
81 : String? macAddress,
82 : MdnsInfo? mdnsInfo,
83 : }) {
84 5 : final InternetAddress? internetAddressTemp = InternetAddress.tryParse(
85 5 : sendableActiveHost.address,
86 : );
87 : if (internetAddressTemp == null) {
88 2 : throw 'Cant parse address ${sendableActiveHost.address} to InternetAddress';
89 : }
90 5 : return ActiveHost(
91 : internetAddress: internetAddressTemp,
92 5 : macAddress: macAddress ?? sendableActiveHost.macAddress,
93 5 : openPorts: sendableActiveHost.openPorts,
94 5 : pingData: sendableActiveHost.pingData,
95 : mdnsInfoVar: mdnsInfo,
96 5 : hostName: sendableActiveHost.hostName,
97 5 : deviceType: sendableActiveHost.deviceType,
98 : );
99 : }
100 :
101 : static const generic = 'Generic Device';
102 :
103 : InternetAddress internetAddress;
104 :
105 : /// The device specific number in the ip address. In IPv4 numbers after the
106 : /// last dot, in IPv6 the numbers after the last colon
107 : late String hostId;
108 :
109 : Future<String?>? _hostName;
110 :
111 : /// Host name of the device, resolved through reverse DNS (PTR).
112 : ///
113 : /// The lookup starts lazily on first access with a short timeout and is
114 : /// cached. Discovery may already have resolved it, in which case this
115 : /// completes immediately. Returns null when the network has no reverse DNS
116 : /// or the address has no PTR record, and never returns the bare address.
117 : ///
118 : /// Not to be confused with [deviceName], which is a display name and does not
119 : /// follow any internet protocol property.
120 3 : Future<String?> get hostName => _hostName ??= setHostInfo();
121 : late String weirdHostName;
122 : late final PingResponse? _pingData;
123 :
124 : Future<MdnsInfo?>? _mdnsInfo;
125 :
126 : /// mDNS information for this device, when discovery found any.
127 : ///
128 : /// Resolved lazily on first access; currently mDNS results come from the
129 : /// mDNS scanner and are null for hosts found by the host scanner.
130 5 : Future<MdnsInfo?> get mdnsInfo => _mdnsInfo ??= setMdnsInfo();
131 :
132 : /// Attaches mDNS information discovered by a separate scan.
133 : ///
134 : /// This is used to merge results from [MdnsScannerService] into hosts found
135 : /// by [HostScannerService], so that device names can be resolved from mDNS
136 : /// advertisements when reverse DNS fails.
137 0 : void attachMdnsInfo(MdnsInfo info) {
138 0 : _mdnsInfo = Future.value(info);
139 : }
140 :
141 : Future<ARPData?>? _arpData;
142 :
143 : /// The neighbor table entry for this address, or null when unavailable.
144 : ///
145 : /// Only supported on Linux, macOS and Windows. Resolved lazily from the ARP
146 : /// repository unless discovery already attached the MAC address.
147 3 : Future<ARPData?> get arpData => _arpData ??= setARPData();
148 :
149 : Future<Vendor?>? _vendor;
150 :
151 : /// The vendor that owns this device's MAC prefix, or null when the MAC
152 : /// address or vendor table is unavailable. Resolved lazily.
153 3 : Future<Vendor?> get vendor => _vendor ??= setVendor();
154 :
155 : /// MAC address of the device, or null when it cannot be determined.
156 : ///
157 : /// Hosts found through the neighbor table already carry their MAC address,
158 : /// so this completes without another read on Linux, macOS and Windows.
159 : String? _macAddress;
160 1 : Future<String?> getMacAddress() async =>
161 3 : _macAddress ?? (await arpData)?.macAddress;
162 :
163 : /// List of all the open port of this device
164 : List<OpenPort> openPorts;
165 :
166 : /// Inferred device type based on open port patterns (e.g., "Router", "Printer").
167 : ///
168 : /// Determined during discovery by analyzing which common ports responded.
169 : /// Returns null when no TCP probe data is available (e.g., host found only via ping).
170 : final String? deviceType;
171 :
172 : Future<String>? _deviceName;
173 :
174 : /// A human-readable name for the device, suitable for display.
175 : ///
176 : /// Tries [hostName], then the mDNS name, then the name recorded in the
177 : /// neighbor table, and finally falls back to [generic]. Resolved lazily and
178 : /// cached, so this may complete immediately when discovery already resolved
179 : /// the name and otherwise performs the lookup on first access.
180 3 : Future<String> get deviceName => _deviceName ??= setDeviceName();
181 :
182 : /// The ICMP response recorded during discovery, or null when the host was
183 : /// found through the neighbor table without answering ping.
184 2 : PingResponse? get pingData => _pingData;
185 :
186 : /// Round-trip time of the discovery ping, or null without [pingData].
187 2 : Duration? get responseTime {
188 2 : final event = _pingData;
189 3 : if (event is PingResponse) return event.time;
190 : return null;
191 : }
192 :
193 : /// The device's IPv4 or IPv6 address as a string.
194 15 : String get address => internetAddress.address;
195 :
196 1 : static PingResponse? getPingData(String host) {
197 : const int timeoutInSeconds = 1;
198 : PingResponse? tempPingData;
199 :
200 1 : Ping(
201 : host,
202 : count: 1,
203 : timeout: timeoutInSeconds,
204 1 : forceCodepage: Platform.isWindows,
205 3 : ).stream.listen((Object? event) {
206 1 : final PingResponse? response = _extractPingResponse(event);
207 1 : if (response != null && response.time != null) {
208 : tempPingData = response;
209 : }
210 : });
211 : return tempPingData;
212 : }
213 :
214 1 : static PingResponse? _extractPingResponse(Object? event) {
215 1 : if (event is PingResponse) {
216 : return event;
217 : }
218 : if (event == null) {
219 : return null;
220 : }
221 :
222 : // dart_ping changed its stream payload type across versions.
223 : // Some versions emit PingSummary or other payloads instead of a response.
224 : try {
225 : final dynamic dynamicEvent = event;
226 : // ignore: avoid_dynamic_calls
227 1 : final Object? response = dynamicEvent.response;
228 0 : return response is PingResponse ? response : null;
229 : } catch (error) {
230 : return null;
231 : }
232 : }
233 :
234 : /// Maximum time to wait for a reverse DNS answer before giving up.
235 : static const Duration reverseLookupTimeout = Duration(seconds: 2);
236 :
237 : /// Try to find the host name of this device, if not exist host name will
238 : /// stay null
239 1 : Future<String?> setHostInfo() async {
240 : // For some reason when internetAddress.host get called before the reverse
241 : // there is weired value
242 3 : weirdHostName = internetAddress.host;
243 :
244 : // In the future if mdnsInfo is null it will execute a search
245 : // Currently the functionality is missing in dart multicast_dns package
246 : // https://github.com/flutter/flutter/issues/96755
247 :
248 : try {
249 3 : final InternetAddress resolved = await internetAddress.reverse().timeout(
250 : reverseLookupTimeout,
251 : );
252 1 : final String host = resolved.host;
253 : // Some platforms return the IP itself when no PTR record exists.
254 3 : if (host.isEmpty || host == address) {
255 : return null;
256 : }
257 1 : internetAddress = resolved;
258 : return host;
259 1 : } on TimeoutException {
260 0 : logger.fine('Reverse DNS lookup timed out for $address');
261 : } catch (e) {
262 1 : if (e is SocketException &&
263 1 : e.osError != null &&
264 3 : (e.osError!.message == 'Name or service not known')) {
265 : // Some devices does not have host name and the reverse search will just
266 : // throw exception.
267 : // We don't need to print this crash as it is by design.
268 : } else {
269 0 : logger.severe('Exception here: $e');
270 : }
271 : }
272 : return null;
273 : }
274 :
275 : /// Resolves every lazy detail of this host: neighbor table entry, device
276 : /// name, mDNS info and host name.
277 : ///
278 : /// Prefer awaiting the individual getters when only some details are needed.
279 1 : Future<void> resolveInfo() async {
280 1 : await arpData;
281 : // await vendor;
282 1 : await deviceName;
283 1 : await mdnsInfo;
284 1 : await hostName;
285 : }
286 :
287 1 : Future<ARPData?> setARPData() {
288 4 : return getIt<Repository<ARPData>>().entryFor(address);
289 : }
290 :
291 1 : Future<Vendor?> setVendor() async {
292 1 : final String? macAddress = await getMacAddress();
293 :
294 : return macAddress == null
295 : ? null
296 3 : : await getIt<Repository<Vendor>>().entryFor(macAddress);
297 : }
298 :
299 : /// Try to find the mdns name of this device, if not exist mdns name will
300 : /// be null
301 : /// TODO: search mdns name for each device
302 1 : Future<MdnsInfo?> setMdnsInfo() async {
303 : return null;
304 : }
305 :
306 : /// Set some kind of device name.
307 : /// Will try couple of names, if all are null will just return [generic]
308 1 : Future<String> setDeviceName() async {
309 1 : final String? hostNameTemp = await hostName;
310 1 : if (_isUsefulName(hostNameTemp)) {
311 : return hostNameTemp!;
312 : }
313 1 : final MdnsInfo? mdnsTemp = await mdnsInfo;
314 1 : final String? mdnsName = mdnsTemp?.getOnlyTheStartOfMdnsName();
315 1 : if (_isUsefulName(mdnsName)) {
316 : return mdnsName!;
317 : }
318 : // ARP tables on Linux and macOS usually contain the peer host name.
319 2 : final String? arpHostName = (await arpData)?.hostname;
320 1 : if (_isUsefulName(arpHostName)) {
321 : return arpHostName!;
322 : }
323 : return generic;
324 : }
325 :
326 6 : bool _isUsefulName(String? name) {
327 2 : if (name == null || name.isEmpty || name == '?') {
328 : return false;
329 : }
330 2 : return name != address;
331 : }
332 :
333 2 : @override
334 4 : int get hashCode => address.hashCode;
335 :
336 2 : @override
337 8 : bool operator ==(Object o) => o is ActiveHost && address == o.address;
338 :
339 1 : int compareTo(ActiveHost other) {
340 3 : return hostId.compareTo(other.hostId);
341 : }
342 :
343 2 : @override
344 : String toString() {
345 13 : return 'Address: $address, HostId: $hostId, Time: ${responseTime?.inMilliseconds}ms, port: ${openPorts.join(",")}';
346 : }
347 :
348 1 : Future<String> toStringFull() async {
349 11 : return 'Address: $address, MAC: ${(await arpData)?.macAddress}, HostId: $hostId, Vendor: ${(await vendor)?.vendorName} Time: ${responseTime?.inMilliseconds}ms, DeviceName: ${await deviceName}, HostName: ${await hostName}, MdnsInfo: ${await mdnsInfo}';
350 : }
351 : }
|