Line data Source code
1 : import 'dart:async';
2 : import 'dart:isolate';
3 :
4 : import 'package:network_tools/network_tools.dart';
5 : import 'package:network_tools/src/concurrency.dart';
6 : import 'package:universal_io/io.dart';
7 :
8 : /// Spawns the port scan isolate with its error and exit ports wired up.
9 3 : Future<Isolate> _spawnPortScanIsolate(
10 : void Function(SendPort) entryPoint,
11 : SendPort sendPort,
12 : SendPort errorPort,
13 : SendPort exitPort,
14 3 : ) => Isolate.spawn(entryPoint, sendPort, onError: errorPort, onExit: exitPort);
15 :
16 : /// Scans open port for a target Address or domain.
17 : class PortScannerServiceImpl extends PortScannerService {
18 7 : PortScannerServiceImpl({
19 : Future<Isolate> Function(
20 : void Function(SendPort) entryPoint,
21 : SendPort sendPort,
22 : SendPort errorPort,
23 : SendPort exitPort,
24 : )?
25 : spawnScanIsolate,
26 : }) : _spawnScanIsolate = spawnScanIsolate ?? _spawnPortScanIsolate;
27 :
28 : /// Spawns the isolate behind [customDiscover] when `async` is true.
29 : ///
30 : /// Replaceable so tests can simulate an isolate that crashes or exits before
31 : /// the scan finishes.
32 : final Future<Isolate> Function(
33 : void Function(SendPort) entryPoint,
34 : SendPort sendPort,
35 : SendPort errorPort,
36 : SendPort exitPort,
37 : )
38 : _spawnScanIsolate;
39 :
40 : /// Checks if the single [port] is open or not for the [target].
41 : ///
42 : /// Returns an [ActiveHost] if the port is open, otherwise null.
43 : /// Throws if the port is out of range or the target cannot be resolved.
44 2 : @override
45 : Future<ActiveHost?> isOpen(
46 : String target,
47 : int port, {
48 : Duration timeout = const Duration(milliseconds: 2000),
49 : }) async {
50 4 : if (port < 0 || port > 65535) {
51 : throw 'Provide a valid port range between '
52 : '0 to 65535 or startPort < endPort is not true';
53 : }
54 2 : final List<InternetAddress> address = await InternetAddress.lookup(target);
55 2 : if (address.isNotEmpty) {
56 4 : final String hostAddress = address[0].address;
57 2 : return await connectToPort(
58 : address: hostAddress,
59 : port: port,
60 : timeout: timeout,
61 : );
62 : } else {
63 : throw 'Name can not be resolved';
64 : }
65 : }
66 :
67 : /// Scans only the ports listed in [portList] for a [target].
68 : ///
69 : /// Progress can be retrieved by [progressCallback].
70 : /// Tries connecting ports until [timeout] is reached for each port.
71 : /// If [resultsInAddressAscendingOrder] is false, results may be returned faster but not in ascending order.
72 : /// If [async] is true, scanning is performed in an isolate.
73 : /// [maxConcurrency] limits how many ports are probed at the same time.
74 4 : @override
75 : Stream<ActiveHost> customDiscover(
76 : String target, {
77 : List<int> portList = PortScannerService.commonPorts,
78 : ProgressCallback? progressCallback,
79 : Duration timeout = const Duration(milliseconds: 2000),
80 : bool resultsInAddressAscendingOrder = true,
81 : bool async = false,
82 : int maxConcurrency = PortScannerService.defaultMaxConcurrency,
83 : }) async* {
84 : if (!async) {
85 : // If async is false then run on main isolate
86 3 : yield* _customDiscover<ActiveHost>(
87 : target,
88 : portList: portList,
89 : progressCallback: progressCallback,
90 : timeout: timeout,
91 : resultsInAddressAscendingOrder: resultsInAddressAscendingOrder,
92 : maxConcurrency: maxConcurrency,
93 : );
94 : } else {
95 4 : final receivePort = ReceivePort();
96 4 : final errorPort = ReceivePort();
97 4 : final exitPort = ReceivePort();
98 : // An isolate that dies before sending 'Done' — an unresolvable target,
99 : // for instance — would otherwise leave this stream waiting forever.
100 5 : final errorSubscription = errorPort.listen((dynamic error) {
101 3 : receivePort.sendPort.send(<Object?>['runtimeError', error]);
102 : });
103 5 : final exitSubscription = exitPort.listen((dynamic _) {
104 3 : receivePort.sendPort.send(<Object?>['runtimeError', 'isolate exited']);
105 : });
106 : Isolate? isolate;
107 :
108 : try {
109 8 : isolate = await _spawnScanIsolate(
110 4 : _startSearchingPorts,
111 4 : receivePort.sendPort,
112 4 : errorPort.sendPort,
113 4 : exitPort.sendPort,
114 : );
115 :
116 8 : await for (final message in receivePort) {
117 4 : if (message is SendPort) {
118 6 : message.send(<dynamic>[
119 : target,
120 : portList,
121 : timeout,
122 3 : resultsInAddressAscendingOrder.toString(),
123 : maxConcurrency,
124 : ]);
125 4 : } else if (message is SendableActiveHost) {
126 : // Resolution is lazy on ActiveHost, so result creation stays cheap.
127 3 : yield ActiveHost.fromSendableActiveHost(
128 : sendableActiveHost: message,
129 : );
130 12 : } else if (message is List && message.first == 'progress') {
131 3 : progressCallback?.call((message[1] as num).toDouble());
132 6 : } else if (message is List && message.first == 'runtimeError') {
133 3 : throw Exception('Port scan isolate failed: ${message[1]}');
134 6 : } else if (message is String && message == 'Done') {
135 : break;
136 2 : } else if (message is String && message.startsWith('Error:')) {
137 1 : throw Exception(
138 3 : 'Port scan isolate failed: ${message.substring(6).trim()}',
139 : );
140 : }
141 : }
142 : } finally {
143 : // Also runs when the consumer cancels the stream early.
144 4 : await errorSubscription.cancel();
145 4 : await exitSubscription.cancel();
146 4 : errorPort.close();
147 4 : exitPort.close();
148 4 : isolate?.kill();
149 4 : receivePort.close();
150 : }
151 : }
152 : }
153 :
154 3 : @pragma('vm:entry-point')
155 : Future<void> _startSearchingPorts(SendPort sendPort) async {
156 3 : final port = ReceivePort();
157 6 : sendPort.send(port.sendPort);
158 :
159 6 : await for (final message in port) {
160 3 : if (message is List<dynamic>) {
161 : try {
162 3 : final String target = message[0] as String;
163 3 : final List<int> portList = message[1] as List<int>;
164 3 : final Duration timeout = message[2] as Duration;
165 6 : final bool resultsInAddressAscendingOrder = message[3] == "true";
166 3 : final int maxConcurrency = message[4] as int;
167 :
168 : double lastProgress = -1;
169 3 : final openPortsForTarget = _customDiscover<SendableActiveHost>(
170 : target,
171 : portList: portList,
172 : timeout: timeout,
173 : resultsInAddressAscendingOrder: resultsInAddressAscendingOrder,
174 : maxConcurrency: maxConcurrency,
175 3 : progressCallback: (double progress) {
176 : // Avoid flooding the main isolate with one message per port.
177 9 : if ((progress - lastProgress).abs() >= 1) {
178 : lastProgress = progress;
179 6 : sendPort.send(<dynamic>['progress', progress]);
180 : }
181 : },
182 : );
183 :
184 3 : await for (final SendableActiveHost activeHostFound
185 3 : in openPortsForTarget) {
186 3 : sendPort.send(activeHostFound);
187 : }
188 3 : sendPort.send('Done');
189 : } catch (error) {
190 2 : sendPort.send('Error: $error');
191 : }
192 : }
193 : }
194 : }
195 :
196 3 : Stream<T> _customDiscover<T>(
197 : String target, {
198 : List<int> portList = PortScannerService.commonPorts,
199 : ProgressCallback? progressCallback,
200 : Duration timeout = const Duration(milliseconds: 2000),
201 : bool resultsInAddressAscendingOrder = true,
202 : int maxConcurrency = PortScannerService.defaultMaxConcurrency,
203 : }) async* {
204 3 : final List<InternetAddress> address = await InternetAddress.lookup(target);
205 3 : if (address.isEmpty) {
206 : throw 'Name can not be resolved';
207 : }
208 6 : final String hostAddress = address[0].address;
209 : final List<int> ports = portList
210 12 : .where((int port) => port >= 0 && port <= 65535)
211 3 : .toList();
212 3 : if (ports.isEmpty) {
213 : return;
214 : }
215 :
216 : // A bounded pool keeps the number of open sockets low. Without it, a full
217 : // 0-65535 scan opens tens of thousands of sockets at once, hits the
218 : // file-descriptor limit and falls back to slow retries.
219 3 : final Stream<ConcurrentResult<T>> results = mapConcurrently<int, T>(
220 : ports,
221 3 : (int port) =>
222 3 : _connectToPort<T>(address: hostAddress, port: port, timeout: timeout),
223 : maxConcurrency: maxConcurrency,
224 3 : onCompleted: (int completed) =>
225 12 : progressCallback?.call(completed * 100 / ports.length),
226 : );
227 :
228 : if (!resultsInAddressAscendingOrder) {
229 2 : await for (final ConcurrentResult<T> result in results) {
230 : final T? value = result.value;
231 : if (value != null) {
232 : yield value;
233 : }
234 : }
235 : return;
236 : }
237 :
238 : // Results complete out of order; buffer them and emit by port index so the
239 : // ascending-order contract is preserved while still running in parallel.
240 3 : final Map<int, T?> pending = <int, T?>{};
241 : int nextIndex = 0;
242 6 : await for (final ConcurrentResult<T> result in results) {
243 3 : pending[result.index] = result.value;
244 3 : while (pending.containsKey(nextIndex)) {
245 3 : final T? value = pending.remove(nextIndex);
246 3 : nextIndex++;
247 : if (value != null) {
248 : yield value;
249 : }
250 : }
251 : }
252 : }
253 :
254 : /// Scans ports from [startPort] to [endPort] for a [target].
255 : ///
256 : /// Progress can be retrieved by [progressCallback].
257 : /// Tries connecting ports until [timeout] is reached for each port.
258 : /// If [resultsInAddressAscendingOrder] is false, results may be returned faster but not in ascending order.
259 : /// If [async] is true, scanning is performed in an isolate.
260 : /// [maxConcurrency] limits how many ports are probed at the same time.
261 2 : @override
262 : Stream<ActiveHost> scanPortsForSingleDevice(
263 : String target, {
264 : int startPort = PortScannerService.defaultStartPort,
265 : int endPort = PortScannerService.defaultEndPort,
266 : ProgressCallback? progressCallback,
267 : Duration timeout = const Duration(milliseconds: 2000),
268 : bool resultsInAddressAscendingOrder = true,
269 : bool async = false,
270 : int maxConcurrency = PortScannerService.defaultMaxConcurrency,
271 : }) async* {
272 2 : if (startPort < 0 ||
273 2 : endPort < 0 ||
274 2 : startPort > 65535 ||
275 2 : endPort > 65535 ||
276 2 : startPort > endPort) {
277 : throw 'Provide a valid port range between 0 to 65535 or startPort <'
278 : ' endPort is not true';
279 : }
280 :
281 2 : final List<int> portList = [];
282 :
283 4 : for (int i = startPort; i <= endPort; ++i) {
284 2 : portList.add(i);
285 : }
286 :
287 2 : yield* customDiscover(
288 : target,
289 : portList: portList,
290 : progressCallback: progressCallback,
291 : timeout: timeout,
292 : resultsInAddressAscendingOrder: resultsInAddressAscendingOrder,
293 : async: async,
294 : maxConcurrency: maxConcurrency,
295 : );
296 : }
297 :
298 : /// Attempts to connect to a specific [port] on an [address] within a [timeout].
299 : ///
300 : /// Returns an [ActiveHost] if the port is open, otherwise null. Used internally.
301 4 : @override
302 : Future<ActiveHost?> connectToPort({
303 : required String address,
304 : required int port,
305 : required Duration timeout,
306 : StreamController<ActiveHost>? activeHostsController,
307 : int recursionCount = 0,
308 : }) async {
309 4 : return await _connectToPort<ActiveHost>(
310 : address: address,
311 : port: port,
312 : timeout: timeout,
313 : activeHostsController: activeHostsController,
314 : );
315 : }
316 :
317 4 : Future<T?> _connectToPort<T>({
318 : required String address,
319 : required int port,
320 : required Duration timeout,
321 : StreamController<T>? activeHostsController,
322 : int recursionCount = 0,
323 : }) async {
324 : try {
325 4 : final Socket s = await Socket.connect(address, port, timeout: timeout);
326 4 : s.destroy();
327 :
328 4 : if (T == SendableActiveHost) {
329 3 : final SendableActiveHost sendableActiveHost = SendableActiveHost(
330 : address,
331 6 : openPorts: [OpenPort(port)],
332 : );
333 0 : if (activeHostsController != null && !activeHostsController.isClosed) {
334 0 : activeHostsController.add(sendableActiveHost as T);
335 : }
336 : return sendableActiveHost as T;
337 : }
338 4 : final ActiveHost activeHost = ActiveHost.buildWithAddress(
339 : address: address,
340 8 : openPorts: [OpenPort(port)],
341 : );
342 1 : if (activeHostsController != null && !activeHostsController.isClosed) {
343 1 : activeHostsController.add(activeHost as T);
344 : }
345 : return activeHost as T;
346 : } catch (e) {
347 4 : if (e is! SocketException) {
348 : rethrow;
349 : }
350 :
351 4 : if (isClosedPortError(e)) {
352 : return null;
353 : }
354 :
355 : // Error 23,24: Too many open files in system
356 : // e.osError can't be null here so `!` can be used
357 : // Do no more than 2 retries to prevent infinite loops
358 0 : if (recursionCount < 3 &&
359 0 : (e.osError!.errorCode == 23 || e.osError!.errorCode == 24)) {
360 : // Hotfix: Wait for the timeout (+ a little more) to complete and retry
361 : // -> Other connections must be closed now and the file handles available again
362 :
363 0 : await Future.delayed(timeout + const Duration(milliseconds: 250));
364 :
365 0 : return await _connectToPort<T>(
366 : address: address,
367 : port: port,
368 : timeout: timeout,
369 : activeHostsController: activeHostsController,
370 0 : recursionCount: recursionCount + 1,
371 : );
372 : }
373 :
374 : rethrow;
375 : }
376 : }
377 :
378 : /// Error codes that mean nothing is listening on the probed port, as opposed
379 : /// to the probe itself failing.
380 : ///
381 : /// A refused connect and a reset both answer "closed", but every platform
382 : /// numbers them differently: ECONNREFUSED is 111 on Linux/Android, 61 on
383 : /// Darwin and 10061 on Windows, and ECONNRESET is 104, 54 and 10054 for the
384 : /// same three. Darwin and Linux also answer RST instead of refusal when a
385 : /// port is rebound between the probe and the reply, so without the reset code
386 : /// a scan aborts on a port that is simply closed.
387 : static const Set<int> closedPortErrorCodes = <int>{
388 : 13,
389 : 49,
390 : 54, // ECONNRESET, Darwin
391 : 61, // ECONNREFUSED, Darwin
392 : 64,
393 : 65,
394 : 101,
395 : 104, // ECONNRESET, Linux
396 : 110,
397 : 111, // ECONNREFUSED, Linux
398 : 113,
399 : 10054, // WSAECONNRESET, Windows
400 : 10060,
401 : 10061, // WSAECONNREFUSED, Windows
402 : // WSAENOTCONN: Windows reports this when a pending connect is destroyed on
403 : // timeout, so the port never opened.
404 : 10057,
405 : 1225,
406 : };
407 :
408 : /// Whether [error] reports the probed port as closed rather than a failed
409 : /// probe; see [closedPortErrorCodes].
410 5 : static bool isClosedPortError(SocketException error) {
411 : // A socket error with no OS code behind it came from the Dart layer, for
412 : // example a connect destroyed once its timeout elapsed, so the port never
413 : // opened.
414 10 : final int? errorCode = error.osError?.errorCode;
415 : if (errorCode == null) {
416 : return true;
417 : }
418 5 : return closedPortErrorCodes.contains(errorCode) ||
419 3 : error.message.toLowerCase().contains('refused');
420 : }
421 : }
|